flux_desugar/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
//! Desugaring from types in [`flux_syntax::surface`] to types in [`flux_middle::fhir`]

#![feature(
    rustc_private,
    min_specialization,
    box_patterns,
    let_chains,
    never_type,
    unwrap_infallible
)]

extern crate rustc_data_structures;
extern crate rustc_errors;

extern crate rustc_hir;
extern crate rustc_hir_pretty;
extern crate rustc_middle;
extern crate rustc_span;

use desugar::RustItemCtxt;
use flux_common::{
    bug,
    result::{ErrorCollector, ResultExt},
    span_bug,
};
use flux_macros::fluent_messages;
use rustc_data_structures::unord::UnordMap;

fluent_messages! { "../locales/en-US.ftl" }

mod desugar;
mod errors;
pub mod resolver;

use flux_middle::{
    ResolverOutput, Specs,
    def_id::FluxLocalDefId,
    fhir,
    global_env::GlobalEnv,
    queries::{Providers, QueryErr, QueryResult},
};
use flux_syntax::surface;
use rustc_errors::ErrorGuaranteed;
use rustc_hir::{self as hir, OwnerId};
use rustc_span::def_id::LocalDefId;

type Result<T = ()> = std::result::Result<T, ErrorGuaranteed>;

pub fn provide(providers: &mut Providers) {
    providers.resolve_crate = resolver::resolve_crate;
    providers.desugar = desugar;
    providers.fhir_crate = desugar_crate;
}

