flux_desugar/desugar/
lift.rs

1//! "Lift" HIR types into  FHIR types.
2
3use flux_common::{bug, iter::IterExt, result::ErrorEmitter as _};
4use flux_errors::ErrorGuaranteed;
5use flux_middle::{
6    def_id::MaybeExternId,
7    fhir::{self, FhirId, FluxOwnerId},
8    try_alloc_slice,
9};
10use rustc_hir::{self as hir, FnHeader, def_id::LocalDefId};
11use rustc_span::Span;
12
13use super::{DesugarCtxt, RustItemCtxt};
14
15type Result<T = ()> = std::result::Result<T, ErrorGuaranteed>;
16
17impl<'genv> RustItemCtxt<'_, 'genv, '_> {
18    pub fn lift_generics(&mut self) -> fhir::Generics<'genv> {
19        let generics = self.genv.tcx().hir_get_generics(self.local_id()).unwrap();
20        self.lift_generics_inner(generics)
21    }
22
23    pub fn lift_generic_param(&mut self, param: &hir::GenericParam) -> fhir::GenericParam<'genv> {
24        let kind = match param.kind {
25            hir::GenericParamKind::Lifetime { .. } => fhir::GenericParamKind::Lifetime,
26            hir::GenericParamKind::Type { default, .. } => {
27                fhir::GenericParamKind::Type { default: default.map(|ty| self.lift_ty(ty)) }
28            }
29            hir::GenericParamKind::Const { ty, .. } => {
30                let ty = self.lift_ty(ty);
31                fhir::GenericParamKind::Const { ty }
32            }
33        };
34        fhir::GenericParam {
35            def_id: self.genv.maybe_extern_id(param.def_id),
36            name: param.name,
37            kind,
38        }
39    }
40
41    fn lift_generics_inner(&mut self, generics: &hir::Generics) -> fhir::Generics<'genv> {
42        let params = self.genv.alloc_slice_fill_iter(
43            generics
44                .params
45                .iter()
46                .map(|param| self.lift_generic_param(param)),
47        );
48
49        fhir::Generics { params, refinement_params: &[], predicates: None }
50    }
51
52    fn lift_generic_bound(
53        &mut self,
54        bound: &hir::GenericBound,
55    ) -> Result<fhir::GenericBound<'genv>> {
56        match bound {
57            hir::GenericBound::Trait(poly_trait_ref) => {
58                Ok(fhir::GenericBound::Trait(self.lift_poly_trait_ref(*poly_trait_ref)?))
59            }
60            hir::GenericBound::Outlives(lft) => {
61                let lft = self.lift_lifetime(lft);
62                Ok(fhir::GenericBound::Outlives(lft))
63            }
64            _ => Err(self.emit_unsupported(&format!("unsupported generic bound: `{bound:?}`"))),
65        }
66    }
67
68    fn lift_poly_trait_ref(
69        &mut self,
70        poly_trait_ref: hir::PolyTraitRef,
71    ) -> Result<fhir::PolyTraitRef<'genv>> {
72        let modifiers = match poly_trait_ref.modifiers {
73            rustc_hir::TraitBoundModifiers {
74                constness: rustc_hir::BoundConstness::Never,
75                polarity: rustc_hir::BoundPolarity::Positive,
76            } => fhir::TraitBoundModifier::None,
77            rustc_hir::TraitBoundModifiers {
78                constness: rustc_hir::BoundConstness::Never,
79                polarity: rustc_hir::BoundPolarity::Maybe(_),
80            } => fhir::TraitBoundModifier::Maybe,
81            _ => {
82                return Err(self.emit_unsupported(&format!(
83                    "unsupported trait modifiers: `{:?}`",
84                    poly_trait_ref.modifiers,
85                )));
86            }
87        };
88        let bound_generic_params = self.genv.alloc_slice_fill_iter(
89            poly_trait_ref
90                .bound_generic_params
91                .iter()
92                .map(|param| self.lift_generic_param(param)),
93        );
94        let trait_ref = self.lift_path(poly_trait_ref.trait_ref.path)?;
95        Ok(fhir::PolyTraitRef {
96            bound_generic_params,
97            refine_params: &[],
98            modifiers,
99            trait_ref,
100            span: poly_trait_ref.span,
101        })
102    }
103
104    fn lift_opaque_ty(&mut self, opaque_ty: &hir::OpaqueTy) -> Result<fhir::OpaqueTy<'genv>> {
105        let bounds =
106            try_alloc_slice!(self.genv, &opaque_ty.bounds, |bound| self.lift_generic_bound(bound))?;
107
108        Ok(fhir::OpaqueTy { def_id: MaybeExternId::Local(opaque_ty.def_id), bounds })
109    }
110
111    pub fn lift_fn_header(&mut self) -> FnHeader {
112        let hir_id = self.genv.tcx().local_def_id_to_hir_id(self.local_id());
113        self.genv
114            .tcx()
115            .hir_fn_sig_by_hir_id(hir_id)
116            .expect("item does not have a `FnDecl`")
117            .header
118    }
119
120    pub fn lift_fn_decl(&mut self) -> fhir::FnDecl<'genv> {
121        let hir_id = self.genv.tcx().local_def_id_to_hir_id(self.local_id());
122        let fn_sig = self
123            .genv
124            .tcx()
125            .hir_fn_sig_by_hir_id(hir_id)
126            .expect("item does not have a `FnDecl`");
127
128        self.lift_fn_decl_inner(fn_sig.span, fn_sig.decl)
129    }
130
131    fn lift_fn_decl_inner(&mut self, span: Span, decl: &hir::FnDecl) -> fhir::FnDecl<'genv> {
132        let inputs = self
133            .genv
134            .alloc_slice_fill_iter(decl.inputs.iter().map(|ty| self.lift_ty(ty)));
135
136        let output =
137            fhir::FnOutput { params: &[], ensures: &[], ret: self.lift_fn_ret_ty(&decl.output) };
138
139        fhir::FnDecl { requires: &[], inputs, output, span, lifted: true }
140    }
141
142    fn lift_fn_ret_ty(&mut self, ret_ty: &hir::FnRetTy) -> fhir::Ty<'genv> {
143        match ret_ty {
144            hir::FnRetTy::DefaultReturn(_) => {
145                let kind = fhir::TyKind::Tuple(&[]);
146                fhir::Ty { kind, span: ret_ty.span() }
147            }
148            hir::FnRetTy::Return(ty) => self.lift_ty(ty),
149        }
150    }
151
152    pub fn lift_type_alias(&mut self) -> fhir::Item<'genv> {
153        let item = self.genv.hir().expect_item(self.local_id());
154        let hir::ItemKind::TyAlias(ty, _) = item.kind else {
155            bug!("expected type alias");
156        };
157
158        let generics = self.lift_generics();
159        let ty = self.lift_ty(ty);
160        let ty_alias = fhir::TyAlias { index: None, ty, span: item.span, lifted: true };
161        fhir::Item { generics, kind: fhir::ItemKind::TyAlias(ty_alias), owner_id: self.owner }
162    }
163
164    pub fn lift_field_def(&mut self, field_def: &hir::FieldDef) -> fhir::FieldDef<'genv> {
165        let ty = self.lift_ty(field_def.ty);
166        fhir::FieldDef { ty, lifted: true }
167    }
168
169    pub fn lift_enum_variant(&mut self, variant: &hir::Variant) -> fhir::VariantDef<'genv> {
170        let item = self.genv.hir().expect_item(self.local_id());
171        let hir::ItemKind::Enum(_, generics) = &item.kind else { bug!("expected an enum") };
172
173        let fields = self.genv.alloc_slice_fill_iter(
174            variant
175                .data
176                .fields()
177                .iter()
178                .map(|field| self.lift_field_def(field)),
179        );
180
181        let ret = self.lift_variant_ret_inner(generics);
182
183        fhir::VariantDef {
184            def_id: variant.def_id,
185            params: &[],
186            fields,
187            ret,
188            span: variant.span,
189            lifted: true,
190        }
191    }
192
193    pub fn lift_variant_ret(&mut self) -> fhir::VariantRet<'genv> {
194        let item = self.genv.hir().expect_item(self.local_id());
195        let hir::ItemKind::Enum(_, generics) = &item.kind else { bug!("expected an enum") };
196        self.lift_variant_ret_inner(generics)
197    }
198
199    fn lift_variant_ret_inner(&mut self, generics: &hir::Generics) -> fhir::VariantRet<'genv> {
200        let kind = fhir::ExprKind::Record(&[]);
201        fhir::VariantRet {
202            enum_id: self.owner.resolved_id(),
203            idx: fhir::Expr {
204                kind,
205                fhir_id: self.next_fhir_id(),
206                span: generics.span.shrink_to_hi(),
207            },
208        }
209    }
210
211    pub fn lift_ty(&mut self, ty: &hir::Ty) -> fhir::Ty<'genv> {
212        let kind = match ty.kind {
213            hir::TyKind::Slice(ty) => {
214                let ty = self.lift_ty(ty);
215                let kind = fhir::BaseTyKind::Slice(self.genv.alloc(ty));
216                let bty = fhir::BaseTy { kind, fhir_id: self.next_fhir_id(), span: ty.span };
217                return fhir::Ty { kind: fhir::TyKind::BaseTy(bty), span: ty.span };
218            }
219            hir::TyKind::Array(ty, len) => {
220                let ty = self.lift_ty(ty);
221                fhir::TyKind::Array(self.genv.alloc(ty), self.lift_const_arg(len))
222            }
223            hir::TyKind::Ref(lft, mut_ty) => {
224                fhir::TyKind::Ref(self.lift_lifetime(lft), self.lift_mut_ty(mut_ty))
225            }
226            hir::TyKind::BareFn(bare_fn) => {
227                let bare_fn = self.lift_bare_fn(ty.span, bare_fn);
228                fhir::TyKind::BareFn(self.genv.alloc(bare_fn))
229            }
230            hir::TyKind::Never => fhir::TyKind::Never,
231            hir::TyKind::Tup(tys) => {
232                let tys = self
233                    .genv
234                    .alloc_slice_fill_iter(tys.iter().map(|ty| self.lift_ty(ty)));
235                fhir::TyKind::Tuple(tys)
236            }
237            hir::TyKind::Path(qpath) => {
238                match self.lift_qpath(qpath) {
239                    Ok(qpath) => {
240                        let bty = fhir::BaseTy::from_qpath(qpath, self.next_fhir_id());
241                        fhir::TyKind::BaseTy(bty)
242                    }
243                    Err(err) => fhir::TyKind::Err(err),
244                }
245            }
246            hir::TyKind::Ptr(mut_ty) => {
247                let ty = self.lift_ty(mut_ty.ty);
248                fhir::TyKind::RawPtr(self.genv.alloc(ty), mut_ty.mutbl)
249            }
250            hir::TyKind::OpaqueDef(opaque_ty) => {
251                match self.lift_opaque_ty(opaque_ty) {
252                    Ok(opaque_ty) => {
253                        let opaque_ty = self.insert_opaque_ty(opaque_ty);
254                        fhir::TyKind::OpaqueDef(opaque_ty)
255                    }
256                    Err(err) => fhir::TyKind::Err(err),
257                }
258            }
259            hir::TyKind::TraitObject(poly_traits, lt) => {
260                let poly_traits = try_alloc_slice!(self.genv, poly_traits, |poly_trait| {
261                    if poly_trait.modifiers != hir::TraitBoundModifiers::NONE {
262                        return Err(self.emit_unsupported(&format!(
263                            "unsupported type: `{}`",
264                            rustc_hir_pretty::ty_to_string(&self.genv.tcx(), ty)
265                        )));
266                    }
267                    self.lift_poly_trait_ref(*poly_trait)
268                });
269                match poly_traits {
270                    Ok(poly_traits) => {
271                        let lft = self.lift_lifetime(lt.pointer());
272                        fhir::TyKind::TraitObject(poly_traits, lft, lt.tag())
273                    }
274                    Err(err) => fhir::TyKind::Err(err),
275                }
276            }
277            _ => {
278                fhir::TyKind::Err(self.emit_unsupported(&format!(
279                    "unsupported type: `{}`",
280                    rustc_hir_pretty::ty_to_string(&self.genv.tcx(), ty)
281                )))
282            }
283        };
284        fhir::Ty { kind, span: ty.span }
285    }
286
287    fn lift_bare_fn(&mut self, span: Span, bare_fn: &hir::BareFnTy) -> fhir::BareFnTy<'genv> {
288        let generic_params = self.genv.alloc_slice_fill_iter(
289            bare_fn
290                .generic_params
291                .iter()
292                .map(|param| self.lift_generic_param(param)),
293        );
294        let decl = self.lift_fn_decl_inner(span, bare_fn.decl);
295        fhir::BareFnTy {
296            safety: bare_fn.safety,
297            abi: bare_fn.abi,
298            generic_params,
299            decl: self.genv.alloc(decl),
300            param_names: self.genv.alloc_slice(bare_fn.param_names),
301        }
302    }
303
304    fn lift_lifetime(&self, lft: &hir::Lifetime) -> fhir::Lifetime {
305        if let Some(resolved) = self.genv.tcx().named_bound_var(lft.hir_id) {
306            fhir::Lifetime::Resolved(resolved)
307        } else {
308            self.mk_lft_hole()
309        }
310    }
311
312    fn lift_mut_ty(&mut self, mut_ty: hir::MutTy) -> fhir::MutTy<'genv> {
313        let ty = self.lift_ty(mut_ty.ty);
314        fhir::MutTy { ty: self.genv.alloc(ty), mutbl: mut_ty.mutbl }
315    }
316
317    fn lift_qpath(&mut self, qpath: hir::QPath) -> Result<fhir::QPath<'genv>> {
318        match qpath {
319            hir::QPath::Resolved(qself, path) => {
320                let qself = if let Some(ty) = qself {
321                    let ty = self.lift_ty(ty);
322                    Some(self.genv.alloc(ty))
323                } else {
324                    None
325                };
326                let path = self.lift_path(path)?;
327                Ok(fhir::QPath::Resolved(qself, path))
328            }
329            hir::QPath::TypeRelative(qself, segment) => {
330                let qself = self.lift_ty(qself);
331                let segment = self.lift_path_segment(segment)?;
332                Ok(fhir::QPath::TypeRelative(self.genv.alloc(qself), self.genv.alloc(segment)))
333            }
334            hir::QPath::LangItem(_, _) => {
335                Err(self.emit_unsupported(&format!(
336                    "unsupported type: `{}`",
337                    rustc_hir_pretty::qpath_to_string(&self.genv.tcx(), &qpath)
338                )))
339            }
340        }
341    }
342
343    fn lift_path(&mut self, path: &hir::Path) -> Result<fhir::Path<'genv>> {
344        let Ok(res) = path.res.try_into() else {
345            return Err(self.emit_unsupported(&format!("unsupported res: `{:?}`", path.res)));
346        };
347        let segments =
348            try_alloc_slice!(self.genv, path.segments, |segment| self.lift_path_segment(segment))?;
349
350        Ok(fhir::Path { res, fhir_id: self.next_fhir_id(), segments, refine: &[], span: path.span })
351    }
352
353    fn lift_path_segment(
354        &mut self,
355        segment: &hir::PathSegment,
356    ) -> Result<fhir::PathSegment<'genv>> {
357        let Ok(res) = segment.res.try_into() else {
358            return Err(self.emit_unsupported(&format!("unsupported res: `{:?}`", segment.res)));
359        };
360        let (args, bindings) = {
361            match segment.args {
362                Some(args) => {
363                    (
364                        self.lift_generic_args(args.args)?,
365                        self.lift_assoc_item_constraints(args.constraints)?,
366                    )
367                }
368                None => ([].as_slice(), [].as_slice()),
369            }
370        };
371
372        Ok(fhir::PathSegment { res, ident: segment.ident, args, constraints: bindings })
373    }
374
375    fn lift_generic_args(
376        &mut self,
377        args: &[hir::GenericArg<'_>],
378    ) -> Result<&'genv [fhir::GenericArg<'genv>]> {
379        try_alloc_slice!(self.genv, args, |arg| {
380            match arg {
381                hir::GenericArg::Lifetime(lft) => {
382                    let lft = self.lift_lifetime(lft);
383                    Ok(fhir::GenericArg::Lifetime(lft))
384                }
385                hir::GenericArg::Type(ty) => {
386                    let ty = self.lift_ty(ty.as_unambig_ty());
387                    Ok(fhir::GenericArg::Type(self.genv.alloc(ty)))
388                }
389                hir::GenericArg::Const(const_arg) => {
390                    Ok(fhir::GenericArg::Const(self.lift_const_arg(const_arg.as_unambig_ct())))
391                }
392                hir::GenericArg::Infer(_) => {
393                    Err(self.emit_unsupported("unsupported inference generic argument"))
394                }
395            }
396        })
397    }
398
399    fn lift_assoc_item_constraints(
400        &mut self,
401        constraints: &[hir::AssocItemConstraint<'_>],
402    ) -> Result<&'genv [fhir::AssocItemConstraint<'genv>]> {
403        try_alloc_slice!(self.genv, constraints, |cstr| {
404            let hir::AssocItemConstraintKind::Equality { term } = cstr.kind else {
405                return Err(self.emit_unsupported("unsupported type binding"));
406            };
407            let hir::Term::Ty(term) = term else {
408                return Err(self.emit_unsupported("unsupported type binding"));
409            };
410            let kind = fhir::AssocItemConstraintKind::Equality { term: self.lift_ty(term) };
411            Ok(fhir::AssocItemConstraint { ident: cstr.ident, kind })
412        })
413    }
414
415    fn lift_const_arg(&mut self, const_arg: &hir::ConstArg) -> fhir::ConstArg {
416        fhir::ConstArg { kind: fhir::ConstArgKind::Infer, span: const_arg.span() }
417    }
418
419    #[track_caller]
420    fn emit_unsupported(&self, note: &str) -> ErrorGuaranteed {
421        let tcx = self.genv.tcx();
422        let local_id = self.owner.local_id().def_id;
423        let span = tcx.def_span(local_id);
424        let def_kind = tcx.def_descr(local_id.to_def_id());
425        self.emit(errors::UnsupportedHir { span, def_kind, note })
426    }
427
428    fn next_fhir_id(&self) -> FhirId {
429        FhirId {
430            owner: FluxOwnerId::Rust(self.owner.local_id()),
431            local_id: self.local_id_gen.fresh(),
432        }
433    }
434
435    fn local_id(&self) -> LocalDefId {
436        self.owner.local_id().def_id
437    }
438
439    fn lift_fn_sig(&mut self, fn_sig: hir::FnSig) -> fhir::FnSig<'genv> {
440        let decl = self.lift_fn_decl_inner(fn_sig.span, fn_sig.decl);
441        fhir::FnSig {
442            header: fn_sig.header,
443            qualifiers: &[],
444            reveals: &[],
445            decl: self.genv.alloc(decl),
446        }
447    }
448
449    pub fn lift_foreign_item(
450        &mut self,
451        foreign_item: hir::ForeignItem,
452    ) -> Result<fhir::ForeignItem<'genv>> {
453        let hir::ForeignItemKind::Fn(fnsig, _, _) = foreign_item.kind else {
454            return Err(self.emit_unsupported("Static and type in extern_item are not supported."));
455        };
456
457        let lifted_fnsig = self.lift_fn_sig(fnsig);
458        let fnsig = self.genv.alloc(lifted_fnsig);
459        let lifted_generics = self.lift_generics();
460        let generics = self.genv.alloc(lifted_generics);
461        let kind = fhir::ForeignItemKind::Fn(*fnsig, generics);
462
463        Ok(fhir::ForeignItem {
464            ident: foreign_item.ident,
465            kind,
466            owner_id: MaybeExternId::Local(foreign_item.owner_id),
467            span: foreign_item.span,
468        })
469    }
470}
471
472pub mod errors {
473    use flux_errors::E0999;
474    use flux_macros::Diagnostic;
475    use rustc_span::Span;
476
477    #[derive(Diagnostic)]
478    #[diag(desugar_unsupported_hir, code = E0999)]
479    #[note]
480    pub(super) struct UnsupportedHir<'a> {
481        #[primary_span]
482        #[label]
483        pub span: Span,
484        pub def_kind: &'static str,
485        pub note: &'a str,
486    }
487}