flux_desugar/
lib.rs

1//! Desugaring from types in [`flux_syntax::surface`] to types in [`flux_middle::fhir`]
2
3#![feature(rustc_private, min_specialization, box_patterns, never_type, unwrap_infallible)]
4
5extern crate rustc_data_structures;
6extern crate rustc_errors;
7
8extern crate rustc_hir;
9extern crate rustc_hir_pretty;
10extern crate rustc_middle;
11extern crate rustc_span;
12
13use desugar::RustItemCtxt;
14use flux_common::result::{ErrorCollector, ResultExt};
15use flux_macros::fluent_messages;
16use flux_syntax::surface;
17use itertools::Itertools as _;
18use rustc_data_structures::unord::UnordMap;
19
20fluent_messages! { "../locales/en-US.ftl" }
21
22mod desugar;
23mod errors;
24pub mod resolver;
25
26use flux_middle::{
27    ResolverOutput,
28    def_id::FluxLocalDefId,
29    fhir,
30    global_env::GlobalEnv,
31    queries::{Providers, QueryErr, QueryResult},
32    query_bug,
33};
34use rustc_errors::ErrorGuaranteed;
35use rustc_hir::OwnerId;
36use rustc_span::def_id::LocalDefId;
37
38use crate::desugar::FluxItemCtxt;
39
40type Result<T = ()> = std::result::Result<T, ErrorGuaranteed>;
41
42pub fn provide(providers: &mut Providers) {
43    providers.resolve_crate = resolver::resolve_crate;
44    providers.desugar = desugar;
45    providers.fhir_attr_map = fhir_attr_map;
46    providers.fhir_crate = desugar_crate;
47}
48
49pub fn desugar<'genv>(
50    genv: GlobalEnv<'genv, '_>,
51    def_id: LocalDefId,
52) -> QueryResult<UnordMap<LocalDefId, fhir::Node<'genv>>> {
53    if genv.ignored(def_id) {
54        return Err(QueryErr::Ignored { def_id: def_id.to_def_id() });
55    }
56
57    let cx = DesugarCtxt { genv, resolver_output: genv.resolve_crate() };
58    let specs = genv.collect_specs();
59    let owner_id = OwnerId { def_id };
60    let mut nodes = UnordMap::default();
61
62    let mut opaque_tys = Default::default();
63    let node = match genv.tcx().hir_node_by_def_id(def_id) {
64        rustc_hir::Node::Item(_) => {
65            let item = cx.with_rust_item_ctxt(owner_id, Some(&mut opaque_tys), |cx| {
66                match specs.get_item(owner_id) {
67                    Some(item) => cx.desugar_item(item),
68                    None => cx.lift_item(),
69                }
70            })?;
71            fhir::Node::Item(genv.alloc(item))
72        }
73        rustc_hir::Node::TraitItem(_) => {
74            let item = cx.with_rust_item_ctxt(owner_id, Some(&mut opaque_tys), |cx| {
75                match specs.get_trait_item(owner_id) {
76                    Some(item) => cx.desugar_trait_item(item),
77                    None => Ok(cx.lift_trait_item()),
78                }
79            })?;
80            fhir::Node::TraitItem(genv.alloc(item))
81        }
82        rustc_hir::Node::ImplItem(..) => {
83            let item = cx.with_rust_item_ctxt(owner_id, Some(&mut opaque_tys), |cx| {
84                match specs.get_impl_item(owner_id) {
85                    Some(item) => cx.desugar_impl_item(item),
86                    None => Ok(cx.lift_impl_item()),
87                }
88            })?;
89            fhir::Node::ImplItem(genv.alloc(item))
90        }
91        rustc_hir::Node::AnonConst(..) => fhir::Node::AnonConst,
92        rustc_hir::Node::Expr(..) => fhir::Node::Expr,
93        rustc_hir::Node::ForeignItem(foreign) => {
94            let item =
95                cx.with_rust_item_ctxt(owner_id, None, |cx| cx.lift_foreign_item(*foreign))?;
96            fhir::Node::ForeignItem(genv.alloc(item))
97        }
98        rustc_hir::Node::Ctor(rustc_hir::VariantData::Tuple(_, _, _)) => fhir::Node::Ctor,
99        node => {
100            if let Some(ident) = node.ident() {
101                return Err(query_bug!(def_id, "unsupported item {ident:?}"));
102            } else {
103                return Err(query_bug!(def_id, "unsupported item"));
104            }
105        }
106    };
107    nodes.insert(def_id, node);
108    nodes.extend(
109        opaque_tys
110            .into_iter()
111            .map(|opaque_ty| (opaque_ty.def_id.local_id(), fhir::Node::OpaqueTy(opaque_ty))),
112    );
113    Ok(nodes)
114}
115
116struct DesugarCtxt<'genv, 'tcx> {
117    genv: GlobalEnv<'genv, 'tcx>,
118    resolver_output: &'genv ResolverOutput,
119}
120
121impl<'genv, 'tcx> DesugarCtxt<'genv, 'tcx> {
122    fn with_rust_item_ctxt<'a, T>(
123        &'a self,
124        owner_id: OwnerId,
125        opaque_tys: Option<&'a mut Vec<&'genv fhir::OpaqueTy<'genv>>>,
126        f: impl FnOnce(&mut RustItemCtxt<'a, 'genv, 'tcx>) -> Result<T>,
127    ) -> Result<T> {
128        let owner_id = self
129            .genv
130            .maybe_extern_id(owner_id.def_id)
131            .map(|def_id| OwnerId { def_id });
132        RustItemCtxt::with(self.genv, owner_id, self.resolver_output, opaque_tys, f)
133    }
134}
135
136fn desugar_crate<'genv>(genv: GlobalEnv<'genv, '_>) -> fhir::FluxItems<'genv> {
137    match try_desugar_crate(genv) {
138        Ok(fhir) => fhir,
139        Err(err) => {
140            // There's too much code down the pipeline that relies on having the fhir, so we abort
141            // if there are any error during desugaring to avoid propagating the error back the query
142            // system. We should probably move away from desugaring the entire crate in one go and
143            // instead desugar items on demand so we can fail on a per item basis.
144            genv.sess().abort(err);
145        }
146    }
147}
148
149#[allow(clippy::disallowed_methods, reason = "Ths is the source of truth for FluxDefId's")]
150fn try_desugar_crate<'genv>(genv: GlobalEnv<'genv, '_>) -> Result<fhir::FluxItems<'genv>> {
151    let specs = genv.collect_specs();
152    let resolver_output = genv.resolve_crate();
153
154    let mut fhir = fhir::FluxItems::new();
155    let mut err: Option<ErrorGuaranteed> = None;
156    for (parent, items) in &specs.flux_items_by_parent {
157        for item in items {
158            let def_id = FluxLocalDefId::new(parent.def_id, item.name().name);
159            FluxItemCtxt::with(genv, resolver_output, def_id, |cx| {
160                fhir.items.insert(def_id, cx.desugar_flux_item(item));
161            })
162            .collect_err(&mut err);
163        }
164    }
165    err.into_result()?;
166
167    Ok(fhir)
168}
169
170fn fhir_attr_map<'genv>(genv: GlobalEnv<'genv, '_>, def_id: LocalDefId) -> fhir::AttrMap<'genv> {
171    let owner_id = OwnerId { def_id };
172    let specs = genv.collect_specs();
173
174    let (node_id, attrs) = if let Some(item) = specs.get_item(owner_id) {
175        (item.node_id, &item.attrs)
176    } else if let Some(impl_item) = specs.get_impl_item(owner_id) {
177        (impl_item.node_id, &impl_item.attrs)
178    } else if let Some(trait_item) = specs.get_trait_item(owner_id) {
179        (trait_item.node_id, &trait_item.attrs)
180    } else {
181        return fhir::AttrMap::default();
182    };
183
184    let resolver_output = genv.resolve_crate();
185    fhir::AttrMap {
186        attrs: genv.alloc_slice_fill_iter(
187            attrs
188                .iter()
189                .filter_map(|attr| {
190                    match *attr {
191                        surface::Attr::Trusted(trusted) => Some(fhir::Attr::Trusted(trusted)),
192                        surface::Attr::TrustedImpl(trusted) => {
193                            Some(fhir::Attr::TrustedImpl(trusted))
194                        }
195                        surface::Attr::Ignore(ignored) => Some(fhir::Attr::Ignore(ignored)),
196                        surface::Attr::ProvenExternally => Some(fhir::Attr::ProvenExternally),
197                        surface::Attr::ShouldFail => Some(fhir::Attr::ShouldFail),
198                        surface::Attr::InferOpts(opts) => Some(fhir::Attr::InferOpts(opts)),
199                        surface::Attr::Qualifiers(_) | surface::Attr::Reveal(_) => None,
200                    }
201                })
202                .collect_vec(),
203        ),
204        qualifiers: resolver_output
205            .qualifier_res_map
206            .get(&node_id)
207            .map_or(&[][..], Vec::as_slice),
208        reveals: resolver_output
209            .reveal_res_map
210            .get(&node_id)
211            .map_or(&[][..], Vec::as_slice),
212    }
213}