pub fn desugar<'genv>(
    genv: GlobalEnv<'genv, '_>,
    def_id: LocalDefId,
) -> QueryResult<UnordMap<LocalDefId, fhir::Node<'genv>>> {
    if genv.ignored(def_id) {
        return Err(QueryErr::Ignored { def_id: def_id.to_def_id() });
    }

    let cx = DesugarCtxt { genv, resolver_output: genv.resolve_crate() };
    let specs = genv.collect_specs();
    let owner_id = OwnerId { def_id };
    let mut nodes = UnordMap::default();

    match genv.tcx().hir_node_by_def_id(def_id) {
        rustc_hir::Node::Item(item) => {
            match item.kind {
                hir::ItemKind::Fn { .. } => {
                    let fn_spec = specs.fn_sigs.get(&owner_id).unwrap();
                    let mut opaque_tys = Default::default();
                    let item = cx.with_rust_item_ctxt(owner_id, Some(&mut opaque_tys), |cx| {
                        cx.desugar_item_fn(fn_spec)
                    })?;
                    nodes.extend(opaque_tys.into_iter().map(|opaque_ty| {
                        (opaque_ty.def_id.local_id(), fhir::Node::OpaqueTy(opaque_ty))
                    }));
                    nodes.insert(def_id, fhir::Node::Item(genv.alloc(item)));
                }
                hir::ItemKind::TyAlias(..) => {
                    let ty_alias = specs.ty_aliases[&owner_id].as_ref();
                    nodes.insert(
                        def_id,
                        fhir::Node::Item(genv.alloc(cx.with_rust_item_ctxt(
                            owner_id,
                            None,
                            |cx| Ok(cx.desugar_type_alias(ty_alias)),
                        )?)),
                    );
                }

                hir::ItemKind::Enum(..) => {
                    let enum_def = &specs.enums[&owner_id];
                    nodes.insert(
                        def_id,
                        fhir::Node::Item(genv.alloc(cx.with_rust_item_ctxt(
                            owner_id,
                            None,
                            |cx| cx.desugar_enum_def(enum_def),
                        )?)),
                    );
                }
                hir::ItemKind::Union(..) => {
                    let union_def = &specs.structs[&owner_id];
                    nodes.insert(
                        def_id,
                        fhir::Node::Item(genv.alloc(cx.with_rust_item_ctxt(
                            owner_id,
                            None,
                            |cx| Ok(cx.desugar_struct_def(union_def)),
                        )?)),
                    );
                }
                hir::ItemKind::Struct(..) => {
                    let struct_def = &specs.structs[&owner_id];
                    nodes.insert(
                        def_id,
                        fhir::Node::Item(genv.alloc(cx.with_rust_item_ctxt(
                            owner_id,
                            None,
                            |cx| Ok(cx.desugar_struct_def(struct_def)),
                        )?)),
                    );
                }
                hir::ItemKind::Trait(..) => {
                    let trait_ = &specs.traits[&owner_id];
                    nodes.insert(
                        def_id,
                        fhir::Node::Item(genv.alloc(cx.with_rust_item_ctxt(
                            owner_id,
                            None,
                            |cx| Ok(cx.desugar_trait(trait_)),
                        )?)),
                    );
                }
                hir::ItemKind::Impl(..) => {
                    let impl_ = &specs.impls[&owner_id];
                    nodes.insert(
                        def_id,
                        fhir::Node::Item(genv.alloc(cx.with_rust_item_ctxt(
                            owner_id,
                            None,
                            |cx| Ok(cx.desugar_impl(impl_)),
                        )?)),
                    );
                }
                hir::ItemKind::Const(..) => {
                    let constant_ = match specs.constants.get(&owner_id) {
                        Some(constant_) => constant_,
                        None => &surface::ConstantInfo { expr: None },
                    };

                    nodes.insert(
                        def_id,
                        fhir::Node::Item(genv.alloc(cx.with_rust_item_ctxt(
                            owner_id,
                            None,
                            |cx| Ok(cx.desugar_const(constant_)),
                        )?)),
                    );
                }
                _ => span_bug!(item.span, "unsupported item"),
            }
        }
        rustc_hir::Node::TraitItem(trait_item) => {
            match trait_item.kind {
                rustc_hir::TraitItemKind::Fn(..) => {
                    let fn_spec = specs.fn_sigs.get(&owner_id).unwrap();
                    let mut opaque_tys = Default::default();
                    let item = cx.with_rust_item_ctxt(owner_id, Some(&mut opaque_tys), |cx| {
                        cx.desugar_trait_fn(fn_spec)
                    })?;
                    nodes.extend(opaque_tys.into_iter().map(|opaque_ty| {
                        (opaque_ty.def_id.local_id(), fhir::Node::OpaqueTy(opaque_ty))
                    }));
                    nodes.insert(def_id, fhir::Node::TraitItem(genv.alloc(item)));
                }
                rustc_hir::TraitItemKind::Type(..) => {
                    let item = cx.with_rust_item_ctxt(owner_id, None, |cx| {
                        Ok(cx.desugar_trait_assoc_ty())
                    })?;
                    nodes.insert(owner_id.def_id, fhir::Node::TraitItem(genv.alloc(item)));
                }
                rustc_hir::TraitItemKind::Const(..) => {
                    nodes.insert(
                        def_id,
                        fhir::Node::TraitItem(genv.alloc(cx.with_rust_item_ctxt(
                            owner_id,
                            None,
                            |cx| Ok(cx.desugar_trait_const()),
                        )?)),
                    );
                }
            }
        }
        rustc_hir::Node::ImplItem(impl_item) => {
            match &impl_item.kind {
                rustc_hir::ImplItemKind::Fn(..) => {
                    let fn_spec = specs.fn_sigs.get(&owner_id).unwrap();
                    let mut opaque_tys = Default::default();
                    let item = cx.with_rust_item_ctxt(owner_id, Some(&mut opaque_tys), |cx| {
                        cx.desugar_impl_fn(fn_spec)
                    })?;
                    nodes.extend(opaque_tys.into_iter().map(|opaque_ty| {
                        (opaque_ty.def_id.local_id(), fhir::Node::OpaqueTy(opaque_ty))
                    }));
                    nodes.insert(def_id, fhir::Node::ImplItem(genv.alloc(item)));
                }
                rustc_hir::ImplItemKind::Type(..) => {
                    let item = cx
                        .with_rust_item_ctxt(owner_id, None, |cx| Ok(cx.desugar_impl_assoc_ty()))?;
                    nodes.insert(owner_id.def_id, fhir::Node::ImplItem(genv.alloc(item)));
                }
                rustc_hir::ImplItemKind::Const(..) => {
                    nodes.insert(
                        def_id,
                        fhir::Node::ImplItem(genv.alloc(cx.with_rust_item_ctxt(
                            owner_id,
                            None,
                            |cx| Ok(cx.desugar_impl_const()),
                        )?)),
                    );
                }
            }
        }
        rustc_hir::Node::AnonConst(..) => {
            nodes.insert(def_id, fhir::Node::AnonConst);
        }
        rustc_hir::Node::ForeignItem(foreign) => {
            let foreign_item = fhir::Node::ForeignItem(genv.alloc(cx.with_rust_item_ctxt(
                owner_id,
                None,
                |cx| cx.desugar_foreign_item(*foreign),
            )?));
            nodes.insert(def_id, foreign_item);
        }
        node => {
            if let Some(ident) = node.ident() {
                span_bug!(ident.span, "unsupported node: {node:?}");
            } else {
                bug!("unsupported node: {node:?}");
            }
        }
    }
    Ok(nodes)
}

