Skip to main content

flux_middle/
queries.rs

1use std::{
2    cell::{OnceCell, RefCell},
3    rc::Rc,
4};
5
6use flux_arc_interner::List;
7use flux_common::{bug, tracked_span_bug};
8use flux_config as config;
9use flux_errors::{E0999, ErrorGuaranteed};
10use flux_macros::msg;
11use flux_rustc_bridge::{
12    self, def_id_to_string,
13    lowering::{self, Lower, UnsupportedErr},
14    mir::{self},
15    ty,
16};
17use flux_syntax::{surface, symbols::sym};
18use itertools::Itertools;
19use rustc_attr_ir::LangItem;
20use rustc_data_structures::unord::{ExtendUnord, UnordMap, UnordSet};
21use rustc_errors::{DiagMessage, Diagnostic};
22use rustc_hir::{
23    def::DefKind,
24    def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId},
25};
26use rustc_index::IndexVec;
27use rustc_macros::{Decodable, Encodable};
28use rustc_span::{DUMMY_SP, Span, Symbol};
29
30use crate::{
31    PanicSpec,
32    def_id::{FluxDefId, FluxId, MaybeExternId, ResolvedDefId},
33    dep_graph::{CallGraph, NodeKey},
34    fhir,
35    global_env::GlobalEnv,
36    rty::{
37        self, AliasReft, Expr, GenericArg,
38        fold::TypeFoldable,
39        refining::{self, Refine, Refiner, refine_generic_param_def},
40    },
41};
42
43type Cache<K, V> = RefCell<UnordMap<K, V>>;
44
45pub type QueryResult<T = ()> = Result<T, QueryErr>;
46
47/// An error produced by a query.
48///
49/// We make a distinction between errors reported at def-site and errors reported at use-site.
50///
51/// For most errors reported at the def-site of an item, it makes little sense to check the definition
52/// of dependent items. For example, if a function signature is ill-formed, checking the body of another
53/// function that calls it, can produce confusing errors. In some cases, we can even fail to produce
54/// a signature for a function in which case we can't even check its call sites. For these cases, we
55/// emit an error at the definition site and return a [`QueryErr::Emitted`]. When checking a dependent,
56/// we detect this and early return without reporting any errors at the use-site.
57///
58/// Other errors are better reported at the use-site. For example, if some code calls a function from
59/// an external crate that has unsupported features, we ought to report the error at the call-site,
60/// because it would be confusing to only mention the definition of the external function without
61/// showing which part of the code is calling it. To attach a span to an error one can use [`QueryErr::at`]
62/// to get a [`QueryErrAt`].
63///
64/// Both [`QueryErr`] and [`QueryErrAt`] implement [`Diagnostic`]. The implementation for [`QueryErr`]
65/// reports the error at the definition site, while the implementation for [`QueryErrAt`] reports it at
66/// the (attached) use-site span. This allows us to play a bit lose because we can emit an error without
67/// attaching a span, but this means we may forget to attach spans at some places. We should consider
68/// not implementing [`Diagnostic`] for [`QueryErr`] such that we always make the distinction between
69/// use-site and def-site explicit, e.g., we could have methods `QueryErr::at_use_site` and
70/// `QueryErr::at_def_site` returning types with different implementations of [`Diagnostic`].
71#[derive(Debug, Clone, Encodable, Decodable)]
72pub enum QueryErr {
73    Unsupported {
74        def_id: DefId,
75        err: UnsupportedErr,
76    },
77    Ignored {
78        def_id: DefId,
79    },
80    InvalidGenericArg {
81        def_id: DefId,
82    },
83    MissingAssocReft {
84        impl_id: DefId,
85        trait_id: DefId,
86        name: Symbol,
87    },
88    /// An operation tried to access the internals of an opaque struct.
89    OpaqueStruct {
90        struct_id: DefId,
91    },
92    /// Used to report bugs, typically this means executing an arm in a match we thought it was
93    /// unreachable. Use this instead of panicking if it is easy to return a [`QueryErr`]. Use
94    /// [`QueryErr::bug`] or [`crate::query_bug!`] to construct this variant to track source location.
95    Bug {
96        def_id: Option<DefId>,
97        location: String,
98        msg: String,
99    },
100    Emitted(ErrorGuaranteed),
101    /// A definition from another crate was used but not explicitly included
102    NotIncluded {
103        def_id: DefId,
104    },
105}
106
107#[macro_export]
108macro_rules! query_bug {
109    ($fmt:literal $(,$args:expr)* $(,)?) => {
110        $crate::queries::QueryErr::bug(None, format_args!($fmt, $($args),*))
111    };
112    ($def_id:expr, $fmt:literal $(,$args:expr)* $(,)? ) => {{
113        $crate::queries::QueryErr::bug(Some($def_id.into()), format_args!($fmt, $($args),*))
114    }};
115}
116
117impl QueryErr {
118    pub fn unsupported(def_id: DefId, err: UnsupportedErr) -> Self {
119        QueryErr::Unsupported { def_id, err }
120    }
121
122    #[track_caller]
123    pub fn bug(def_id: Option<DefId>, msg: impl ToString) -> Self {
124        QueryErr::Bug {
125            def_id,
126            location: format!("{}", std::panic::Location::caller()),
127            msg: msg.to_string(),
128        }
129    }
130
131    pub fn at(self, cx: impl Into<ErrCtxt>) -> QueryErrAt {
132        QueryErrAt { cx: cx.into(), err: self }
133    }
134}
135
136/// A [`QueryErr`] with extra context information
137pub struct QueryErrAt {
138    cx: ErrCtxt,
139    err: QueryErr,
140}
141
142/// The "use site" context in which an error is reported
143#[derive(Clone, Copy)]
144pub enum ErrCtxt {
145    /// The error was triggered when checking a function body. The `Span` is the span in
146    /// the mir associated with the error. The `LocalDefId` is the id of the function.
147    FnCheck(Span, LocalDefId),
148    /// A miscellaneous context for which we only have a span
149    Misc(Span),
150}
151
152impl From<Span> for ErrCtxt {
153    fn from(v: Span) -> Self {
154        Self::Misc(v)
155    }
156}
157
158impl ErrCtxt {
159    fn span(self) -> Span {
160        match self {
161            ErrCtxt::Misc(span) => span,
162            ErrCtxt::FnCheck(span, _) => span,
163        }
164    }
165}
166
167pub struct Providers {
168    pub collect_specs: fn(GlobalEnv) -> crate::Specs,
169    pub resolve_crate: fn(GlobalEnv) -> crate::ResolverOutput,
170    pub desugar: for<'genv> fn(
171        GlobalEnv<'genv, '_>,
172        LocalDefId,
173    ) -> QueryResult<UnordMap<LocalDefId, fhir::Node<'genv>>>,
174    pub fhir_attr_map: for<'genv> fn(GlobalEnv<'genv, '_>, LocalDefId) -> fhir::AttrMap<'genv>,
175    pub fhir_crate: for<'genv> fn(GlobalEnv<'genv, '_>) -> fhir::FluxItems<'genv>,
176    pub qualifiers: fn(GlobalEnv) -> QueryResult<Vec<rty::Qualifier>>,
177    pub axioms: fn(GlobalEnv) -> QueryResult<Vec<rty::Axiom>>,
178    pub prim_rel: fn(GlobalEnv) -> QueryResult<UnordMap<rty::BinOp, rty::PrimRel>>,
179    pub spec_funcs: fn(GlobalEnv) -> rty::SpecFuncs,
180    pub func_sort: fn(GlobalEnv, FluxId<MaybeExternId>) -> rty::PolyFuncSort,
181    pub func_span: fn(GlobalEnv, FluxId<MaybeExternId>) -> Span,
182    pub adt_sort_def_of: fn(GlobalEnv, MaybeExternId) -> QueryResult<rty::AdtSortDef>,
183    pub check_wf: fn(GlobalEnv, LocalDefId) -> QueryResult<Rc<rty::WfckResults>>,
184    pub late_bound_refinement_params:
185        for<'genv> fn(GlobalEnv<'genv, '_>, LocalDefId) -> QueryResult<&'genv [fhir::ParamId]>,
186    pub adt_def: fn(GlobalEnv, MaybeExternId) -> QueryResult<rty::AdtDef>,
187    pub invariants_of: fn(GlobalEnv, MaybeExternId) -> rty::EarlyBinder<List<rty::Invariant>>,
188    pub constant_info: fn(GlobalEnv, MaybeExternId) -> QueryResult<rty::ConstantInfo>,
189    pub static_info: fn(GlobalEnv, MaybeExternId) -> QueryResult<rty::Ty>,
190    pub type_of: fn(GlobalEnv, MaybeExternId) -> QueryResult<rty::EarlyBinder<rty::TyOrCtor>>,
191    pub variants_of: fn(
192        GlobalEnv,
193        MaybeExternId,
194    ) -> QueryResult<rty::Opaqueness<rty::EarlyBinder<rty::PolyVariants>>>,
195    pub fn_sig: fn(GlobalEnv, MaybeExternId) -> QueryResult<rty::EarlyBinder<rty::PolyFnSig>>,
196    pub generics_of: fn(GlobalEnv, MaybeExternId) -> QueryResult<rty::Generics>,
197    pub refinement_generics_of:
198        fn(GlobalEnv, MaybeExternId) -> QueryResult<rty::EarlyBinder<rty::RefinementGenerics>>,
199    pub predicates_of:
200        fn(GlobalEnv, MaybeExternId) -> QueryResult<rty::EarlyBinder<rty::GenericPredicates>>,
201    pub assoc_refinements_of: fn(GlobalEnv, MaybeExternId) -> QueryResult<rty::AssocRefinements>,
202    pub sort_of_assoc_reft:
203        fn(GlobalEnv, FluxId<MaybeExternId>) -> QueryResult<rty::EarlyBinder<rty::FuncSort>>,
204    pub assoc_refinement_body:
205        fn(GlobalEnv, FluxId<MaybeExternId>) -> QueryResult<rty::EarlyBinder<rty::Lambda>>,
206    #[allow(clippy::type_complexity)]
207    pub default_assoc_refinement_body:
208        fn(GlobalEnv, FluxId<MaybeExternId>) -> QueryResult<Option<rty::EarlyBinder<rty::Lambda>>>,
209    pub item_bounds:
210        fn(GlobalEnv, MaybeExternId) -> QueryResult<rty::EarlyBinder<List<rty::Clause>>>,
211    pub sort_decl_param_count: fn(GlobalEnv, FluxId<MaybeExternId>) -> usize,
212    pub call_graph: for<'genv, 'tcx> fn(GlobalEnv<'genv, 'tcx>) -> CallGraph<'tcx>,
213    pub inferred_no_panic:
214        for<'genv, 'tcx> fn(GlobalEnv<'genv, 'tcx>) -> UnordMap<NodeKey<'tcx>, PanicSpec>,
215}
216
217macro_rules! empty_query {
218    () => {
219        flux_common::bug!("query not provided")
220    };
221}
222
223impl Default for Providers {
224    fn default() -> Self {
225        Self {
226            collect_specs: |_| empty_query!(),
227            resolve_crate: |_| empty_query!(),
228            desugar: |_, _| empty_query!(),
229            fhir_attr_map: |_, _| empty_query!(),
230            fhir_crate: |_| empty_query!(),
231            spec_funcs: |_| empty_query!(),
232            func_sort: |_, _| empty_query!(),
233            func_span: |_, _| empty_query!(),
234            qualifiers: |_| empty_query!(),
235            axioms: |_| empty_query!(),
236            prim_rel: |_| empty_query!(),
237            adt_sort_def_of: |_, _| empty_query!(),
238            check_wf: |_, _| empty_query!(),
239            late_bound_refinement_params: |_, _| empty_query!(),
240            adt_def: |_, _| empty_query!(),
241            invariants_of: |_, _| empty_query!(),
242            type_of: |_, _| empty_query!(),
243            variants_of: |_, _| empty_query!(),
244            fn_sig: |_, _| empty_query!(),
245            generics_of: |_, _| empty_query!(),
246            refinement_generics_of: |_, _| empty_query!(),
247            predicates_of: |_, _| empty_query!(),
248            assoc_refinements_of: |_, _| empty_query!(),
249            assoc_refinement_body: |_, _| empty_query!(),
250            default_assoc_refinement_body: |_, _| empty_query!(),
251            sort_of_assoc_reft: |_, _| empty_query!(),
252            item_bounds: |_, _| empty_query!(),
253            constant_info: |_, _| empty_query!(),
254            static_info: |_, _| empty_query!(),
255            sort_decl_param_count: |_, _| empty_query!(),
256            call_graph: |_| empty_query!(),
257            inferred_no_panic: |_| empty_query!(),
258        }
259    }
260}
261
262pub struct Queries<'genv, 'tcx> {
263    pub(crate) providers: Providers,
264    /// The set of def ids that have been queried.
265    ///
266    /// After checking the crate, this set contains all items transitively reached from the set
267    /// of explicitly included items. We use this set to avoid triggering queries for items not
268    /// included when encoding metadata.
269    queried_def_ids: RefCell<UnordSet<DefId>>,
270    mir: Cache<LocalDefId, QueryResult<Rc<mir::BodyRoot<'tcx>>>>,
271    collect_specs: OnceCell<crate::Specs>,
272    resolve_crate: OnceCell<crate::ResolverOutput>,
273    flux_module_children: Cache<DefId, &'genv [fhir::FluxModChild]>,
274    desugar: Cache<LocalDefId, QueryResult<fhir::Node<'genv>>>,
275    fhir_attr_map: Cache<LocalDefId, fhir::AttrMap<'genv>>,
276    fhir_crate: OnceCell<fhir::FluxItems<'genv>>,
277    lower_generics_of: Cache<DefId, ty::Generics<'tcx>>,
278    lower_predicates_of: Cache<DefId, QueryResult<ty::GenericPredicates>>,
279    lower_type_of: Cache<DefId, QueryResult<ty::EarlyBinder<ty::Ty>>>,
280    lower_fn_sig: Cache<DefId, QueryResult<ty::EarlyBinder<ty::PolyFnSig>>>,
281    spec_funcs: Cache<CrateNum, Rc<rty::SpecFuncs>>,
282    inlined_body: Cache<FluxDefId, rty::Binder<rty::Expr>>,
283    func_sort: Cache<FluxDefId, rty::PolyFuncSort>,
284    func_span: Cache<FluxDefId, Span>,
285    qualifiers: OnceCell<QueryResult<Vec<rty::Qualifier>>>,
286    axioms: OnceCell<QueryResult<Vec<rty::Axiom>>>,
287    prim_rel: OnceCell<QueryResult<UnordMap<rty::BinOp, rty::PrimRel>>>,
288    adt_sort_def_of: Cache<DefId, QueryResult<rty::AdtSortDef>>,
289    check_wf: Cache<LocalDefId, QueryResult<Rc<rty::WfckResults>>>,
290    late_bound_refinement_params: Cache<LocalDefId, QueryResult<&'genv [fhir::ParamId]>>,
291    adt_def: Cache<DefId, QueryResult<rty::AdtDef>>,
292    invariants_of: Cache<DefId, rty::EarlyBinder<List<rty::Invariant>>>,
293    constant_info: Cache<DefId, QueryResult<rty::ConstantInfo>>,
294    static_info: Cache<DefId, QueryResult<rty::Ty>>,
295    generics_of: Cache<DefId, QueryResult<rty::Generics>>,
296    refinement_generics_of: Cache<DefId, QueryResult<rty::EarlyBinder<rty::RefinementGenerics>>>,
297    predicates_of: Cache<DefId, QueryResult<rty::EarlyBinder<rty::GenericPredicates>>>,
298    assoc_refinements_of: Cache<DefId, QueryResult<rty::AssocRefinements>>,
299    assoc_refinement_body: Cache<FluxDefId, QueryResult<rty::EarlyBinder<rty::Lambda>>>,
300    default_assoc_refinement_body:
301        Cache<FluxDefId, QueryResult<Option<rty::EarlyBinder<rty::Lambda>>>>,
302    sort_of_assoc_reft: Cache<FluxDefId, QueryResult<rty::EarlyBinder<rty::FuncSort>>>,
303    item_bounds: Cache<DefId, QueryResult<rty::EarlyBinder<List<rty::Clause>>>>,
304    type_of: Cache<DefId, QueryResult<rty::EarlyBinder<rty::TyOrCtor>>>,
305    variants_of: Cache<DefId, QueryResult<rty::Opaqueness<rty::EarlyBinder<rty::PolyVariants>>>>,
306    fn_sig: Cache<DefId, QueryResult<rty::EarlyBinder<rty::PolyFnSig>>>,
307    sort_decl_param_count: Cache<FluxDefId, usize>,
308    no_panic: Cache<DefId, bool>,
309    assume_parametric_params: Cache<DefId, UnordSet<u32>>,
310    call_graph: OnceCell<CallGraph<'tcx>>,
311    /// The no-panic inference result for the local crate, keyed by `NodeKey`.
312    inferred_no_panic: OnceCell<Rc<UnordMap<NodeKey<'tcx>, PanicSpec>>>,
313}
314
315impl<'genv, 'tcx> Queries<'genv, 'tcx> {
316    pub(crate) fn new(providers: Providers) -> Self {
317        Self {
318            providers,
319            queried_def_ids: RefCell::new(UnordSet::new()),
320            mir: Default::default(),
321            collect_specs: Default::default(),
322            resolve_crate: Default::default(),
323            flux_module_children: Default::default(),
324            desugar: Default::default(),
325            fhir_attr_map: Default::default(),
326            fhir_crate: Default::default(),
327            lower_generics_of: Default::default(),
328            lower_predicates_of: Default::default(),
329            lower_type_of: Default::default(),
330            lower_fn_sig: Default::default(),
331            spec_funcs: Default::default(),
332            inlined_body: Default::default(),
333            func_sort: Default::default(),
334            func_span: Default::default(),
335            qualifiers: Default::default(),
336            axioms: Default::default(),
337            prim_rel: Default::default(),
338            adt_sort_def_of: Default::default(),
339            check_wf: Default::default(),
340            late_bound_refinement_params: Default::default(),
341            adt_def: Default::default(),
342            invariants_of: Default::default(),
343            constant_info: Default::default(),
344            static_info: Default::default(),
345            generics_of: Default::default(),
346            refinement_generics_of: Default::default(),
347            predicates_of: Default::default(),
348            assoc_refinements_of: Default::default(),
349            assoc_refinement_body: Default::default(),
350            default_assoc_refinement_body: Default::default(),
351            sort_of_assoc_reft: Default::default(),
352            item_bounds: Default::default(),
353            type_of: Default::default(),
354            variants_of: Default::default(),
355            fn_sig: Default::default(),
356            sort_decl_param_count: Default::default(),
357            no_panic: Default::default(),
358            assume_parametric_params: Default::default(),
359            call_graph: Default::default(),
360            inferred_no_panic: Default::default(),
361        }
362    }
363
364    pub(crate) fn queried(&self, def_id: DefId) -> bool {
365        self.queried_def_ids.borrow().contains(&def_id)
366    }
367
368    pub(crate) fn mir(
369        &self,
370        genv: GlobalEnv<'genv, 'tcx>,
371        def_id: LocalDefId,
372    ) -> QueryResult<Rc<mir::BodyRoot<'tcx>>> {
373        run_with_cache(&self.mir, def_id, || {
374            let mir = unsafe { flux_common::mir_storage::retrieve_mir_body(genv.tcx(), def_id) };
375            let mir =
376                lowering::MirLoweringCtxt::lower_mir_body(genv.tcx(), genv.sess(), def_id, mir)?;
377            Ok(Rc::new(mir))
378        })
379    }
380
381    pub(crate) fn collect_specs(&'genv self, genv: GlobalEnv<'genv, 'tcx>) -> &'genv crate::Specs {
382        self.collect_specs
383            .get_or_init(|| (self.providers.collect_specs)(genv))
384    }
385
386    pub(crate) fn resolve_crate(
387        &'genv self,
388        genv: GlobalEnv<'genv, 'tcx>,
389    ) -> &'genv crate::ResolverOutput {
390        self.resolve_crate
391            .get_or_init(|| (self.providers.resolve_crate)(genv))
392    }
393
394    /// Akin to `rustc_middle::ty::TyCtxt::module_children` but for flux items (`defs!` and
395    /// sort declarations) defined directly in a module.
396    #[allow(clippy::disallowed_methods, reason = "`flux_items_by_scope` is the source of truth")]
397    pub(crate) fn flux_module_children(
398        &'genv self,
399        genv: GlobalEnv<'genv, 'tcx>,
400        def_id: DefId,
401    ) -> &'genv [fhir::FluxModChild] {
402        run_with_cache(&self.flux_module_children, def_id, || {
403            def_id.dispatch_query(
404                genv,
405                self,
406                |def_id| -> &'genv [fhir::FluxModChild] {
407                    // Local modules: build children from surface specs (safe to call from the
408                    // resolver; `fhir_crate` would create a query cycle). Modules cannot
409                    // have extern specs, so `local_id()` is sound.
410                    let specs = genv.collect_specs();
411                    let module = rustc_hir::HirId::make_owner(def_id.local_id());
412                    let items = specs
413                        .flux_items_by_scope
414                        .get(&module)
415                        .map_or(&[][..], Vec::as_ref);
416                    genv.alloc_slice(
417                        &items
418                            .iter()
419                            .filter_map(|crate::FluxItemDecl { declarer, item }| {
420                                let declarer = declarer.to_def_id();
421                                let ident;
422                                let res = match item {
423                                    surface::FluxItem::FuncDef(func) => {
424                                        ident = func.name;
425                                        fhir::Res::GlobalFunc(fhir::SpecFuncKind::Def(
426                                            FluxDefId::new(declarer, ident.name),
427                                        ))
428                                    }
429                                    surface::FluxItem::SortDecl(sort) => {
430                                        ident = sort.name;
431                                        fhir::Res::UserSort(FluxDefId::new(declarer, ident.name))
432                                    }
433                                    surface::FluxItem::Qualifier(qual) => {
434                                        ident = qual.name;
435                                        fhir::Res::Qualifier(FluxDefId::new(declarer, ident.name))
436                                    }
437                                    surface::FluxItem::Axiom(axiom) => {
438                                        ident = axiom.name;
439                                        fhir::Res::Axiom(FluxDefId::new(declarer, ident.name))
440                                    }
441                                    surface::FluxItem::PrimOpProp(prop) => {
442                                        ident = prop.name;
443                                        fhir::Res::Property(FluxDefId::new(declarer, ident.name))
444                                    }
445                                    surface::FluxItem::Use(_) => return None,
446                                };
447                                Some(fhir::FluxModChild { ident, res })
448                            })
449                            .collect::<Vec<_>>(),
450                    )
451                },
452                |def_id| genv.cstore().flux_module_children(def_id),
453                |_| &[], // crates without flux metadata have no flux children
454            )
455        })
456    }
457
458    pub(crate) fn desugar(
459        &'genv self,
460        genv: GlobalEnv<'genv, 'tcx>,
461        def_id: LocalDefId,
462    ) -> QueryResult<fhir::Node<'genv>> {
463        if let Some(v) = self.desugar.borrow().get(&def_id) {
464            return v.clone();
465        }
466        match (self.providers.desugar)(genv, def_id) {
467            Ok(nodes) => {
468                let mut cache = self.desugar.borrow_mut();
469                cache.extend_unord(nodes.into_items().map(|(def_id, node)| (def_id, Ok(node))));
470                let Some(res) = cache.get(&def_id) else {
471                    tracked_span_bug!("cannot desugar {def_id:?}")
472                };
473                res.clone()
474            }
475            Err(err) => {
476                self.desugar.borrow_mut().insert(def_id, Err(err.clone()));
477                Err(err)
478            }
479        }
480    }
481
482    pub(crate) fn fhir_attr_map(
483        &'genv self,
484        genv: GlobalEnv<'genv, 'tcx>,
485        def_id: LocalDefId,
486    ) -> fhir::AttrMap<'genv> {
487        run_with_cache(&self.fhir_attr_map, def_id, || (self.providers.fhir_attr_map)(genv, def_id))
488    }
489
490    pub(crate) fn fhir_crate(
491        &'genv self,
492        genv: GlobalEnv<'genv, 'tcx>,
493    ) -> &'genv fhir::FluxItems<'genv> {
494        self.fhir_crate
495            .get_or_init(|| (self.providers.fhir_crate)(genv))
496    }
497
498    pub(crate) fn lower_generics_of(
499        &self,
500        genv: GlobalEnv<'genv, 'tcx>,
501        def_id: DefId,
502    ) -> ty::Generics<'tcx> {
503        run_with_cache(&self.lower_generics_of, def_id, || {
504            genv.tcx().generics_of(def_id).lower(genv.tcx())
505        })
506    }
507
508    pub(crate) fn lower_predicates_of(
509        &self,
510        genv: GlobalEnv,
511        def_id: DefId,
512    ) -> QueryResult<ty::GenericPredicates> {
513        run_with_cache(&self.lower_predicates_of, def_id, || {
514            genv.tcx()
515                .clauses_of(def_id)
516                .lower(genv.tcx())
517                .map_err(|err| QueryErr::unsupported(def_id, err))
518        })
519    }
520
521    pub(crate) fn lower_type_of(
522        &self,
523        genv: GlobalEnv,
524        def_id: DefId,
525    ) -> QueryResult<ty::EarlyBinder<ty::Ty>> {
526        run_with_cache(&self.lower_type_of, def_id, || {
527            let ty = genv
528                .tcx()
529                .type_of(def_id)
530                .instantiate_identity()
531                .skip_norm_wip();
532            Ok(ty::EarlyBinder(
533                ty.lower(genv.tcx())
534                    .map_err(|err| QueryErr::unsupported(def_id, err.into_err()))?,
535            ))
536        })
537    }
538
539    pub(crate) fn lower_fn_sig(
540        &self,
541        genv: GlobalEnv,
542        def_id: DefId,
543    ) -> QueryResult<ty::EarlyBinder<ty::PolyFnSig>> {
544        run_with_cache(&self.lower_fn_sig, def_id, || {
545            let fn_sig = genv
546                .tcx()
547                .fn_sig(def_id)
548                .instantiate_identity()
549                .skip_norm_wip();
550            Ok(ty::EarlyBinder(
551                fn_sig
552                    .lower(genv.tcx())
553                    .map_err(|err| QueryErr::unsupported(def_id, err.into_err()))?,
554            ))
555        })
556    }
557
558    pub(crate) fn spec_funcs(&self, genv: GlobalEnv, krate: CrateNum) -> Rc<rty::SpecFuncs> {
559        run_with_cache(&self.spec_funcs, krate, || {
560            if krate == LOCAL_CRATE {
561                Rc::new((self.providers.spec_funcs)(genv))
562            } else {
563                genv.cstore().spec_funcs(krate)
564            }
565        })
566    }
567
568    pub(crate) fn inlined_body(&self, genv: GlobalEnv, did: FluxDefId) -> rty::Binder<rty::Expr> {
569        // We inline spec functions lazily (including those of external crates) in the current
570        // session, so they are inlined according to the flags of the current crate. Inlining a
571        // body recursively inlines (and caches) the bodies of the functions it calls. This
572        // terminates because `spec_funcs` rejects cycles.
573        run_with_cache(&self.inlined_body, did, || {
574            let rty::SpecFunc::Defined { body, .. } = genv.spec_func(did) else {
575                bug!("inlined body of uninterpreted function `{did:?}`")
576            };
577            body.reduce(genv)
578        })
579    }
580
581    pub(crate) fn func_sort(&self, genv: GlobalEnv, def_id: FluxDefId) -> rty::PolyFuncSort {
582        run_with_cache(&self.func_sort, def_id, || {
583            def_id.dispatch_query(
584                genv,
585                self,
586                |def_id| {
587                    // refinement functions cannot be extern specs so we simply grab the local id
588                    (self.providers.func_sort)(genv, def_id)
589                },
590                |def_id| genv.cstore().func_sort(def_id),
591                |_| {
592                    bug!(
593                        "cannot generate default function sort, the refinement must be defined somewhere"
594                    )
595                },
596            )
597        })
598    }
599
600    pub(crate) fn func_span(&self, genv: GlobalEnv, def_id: FluxDefId) -> Span {
601        run_with_cache(&self.func_span, def_id, || {
602            def_id.dispatch_query(
603                genv,
604                self,
605                |def_id| {
606                    // refinement functions cannot be extern specs so we simply grab the local id
607                    (self.providers.func_span)(genv, def_id)
608                },
609                |def_id| genv.cstore().func_span(def_id),
610                |_|
611                bug!(
612                        "cannot generate default function sort, the refinement must be defined somewhere"
613                    )
614                ,
615            )
616        })
617    }
618
619    pub(crate) fn qualifiers(&self, genv: GlobalEnv) -> QueryResult<&[rty::Qualifier]> {
620        self.qualifiers
621            .get_or_init(|| (self.providers.qualifiers)(genv))
622            .as_deref()
623            .map_err(Clone::clone)
624    }
625
626    pub(crate) fn axioms(&self, genv: GlobalEnv) -> QueryResult<&[rty::Axiom]> {
627        self.axioms
628            .get_or_init(|| (self.providers.axioms)(genv))
629            .as_deref()
630            .map_err(Clone::clone)
631    }
632
633    pub(crate) fn prim_rel(
634        &self,
635        genv: GlobalEnv,
636    ) -> QueryResult<&UnordMap<rty::BinOp, rty::PrimRel>> {
637        self.prim_rel
638            .get_or_init(|| (self.providers.prim_rel)(genv))
639            .as_ref()
640            .map_err(|err| err.clone())
641    }
642
643    pub(crate) fn adt_sort_def_of(
644        &self,
645        genv: GlobalEnv,
646        def_id: DefId,
647    ) -> QueryResult<rty::AdtSortDef> {
648        run_with_cache(&self.adt_sort_def_of, def_id, || {
649            def_id.dispatch_query(
650                genv,
651                self,
652                |def_id| (self.providers.adt_sort_def_of)(genv, def_id),
653                |def_id| genv.cstore().adt_sort_def(def_id),
654                |def_id| {
655                    let variants = IndexVec::from([rty::AdtSortVariant::new(vec![])]);
656                    Ok(rty::AdtSortDef::new(def_id, vec![], variants, false, true))
657                },
658            )
659        })
660    }
661
662    pub(crate) fn sort_decl_param_count(&self, genv: GlobalEnv, def_id: FluxDefId) -> usize {
663        run_with_cache(&self.sort_decl_param_count, def_id, || {
664            def_id.dispatch_query(
665                genv,
666                self,
667                |def_id| {
668                    (self.providers.sort_decl_param_count)(genv, def_id)
669                },
670                |def_id| genv.cstore().sort_decl_param_count(def_id),
671                |_| {
672                    bug!(
673                        "cannot generate default param count for sort declaration, it must be defined somewhere"
674                    )
675                }
676            )
677        })
678    }
679
680    pub(crate) fn check_wf(
681        &self,
682        genv: GlobalEnv<'genv, '_>,
683        def_id: LocalDefId,
684    ) -> QueryResult<Rc<rty::WfckResults>> {
685        run_with_cache(&self.check_wf, def_id, || (self.providers.check_wf)(genv, def_id))
686    }
687
688    pub(crate) fn late_bound_refinement_params(
689        &self,
690        genv: GlobalEnv<'genv, '_>,
691        def_id: LocalDefId,
692    ) -> QueryResult<&'genv [fhir::ParamId]> {
693        run_with_cache(&self.late_bound_refinement_params, def_id, || {
694            (self.providers.late_bound_refinement_params)(genv, def_id)
695        })
696    }
697
698    pub(crate) fn constant_info(
699        &self,
700        genv: GlobalEnv,
701        def_id: DefId,
702    ) -> QueryResult<rty::ConstantInfo> {
703        run_with_cache(&self.constant_info, def_id, || {
704            def_id.dispatch_query(
705                genv,
706                self,
707                |def_id| (self.providers.constant_info)(genv, def_id),
708                |def_id| genv.cstore().constant_info(def_id),
709                |def_id| {
710                    // TODO(RJ): fix duplication with [`conv_constant`]` in `flux-fhir-analysis`
711                    let ty = genv.tcx().type_of(def_id).no_bound_vars().unwrap();
712                    if ty.is_integral() {
713                        let val = genv.tcx().const_eval_poly(def_id).ok().and_then(|val| {
714                            let val = val.try_to_scalar_int()?;
715                            rty::Constant::from_scalar_int(genv.tcx(), val, &ty)
716                        });
717                        if let Some(constant_) = val {
718                            return Ok(rty::ConstantInfo::Interpreted(
719                                rty::Expr::constant(constant_),
720                                rty::Sort::Int,
721                            ));
722                        }
723                    }
724                    Ok(rty::ConstantInfo::Uninterpreted)
725                },
726            )
727        })
728    }
729
730    pub fn call_graph(&'genv self, genv: GlobalEnv<'genv, 'tcx>) -> &'genv CallGraph<'tcx> {
731        self.call_graph
732            .get_or_init(|| (self.providers.call_graph)(genv))
733    }
734
735    /// The no-panic inference result for the local crate, keyed by `NodeKey`.
736    pub fn inferred_no_panic(
737        &'genv self,
738        genv: GlobalEnv<'genv, 'tcx>,
739    ) -> Rc<UnordMap<NodeKey<'tcx>, PanicSpec>> {
740        self.inferred_no_panic
741            .get_or_init(|| Rc::new((self.providers.inferred_no_panic)(genv)))
742            .clone()
743    }
744
745    pub(crate) fn static_info(&self, genv: GlobalEnv, def_id: DefId) -> QueryResult<rty::Ty> {
746        run_with_cache(&self.static_info, def_id, || {
747            def_id.dispatch_query(
748                genv,
749                self,
750                |def_id| (self.providers.static_info)(genv, def_id),
751                |def_id| genv.cstore().static_info(def_id),
752                |def_id| rty::refining::default_static_ty(genv, def_id),
753            )
754        })
755    }
756
757    pub(crate) fn no_panic(&self, genv: GlobalEnv, def_id: DefId) -> bool {
758        run_with_cache(&self.no_panic, def_id, || {
759            def_id.dispatch_query(
760                genv,
761                self,
762                |def_id| {
763                    let mut current_id = def_id.local_id();
764
765                    // Walk up the entire parent chain within this closure
766                    loop {
767                        // Skip dummy items
768                        if genv.is_dummy(current_id) {
769                            if let Some(parent) = genv.tcx().opt_local_parent(current_id) {
770                                current_id = parent;
771                                continue;
772                            } else {
773                                return false; // Reached top without finding non-dummy
774                            }
775                        }
776
777                        // Check if current non-dummy item has the `no_panic` attribute
778                        if genv.fhir_attr_map(current_id).no_panic() {
779                            return true;
780                        }
781
782                        // Move to the next parent
783                        if let Some(parent) = genv.tcx().opt_local_parent(current_id) {
784                            current_id = parent;
785                        } else {
786                            break; // Reached the top
787                        }
788                    }
789
790                    config::no_panic()
791                },
792                |def_id| genv.cstore().no_panic(def_id),
793                |_| false,
794            )
795        })
796    }
797
798    pub(crate) fn assume_parametric_params(&self, genv: GlobalEnv, def_id: DefId) -> UnordSet<u32> {
799        run_with_cache(&self.assume_parametric_params, def_id, || {
800            def_id.dispatch_query(
801                genv,
802                self,
803                |def_id| {
804                    let tcx = genv.tcx();
805                    let generics = tcx.generics_of(def_id);
806                    genv.fhir_attr_map(def_id.local_id())
807                        .parametric_params()
808                        .iter()
809                        .map(|param_id| generics.param_def_id_to_index(tcx, *param_id).unwrap())
810                        .collect()
811                },
812                |def_id| genv.cstore().assume_parametric_params(def_id),
813                |_| UnordSet::default(),
814            )
815        })
816    }
817
818    pub(crate) fn adt_def(&self, genv: GlobalEnv, def_id: DefId) -> QueryResult<rty::AdtDef> {
819        run_with_cache(&self.adt_def, def_id, || {
820            def_id.dispatch_query(
821                genv,
822                self,
823                |def_id| (self.providers.adt_def)(genv, def_id),
824                |def_id| genv.cstore().adt_def(def_id),
825                |def_id| {
826                    let adt_def = genv.tcx().adt_def(def_id).lower(genv.tcx());
827                    Ok(rty::AdtDef::new(adt_def, genv.adt_sort_def_of(def_id)?, false))
828                },
829            )
830        })
831    }
832
833    pub(crate) fn invariants_of(
834        &self,
835        genv: GlobalEnv,
836        def_id: DefId,
837    ) -> rty::EarlyBinder<List<rty::Invariant>> {
838        run_with_cache(&self.invariants_of, def_id, || {
839            def_id.dispatch_query(
840                genv,
841                self,
842                |def_id| (self.providers.invariants_of)(genv, def_id),
843                |def_id| genv.cstore().invariants_of(def_id),
844                |_| rty::EarlyBinder(List::empty()),
845            )
846        })
847    }
848
849    pub(crate) fn generics_of(&self, genv: GlobalEnv, def_id: DefId) -> QueryResult<rty::Generics> {
850        // Box is special: its first type parameter (the pointee `T`) is refined as a `Type` rather
851        // than a `Base`. This allows refinements to "see through" the Box, similar to how references
852        // work.
853        if genv.tcx().is_lang_item(def_id, LangItem::OwnedBox) {
854            let generics = genv.lower_generics_of(def_id);
855            debug_assert_eq!(generics.params.len(), 2);
856            let deref_ty = &generics.params[0];
857            let alloc = &generics.params[1];
858            return Ok(rty::Generics {
859                own_params: List::from_arr([
860                    refine_generic_param_def(true, deref_ty),
861                    refine_generic_param_def(false, alloc),
862                ]),
863                parent: generics.parent(),
864                parent_count: generics.parent_count(),
865                has_self: generics.orig.has_self,
866            });
867        }
868        // `MetaSized` is a marker trait with a single `Self` type parameter. We refine it as `Type`
869        // (rather than `Base`) so that a type parameter `T` of kind `Type` can flow through bounds
870        // like `T: MetaSized`. This is required because `Box` is defined as `Box<T: ?Sized, ...>`
871        // which desugars to the bound `T: MetaSized`. This should be mostly fine because parameters
872        // of both kinds should be able to satisfy `MetaSized` bounds, but it will cause problems
873        // if we ever try to add associated refinements to `MetaSized` like we did for `Sized`.
874        if genv.tcx().is_lang_item(def_id, LangItem::MetaSized) {
875            let generics = genv.lower_generics_of(def_id);
876            debug_assert_eq!(generics.params.len(), 1);
877            let self_ty = &generics.params[0];
878            return Ok(rty::Generics {
879                own_params: List::from_arr([refine_generic_param_def(true, self_ty)]),
880                parent: generics.parent(),
881                parent_count: generics.parent_count(),
882                has_self: generics.orig.has_self,
883            });
884        }
885
886        run_with_cache(&self.generics_of, def_id, || {
887            def_id.dispatch_query(
888                genv,
889                self,
890                |def_id| (self.providers.generics_of)(genv, def_id),
891                |def_id| genv.cstore().generics_of(def_id),
892                |def_id| Ok(refining::refine_generics(&genv.lower_generics_of(def_id))),
893            )
894        })
895    }
896
897    pub(crate) fn refinement_generics_of(
898        &self,
899        genv: GlobalEnv,
900        def_id: DefId,
901    ) -> QueryResult<rty::EarlyBinder<rty::RefinementGenerics>> {
902        run_with_cache(&self.refinement_generics_of, def_id, || {
903            def_id.dispatch_query(
904                genv,
905                self,
906                |def_id| (self.providers.refinement_generics_of)(genv, def_id),
907                |def_id| genv.cstore().refinement_generics_of(def_id),
908                |def_id| {
909                    let parent = genv.tcx().generics_of(def_id).parent;
910                    Ok(rty::EarlyBinder(rty::RefinementGenerics {
911                        parent,
912                        parent_count: 0,
913                        own_params: List::empty(),
914                    }))
915                },
916            )
917        })
918    }
919
920    pub(crate) fn item_bounds(
921        &self,
922        genv: GlobalEnv<'genv, 'tcx>,
923        def_id: DefId,
924    ) -> QueryResult<rty::EarlyBinder<List<rty::Clause>>> {
925        run_with_cache(&self.item_bounds, def_id, || {
926            def_id.dispatch_query(
927                genv,
928                self,
929                |def_id| (self.providers.item_bounds)(genv, def_id),
930                |def_id| genv.cstore().item_bounds(def_id),
931                |def_id| {
932                    let clauses = genv
933                        .tcx()
934                        .item_bounds(def_id)
935                        .skip_binder()
936                        .lower(genv.tcx())
937                        .map_err(|err| QueryErr::unsupported(def_id, err))?
938                        .refine(&Refiner::default_for_item(genv, def_id)?)?;
939
940                    Ok(rty::EarlyBinder(clauses))
941                },
942            )
943        })
944    }
945
946    pub(crate) fn predicates_of(
947        &self,
948        genv: GlobalEnv,
949        def_id: DefId,
950    ) -> QueryResult<rty::EarlyBinder<rty::GenericPredicates>> {
951        run_with_cache(&self.predicates_of, def_id, || {
952            def_id.dispatch_query(
953                genv,
954                self,
955                |def_id| (self.providers.predicates_of)(genv, def_id),
956                |def_id| genv.cstore().predicates_of(def_id),
957                |def_id| {
958                    let predicates = genv
959                        .lower_predicates_of(def_id)?
960                        .refine(&Refiner::default_for_item(genv, def_id)?)?;
961                    Ok(rty::EarlyBinder(predicates))
962                },
963            )
964        })
965    }
966
967    pub(crate) fn assoc_refinements_of(
968        &self,
969        genv: GlobalEnv,
970        def_id: DefId,
971    ) -> QueryResult<rty::AssocRefinements> {
972        run_with_cache(&self.assoc_refinements_of, def_id, || {
973            def_id.dispatch_query(
974                genv,
975                self,
976                |def_id| (self.providers.assoc_refinements_of)(genv, def_id),
977                |def_id| genv.cstore().assoc_refinements_of(def_id),
978                |def_id| Ok(genv.builtin_assoc_refts(def_id).unwrap_or_default()),
979            )
980        })
981    }
982
983    pub(crate) fn assoc_refinement_body(
984        &self,
985        genv: GlobalEnv,
986        impl_assoc_id: FluxDefId,
987    ) -> QueryResult<rty::EarlyBinder<rty::Lambda>> {
988        run_with_cache(&self.assoc_refinement_body, impl_assoc_id, || {
989            impl_assoc_id.dispatch_query(
990                genv,
991                self,
992                |impl_assoc_id| (self.providers.assoc_refinement_body)(genv, impl_assoc_id),
993                |impl_assoc_id| genv.cstore().assoc_refinements_def(impl_assoc_id),
994                |impl_assoc_id| {
995                    Err(query_bug!(
996                        impl_assoc_id.parent(),
997                        "cannot generate default associate refinement for extern impl"
998                    ))
999                },
1000            )
1001        })
1002    }
1003
1004    pub(crate) fn default_assoc_refinement_body(
1005        &self,
1006        genv: GlobalEnv,
1007        trait_assoc_id: FluxDefId,
1008    ) -> QueryResult<Option<rty::EarlyBinder<rty::Lambda>>> {
1009        run_with_cache(&self.default_assoc_refinement_body, trait_assoc_id, || {
1010            trait_assoc_id.dispatch_query(
1011                genv,
1012                self,
1013                |trait_assoc_id| {
1014                    (self.providers.default_assoc_refinement_body)(genv, trait_assoc_id)
1015                },
1016                |trait_assoc_id| genv.cstore().default_assoc_refinements_def(trait_assoc_id),
1017                |trait_assoc_id| {
1018                    Err(query_bug!(
1019                        trait_assoc_id.parent(),
1020                        "cannot generate default assoc refinement for extern trait"
1021                    ))
1022                },
1023            )
1024        })
1025    }
1026
1027    pub(crate) fn sort_of_assoc_reft(
1028        &self,
1029        genv: GlobalEnv,
1030        assoc_id: FluxDefId,
1031    ) -> QueryResult<rty::EarlyBinder<rty::FuncSort>> {
1032        run_with_cache(&self.sort_of_assoc_reft, assoc_id, || {
1033            assoc_id.dispatch_query(
1034                genv,
1035                self,
1036                |assoc_id| (self.providers.sort_of_assoc_reft)(genv, assoc_id),
1037                |assoc_id| genv.cstore().sort_of_assoc_reft(assoc_id),
1038                |assoc_id| {
1039                    genv.builtin_assoc_reft_sort(assoc_id).ok_or_else(|| {
1040                        query_bug!(
1041                            assoc_id.parent(),
1042                            "assoc refinement on extern crate is not builtin"
1043                        )
1044                    })
1045                },
1046            )
1047        })
1048    }
1049
1050    pub(crate) fn type_of(
1051        &self,
1052        genv: GlobalEnv,
1053        def_id: DefId,
1054    ) -> QueryResult<rty::EarlyBinder<rty::TyOrCtor>> {
1055        run_with_cache(&self.type_of, def_id, || {
1056            def_id.dispatch_query(
1057                genv,
1058                self,
1059                |def_id| (self.providers.type_of)(genv, def_id),
1060                |def_id| genv.cstore().type_of(def_id),
1061                |def_id| {
1062                    // If we're given a type parameter, provide the generics of the parent container.
1063                    let generics_def_id = match genv.def_kind(def_id) {
1064                        DefKind::TyParam => genv.tcx().parent(def_id),
1065                        _ => def_id,
1066                    };
1067                    let ty = genv.lower_type_of(def_id)?.skip_binder();
1068                    Ok(rty::EarlyBinder(
1069                        Refiner::default_for_item(genv, generics_def_id)?
1070                            .refine_ty_or_base(&ty)?
1071                            .into(),
1072                    ))
1073                },
1074            )
1075        })
1076    }
1077
1078    pub(crate) fn variants_of(
1079        &self,
1080        genv: GlobalEnv,
1081        def_id: DefId,
1082    ) -> QueryResult<rty::Opaqueness<rty::EarlyBinder<rty::PolyVariants>>> {
1083        run_with_cache(&self.variants_of, def_id, || {
1084            def_id.dispatch_query(
1085                genv,
1086                self,
1087                |def_id| (self.providers.variants_of)(genv, def_id),
1088                |def_id| genv.cstore().variants_of(def_id),
1089                |def_id| {
1090                    let variants = genv
1091                        .tcx()
1092                        .adt_def(def_id)
1093                        .variants()
1094                        .indices()
1095                        .map(|variant_idx| {
1096                            Refiner::default_for_item(genv, def_id)?
1097                                .refine_variant_def(def_id, variant_idx)
1098                        })
1099                        .try_collect()?;
1100                    Ok(rty::Opaqueness::Transparent(rty::EarlyBinder(variants)))
1101                },
1102            )
1103        })
1104    }
1105
1106    pub(crate) fn fn_sig(
1107        &self,
1108        genv: GlobalEnv,
1109        def_id: DefId,
1110    ) -> QueryResult<rty::EarlyBinder<rty::PolyFnSig>> {
1111        run_with_cache(&self.fn_sig, def_id, || {
1112            def_id.dispatch_query(
1113                genv,
1114                self,
1115                |def_id| (self.providers.fn_sig)(genv, def_id),
1116                |def_id| genv.cstore().fn_sig(def_id),
1117                |def_id| {
1118                    let tcx = genv.tcx();
1119
1120                    let mut poly_sig = genv
1121                        .lower_fn_sig(def_id)?
1122                        .skip_binder()
1123                        .refine(&Refiner::default_for_item(genv, def_id)?)?
1124                        .hoist_input_binders();
1125                    if genv.is_fn_call(def_id) {
1126                        let fn_once_id = tcx.require_lang_item(LangItem::FnOnce, DUMMY_SP);
1127
1128                        let fn_once_no_panic = genv
1129                            .builtin_assoc_refts(fn_once_id)
1130                            .unwrap()
1131                            .find(sym::no_panic)
1132                            .unwrap();
1133
1134                        let args = GenericArg::identity_for_item(genv, fn_once_id)?;
1135
1136                        let alias_reft = AliasReft { assoc_id: fn_once_no_panic.def_id, args };
1137
1138                        poly_sig = poly_sig.map(|mut fn_sig| {
1139                            fn_sig.no_panic = Expr::alias(alias_reft, List::empty());
1140                            fn_sig
1141                        });
1142                    }
1143
1144                    // We only will add weak kvars if
1145                    //   0. If suggestions are enabled.
1146                    //   1. There are no weak kvars already
1147                    //   2. The function does NOT have a `#[no_suggestions]` annotation
1148                    //      in its parent. (checked below)
1149                    if config::suggestions() && genv.weak_kvars_for(def_id).is_none() {
1150                        // We only will add weak kvars to specs that are
1151                        // available locally (also enforced in fixpoint_encoding
1152                        // --- this check is perhaps redundant).
1153                        match genv.resolve_id(def_id).as_maybe_extern() {
1154                            Some(maybe_extern) if !genv.no_suggestions(maybe_extern.local_id()) => {
1155                                poly_sig =
1156                                    poly_sig.add_weak_kvars(genv, maybe_extern.resolved_id())?;
1157                            }
1158                            _ => {}
1159                        }
1160                    }
1161                    Ok(rty::EarlyBinder(poly_sig))
1162                },
1163            )
1164        })
1165    }
1166}
1167
1168/// Logic to *dispatch* a `def_id` to a provider (`local`, `external`, or `default`).
1169/// This is a trait so it can be implemented for [`DefId`] and for [`FluxDefId`].
1170pub trait DispatchKey: Sized + Copy {
1171    type LocalId;
1172
1173    fn dispatch_query<R>(
1174        self,
1175        genv: GlobalEnv,
1176        queries: &Queries,
1177        local: impl FnOnce(Self::LocalId) -> R,
1178        external: impl FnOnce(Self) -> Option<R>,
1179        default: impl FnOnce(Self) -> R,
1180    ) -> R;
1181
1182    fn def_id(self) -> DefId;
1183}
1184
1185impl DispatchKey for DefId {
1186    type LocalId = MaybeExternId;
1187
1188    fn dispatch_query<R>(
1189        self,
1190        genv: GlobalEnv,
1191        queries: &Queries,
1192        local: impl FnOnce(MaybeExternId) -> R,
1193        external: impl FnOnce(Self) -> Option<R>,
1194        default: impl FnOnce(Self) -> R,
1195    ) -> R {
1196        queries.queried_def_ids.borrow_mut().insert(self);
1197        match genv.resolve_id(self) {
1198            ResolvedDefId::Local(local_id) => {
1199                // Case 1: `def_id` is a `LocalDefId` so forward it to the *local provider*
1200                local(MaybeExternId::Local(local_id))
1201            }
1202            ResolvedDefId::ExternSpec(local_id, def_id) => {
1203                // Case 2: `def_id` is a `LocalDefId` wrapping an extern spec, so we also
1204                // forward it to the local provider
1205                local(MaybeExternId::Extern(local_id, def_id))
1206            }
1207            ResolvedDefId::Extern(def_id) if let Some(v) = external(def_id) => {
1208                // Case 3: `def_id` is an external `def_id` for which we have an annotation in the
1209                // *external provider*
1210                v
1211            }
1212            ResolvedDefId::Extern(def_id) => {
1213                // Case 4: If none of the above, we generate a default annotation
1214                default(def_id)
1215            }
1216        }
1217    }
1218
1219    fn def_id(self) -> DefId {
1220        self
1221    }
1222}
1223
1224impl DispatchKey for FluxDefId {
1225    type LocalId = FluxId<MaybeExternId>;
1226
1227    fn dispatch_query<R>(
1228        self,
1229        genv: GlobalEnv,
1230        queries: &Queries,
1231        local: impl FnOnce(FluxId<MaybeExternId>) -> R,
1232        external: impl FnOnce(FluxId<DefId>) -> Option<R>,
1233        default: impl FnOnce(FluxId<DefId>) -> R,
1234    ) -> R {
1235        #[allow(
1236            clippy::disallowed_methods,
1237            reason = "we are mapping the parent id to a different representation which still guarantees the existence of the item"
1238        )]
1239        self.parent().dispatch_query(
1240            genv,
1241            queries,
1242            |container_id| local(FluxId::new(container_id, self.name())),
1243            |container_id| external(FluxId::new(container_id, self.name())),
1244            |container_id| default(FluxId::new(container_id, self.name())),
1245        )
1246    }
1247
1248    fn def_id(self) -> DefId {
1249        self.parent()
1250    }
1251}
1252
1253fn run_with_cache<K, V>(cache: &Cache<K, V>, key: K, f: impl FnOnce() -> V) -> V
1254where
1255    K: std::hash::Hash + Eq,
1256    V: Clone,
1257{
1258    if let Some(v) = cache.borrow().get(&key) {
1259        return v.clone();
1260    }
1261    let v = f();
1262    cache.borrow_mut().insert(key, v.clone());
1263    v
1264}
1265
1266const OPAQUE_STRUCT: DiagMessage = msg!("invalid use of opaque struct");
1267const MISSING_ASSOC_REFT: DiagMessage =
1268    msg!("associated refinement `{$name}` is missing from implementation");
1269
1270impl<'a> Diagnostic<'a> for QueryErr {
1271    #[track_caller]
1272    fn into_diag(
1273        self,
1274        dcx: rustc_errors::DiagCtxtHandle<'a>,
1275        _level: rustc_errors::Level,
1276    ) -> rustc_errors::Diag<'a> {
1277        rustc_middle::ty::tls::with_opt(
1278            #[track_caller]
1279            |tcx| {
1280                let tcx = tcx.expect("no TyCtxt stored in tls");
1281                match self {
1282                    QueryErr::Unsupported { def_id, err } => {
1283                        let span = err.span.unwrap_or_else(|| tcx.def_span(def_id));
1284                        let mut diag = dcx.struct_span_err(span, msg!("unsupported signature"));
1285                        diag.code(E0999);
1286                        diag.note(err.descr);
1287                        diag
1288                    }
1289                    QueryErr::Ignored { def_id } => {
1290                        let def_span = tcx.def_span(def_id);
1291                        let mut diag = dcx.struct_span_err(def_span, msg!("use of ignored item"));
1292                        diag.code(E0999);
1293                        diag
1294                    }
1295                    QueryErr::NotIncluded { def_id } => {
1296                        let def_span = tcx.def_span(def_id);
1297                        let mut diag = dcx.struct_span_err(
1298                            def_span,
1299                            msg!("use of item defined in external crate, but was not included when checking that crate"),
1300                        );
1301                        diag.code(E0999);
1302                        diag
1303                    }
1304                    QueryErr::InvalidGenericArg { def_id } => {
1305                        let def_span = tcx.def_span(def_id);
1306                        let mut diag = dcx.struct_span_err(
1307                            def_span,
1308                            msg!("cannot instantiate base generic with opaque type or a type parameter of kind type"),
1309                        );
1310                        diag.code(E0999);
1311                        diag
1312                    }
1313                    QueryErr::MissingAssocReft { impl_id, name, .. } => {
1314                        let def_span = tcx.def_span(impl_id);
1315                        let mut diag = dcx.struct_span_err(def_span, MISSING_ASSOC_REFT);
1316                        diag.arg("name", name);
1317                        diag.code(E0999);
1318                        diag
1319                    }
1320                    QueryErr::Bug { def_id, location, msg } => {
1321                        let mut diag = dcx.struct_err(msg!("internal flux error: {$location}"));
1322                        if let Some(def_id) = def_id {
1323                            diag.span(tcx.def_span(def_id));
1324                        }
1325                        diag.arg("location", location);
1326                        diag.note(msg);
1327                        diag
1328                    }
1329                    QueryErr::Emitted(_) => {
1330                        let mut diag = dcx.struct_err("QueryErr::Emitted should be emitted");
1331                        diag.downgrade_to_delayed_bug();
1332                        diag
1333                    }
1334                    QueryErr::OpaqueStruct { struct_id } => {
1335                        let struct_span = tcx.def_span(struct_id);
1336                        let mut diag = dcx.struct_span_err(struct_span, OPAQUE_STRUCT);
1337                        diag.arg("struct", tcx.def_path_str(struct_id));
1338                        diag
1339                    }
1340                }
1341            },
1342        )
1343    }
1344}
1345
1346impl<'a> Diagnostic<'a> for QueryErrAt {
1347    #[track_caller]
1348    fn into_diag(
1349        self,
1350        dcx: rustc_errors::DiagCtxtHandle<'a>,
1351        level: rustc_errors::Level,
1352    ) -> rustc_errors::Diag<'a> {
1353        rustc_middle::ty::tls::with_opt(
1354            #[track_caller]
1355            |tcx| {
1356                let tcx = tcx.expect("no TyCtxt stored in tls");
1357                let cx_span = self.cx.span();
1358                let mut diag = match self.err {
1359                    QueryErr::Unsupported { def_id, err, .. } => {
1360                        let mut diag =
1361                            dcx.struct_span_err(cx_span, msg!("use of unsupported {$kind}"));
1362                        diag.arg("kind", tcx.def_kind(def_id).descr(def_id));
1363                        if let Some(def_ident_span) = tcx.def_ident_span(def_id) {
1364                            diag.span_note(
1365                                def_ident_span,
1366                                msg!("this {$kind} has unsupported features"),
1367                            );
1368                        }
1369                        diag.note(err.descr);
1370                        diag
1371                    }
1372                    QueryErr::Ignored { def_id } => {
1373                        let mut diag =
1374                            dcx.struct_span_err(cx_span, msg!("use of ignored {$kind} `{$name}`"));
1375                        diag.arg("kind", tcx.def_kind(def_id).descr(def_id));
1376                        diag.arg("name", def_id_to_string(def_id));
1377                        diag.span_label(cx_span, msg!("help: try ignoring or trusting this code"));
1378                        diag
1379                    }
1380                    QueryErr::NotIncluded { def_id } => {
1381                        let mut diag = dcx.struct_span_err(
1382                            cx_span,
1383                            msg!("use of {$kind} `{$name}` that was not included when checking external crate"),
1384                        );
1385                        diag.arg("kind", tcx.def_kind(def_id).descr(def_id));
1386                        diag.arg("name", def_id_to_string(def_id));
1387                        let span = tcx
1388                            .def_ident_span(def_id)
1389                            .unwrap_or_else(|| tcx.def_span(def_id));
1390                        diag.span_help(
1391                            span,
1392                            msg!("when checking external crate, include the file or module where the excluded item is defined"),
1393                        );
1394                        diag
1395                    }
1396                    QueryErr::MissingAssocReft { name, .. } => {
1397                        let mut diag = dcx.struct_span_err(cx_span, MISSING_ASSOC_REFT);
1398                        diag.arg("name", name);
1399                        diag.code(E0999);
1400                        diag
1401                    }
1402                    QueryErr::OpaqueStruct { struct_id } => {
1403                        let mut diag = dcx.struct_span_err(cx_span, OPAQUE_STRUCT);
1404                        diag.arg("struct", tcx.def_path_str(struct_id));
1405                        diag.span_label(
1406                            cx_span,
1407                            msg!("operation accesses the internal representation of `{$struct}`"),
1408                        );
1409                        if let ErrCtxt::FnCheck(_, fn_def_id) = self.cx {
1410                            let fn_span = tcx.def_span(fn_def_id);
1411                            if fn_span.in_derive_expansion() {
1412                                // reset message span to use the type definition
1413                                diag.span_label(
1414                                    tcx.def_span(struct_id),
1415                                    msg!("help: this code was generated by a `#[derive(..)]` and cannot be annotated directly; try annotating this type with `#[flux::trusted_derive]`"),
1416                                );
1417                            } else {
1418                                diag.arg("def_kind", tcx.def_descr(fn_def_id.to_def_id()));
1419                                diag.span_label(
1420                                    fn_span,
1421                                    msg!("help: try annotating this {$def_kind} with `#[trusted]`"),
1422                                );
1423                            }
1424                            diag.note(
1425                                msg!("opaque structs can only be accessed in trusted code (see <https://flux-rs.github.io/flux/guide/specifications.html#opaque-structs>)"),
1426                            );
1427                        }
1428                        diag
1429                    }
1430                    QueryErr::InvalidGenericArg { .. }
1431                    | QueryErr::Emitted(_)
1432                    | QueryErr::Bug { .. } => {
1433                        let mut diag = self.err.into_diag(dcx, level);
1434                        diag.span(cx_span);
1435                        diag
1436                    }
1437                };
1438                diag.code(E0999);
1439                diag
1440            },
1441        )
1442    }
1443}
1444
1445impl From<ErrorGuaranteed> for QueryErr {
1446    fn from(err: ErrorGuaranteed) -> Self {
1447        Self::Emitted(err)
1448    }
1449}
1450
1451pub fn try_query<T>(f: impl FnOnce() -> QueryResult<T>) -> QueryResult<T> {
1452    f()
1453}