struct DesugarCtxt<'genv, 'tcx> {
    genv: GlobalEnv<'genv, 'tcx>,
    resolver_output: &'genv ResolverOutput,
}

impl<'genv, 'tcx> DesugarCtxt<'genv, 'tcx> {
    fn with_rust_item_ctxt<'a, T>(
        &'a self,
        owner_id: OwnerId,
        opaque_tys: Option<&'a mut Vec<&'genv fhir::OpaqueTy<'genv>>>,
        f: impl FnOnce(&mut RustItemCtxt<'a, 'genv, 'tcx>) -> Result<T>,
    ) -> Result<T> {
        let owner_id = self
            .genv
            .maybe_extern_id(owner_id.def_id)
            .map(|def_id| OwnerId { def_id });
        RustItemCtxt::with(self.genv, owner_id, self.resolver_output, opaque_tys, f)
    }
}

fn desugar_crate<'genv>(genv: GlobalEnv<'genv, '_>) -> fhir::FluxItems<'genv> {
    match try_desugar_crate(genv) {
        Ok(fhir) => fhir,
        Err(err) => {
            // There's too much code down the pipeline that relies on having the fhir, so we abort
            // if there are any error during desugaring to avoid propagating the error back the query
            // system. We should probably move away from desugaring the entire crate in one go and
            // instead desugar items on demand so we can fail on a per item basis.
            genv.sess().abort(err);
        }
    }
}

fn try_desugar_crate<'genv>(genv: GlobalEnv<'genv, '_>) -> Result<fhir::FluxItems<'genv>> {
    let specs = genv.collect_specs();
    let fhir = fhir::FluxItems::new();
    let resolver_output = genv.resolve_crate();
    let mut cx = CrateDesugar::new(genv, fhir, resolver_output);
    cx.desugar_flux_items(specs);

    cx.err.into_result()?;
    Ok(cx.fhir)
}

struct CrateDesugar<'genv, 'tcx> {
    genv: GlobalEnv<'genv, 'tcx>,
    fhir: fhir::FluxItems<'genv>,
    resolver_output: &'genv ResolverOutput,
    err: Option<ErrorGuaranteed>,
}

impl<'genv, 'tcx> CrateDesugar<'genv, 'tcx> {
    fn new(
        genv: GlobalEnv<'genv, 'tcx>,
        fhir: fhir::FluxItems<'genv>,
        resolver_output: &'genv ResolverOutput,
    ) -> Self {
        Self { genv, fhir, resolver_output, err: None }
    }
}

impl CrateDesugar<'_, '_> {
    #[allow(clippy::disallowed_methods, reason = "`flux_items_by_parent` is the source of truth")]
    fn desugar_flux_items(&mut self, specs: &Specs) {
        for (parent, items) in &specs.flux_items_by_parent {
            for item in items {
                let def_id = FluxLocalDefId::new(parent.def_id, item.name().name);
                match item {
                    surface::Item::Qualifier(qual) => {
                        self.desugar_qualifier(def_id, qual)
                            .collect_err(&mut self.err);
                    }
                    surface::Item::FuncDef(defn) => {
                        self.desugar_func_defn(def_id, defn)
                            .collect_err(&mut self.err);
                    }
                    surface::Item::SortDecl(_) => {}
                }
            }
        }
    }

    fn desugar_func_defn(&mut self, def_id: FluxLocalDefId, func: &surface::SpecFunc) -> Result {
        let func = desugar::desugar_spec_func(self.genv, self.resolver_output, def_id, func)?;
        self.fhir
            .items
            .insert(def_id, fhir::FluxItem::Func(self.genv.alloc(func)));
        Ok(())
    }

    fn desugar_qualifier(
        &mut self,
        def_id: FluxLocalDefId,
        qualifier: &surface::Qualifier,
    ) -> Result {
        let qualifier =
            desugar::desugar_qualifier(self.genv, self.resolver_output, def_id, qualifier)?;
        self.fhir
            .items
            .insert(def_id, fhir::FluxItem::Qualifier(self.genv.alloc(qualifier)));
        Ok(())
    }
}