Skip to main content

flux_middle/
global_env.rs

1use std::{
2    alloc,
3    cell::RefCell,
4    path::{Path, PathBuf},
5    ptr,
6    rc::Rc,
7    slice,
8};
9
10use flux_arc_interner::List;
11use flux_common::{bug, result::ErrorEmitter};
12use flux_config::{self as config, IncludePattern};
13use flux_errors::FluxSession;
14use flux_rustc_bridge::{self, lowering::Lower, mir, ty};
15use flux_syntax::symbols::sym;
16use rustc_data_structures::unord::{UnordMap, UnordSet};
17use rustc_hir::{
18    attrs::lang_items::LangItem,
19    def::DefKind,
20    def_id::{CrateNum, DefId, LocalDefId},
21};
22use rustc_middle::{
23    query::IntoQueryKey,
24    ty::{TyCtxt, Variance},
25};
26use rustc_span::{FileName, Span};
27pub use rustc_span::{Symbol, symbol::Ident};
28use tempfile::TempDir;
29
30use crate::{
31    PanicReason, PanicSpec,
32    call_graph::NodeKey,
33    cstore::CrateStoreDyn,
34    def_id::{FluxDefId, FluxLocalDefId, MaybeExternId, ResolvedDefId},
35    fhir::{self, VariantIdx},
36    queries::{DispatchKey, Providers, Queries, QueryErr, QueryResult},
37    query_bug,
38    rty::{
39        self, QualifierKind,
40        refining::{Refine as _, Refiner},
41    },
42};
43
44#[derive(Clone, Copy)]
45pub struct GlobalEnv<'genv, 'tcx> {
46    inner: &'genv GlobalEnvInner<'genv, 'tcx>,
47}
48
49pub struct WeakKvarInfo {
50    /// Solutions (if provided as ground truth annotations). Each soution is
51    /// part of a conjunction that constitutes the full ground truth.
52    pub solutions: Vec<rty::Binder<rty::Expr>>,
53    /// The sorts of the weak kvar in the order in which they appear in the
54    /// arguments.
55    pub sorts: Vec<rty::Sort>,
56}
57pub type WeakKvarMap = UnordMap<u32, WeakKvarInfo>;
58
59struct GlobalEnvInner<'genv, 'tcx> {
60    tcx: TyCtxt<'tcx>,
61    sess: &'genv FluxSession,
62    arena: &'genv fhir::Arena,
63    cstore: Box<CrateStoreDyn<'tcx>>,
64    queries: Queries<'genv, 'tcx>,
65    tempdir: TempDir,
66    weak_kvars: RefCell<UnordMap<DefId, Rc<WeakKvarMap>>>,
67}
68
69impl<'tcx> GlobalEnv<'_, 'tcx> {
70    pub fn enter<'a, R>(
71        tcx: TyCtxt<'tcx>,
72        sess: &'a FluxSession,
73        cstore: Box<CrateStoreDyn<'tcx>>,
74        arena: &'a fhir::Arena,
75        providers: Providers,
76        f: impl for<'genv> FnOnce(GlobalEnv<'genv, 'tcx>) -> R,
77    ) -> R {
78        // The tempdir must be in the same partition as the target directory so we can `fs::rename`
79        // files in it.
80        let tempdir = TempDir::new_in(lean_parent_dir(tcx)).unwrap();
81        let queries = Queries::new(providers);
82        let inner = GlobalEnvInner {
83            tcx,
84            sess,
85            cstore,
86            arena,
87            queries,
88            tempdir,
89            weak_kvars: Default::default(),
90        };
91        f(GlobalEnv { inner: &inner })
92    }
93}
94
95impl<'genv, 'tcx> GlobalEnv<'genv, 'tcx> {
96    pub fn queried(self, def_id: DefId) -> bool {
97        self.inner.queries.queried(def_id)
98    }
99
100    /// Runs a query only if the given key's `DefId` was previously queried during checking.
101    ///
102    /// During checking, we track all items transitively reached from explicitly included items.
103    /// This method is used during metadata encoding to avoid triggering queries for items that
104    /// were not reached. If the item was not previously queried, returns [`QueryErr::Ignored`].
105    pub fn run_query_if_reached<K: DispatchKey, R>(
106        self,
107        key: K,
108        query: impl FnOnce(Self, K) -> QueryResult<R>,
109    ) -> QueryResult<R> {
110        if !self.inner.queries.queried(key.def_id()) {
111            return Err(QueryErr::NotIncluded { def_id: key.def_id() });
112        }
113
114        query(self, key)
115    }
116
117    pub fn tcx(self) -> TyCtxt<'tcx> {
118        self.inner.tcx
119    }
120
121    pub fn sess(self) -> &'genv FluxSession {
122        self.inner.sess
123    }
124
125    pub fn collect_specs(self) -> &'genv crate::Specs {
126        self.inner.queries.collect_specs(self)
127    }
128
129    pub fn resolve_crate(self) -> &'genv crate::ResolverOutput {
130        self.inner.queries.resolve_crate(self)
131    }
132
133    /// Akin to `rustc_middle::ty::TyCtxt::module_children` but for flux items (`defs!` and
134    /// sort declarations) defined directly in a module.
135    pub fn flux_module_children(self, def_id: DefId) -> &'genv [fhir::FluxModChild] {
136        self.inner.queries.flux_module_children(self, def_id)
137    }
138
139    /// Parent directory of the Lean project.
140    pub fn lean_parent_dir(self) -> PathBuf {
141        lean_parent_dir(self.tcx())
142    }
143
144    pub fn temp_dir(self) -> &'genv TempDir {
145        &self.inner.tempdir
146    }
147
148    pub fn desugar(self, def_id: LocalDefId) -> QueryResult<fhir::Node<'genv>> {
149        self.inner.queries.desugar(self, def_id)
150    }
151
152    pub fn fhir_attr_map(self, def_id: LocalDefId) -> fhir::AttrMap<'genv> {
153        self.inner.queries.fhir_attr_map(self, def_id)
154    }
155
156    pub fn fhir_crate(self) -> &'genv fhir::FluxItems<'genv> {
157        self.inner.queries.fhir_crate(self)
158    }
159
160    pub fn alloc<T>(&self, val: T) -> &'genv T {
161        self.inner.arena.alloc(val)
162    }
163
164    pub fn alloc_slice<T: Copy>(self, slice: &[T]) -> &'genv [T] {
165        self.inner.arena.alloc_slice_copy(slice)
166    }
167
168    pub fn alloc_slice_fill_iter<T, I>(self, it: I) -> &'genv [T]
169    where
170        I: IntoIterator<Item = T>,
171        I::IntoIter: ExactSizeIterator,
172    {
173        self.inner.arena.alloc_slice_fill_iter(it)
174    }
175
176    pub fn def_kind(&self, def_id: impl IntoQueryKey<DefId>) -> DefKind {
177        self.tcx().def_kind(def_id.into_query_key())
178    }
179
180    /// Allocates space to store `cap` elements of type `T`.
181    ///
182    /// The elements are initialized using the supplied iterator. At most `cap` elements will be
183    /// retrieved from the iterator. If the iterator yields fewer than `cap` elements, the returned
184    /// slice will be of length less than the allocated capacity.
185    ///
186    /// ## Panics
187    ///
188    /// Panics if reserving space for the slice fails.
189    pub fn alloc_slice_with_capacity<T, I>(self, cap: usize, it: I) -> &'genv [T]
190    where
191        I: IntoIterator<Item = T>,
192    {
193        let layout = alloc::Layout::array::<T>(cap).unwrap_or_else(|_| bug!("out of memory"));
194        let dst = self.inner.arena.alloc_layout(layout).cast::<T>();
195        unsafe {
196            let mut len = 0;
197            for (i, v) in it.into_iter().take(cap).enumerate() {
198                len += 1;
199                ptr::write(dst.as_ptr().add(i), v);
200            }
201
202            slice::from_raw_parts(dst.as_ptr(), len)
203        }
204    }
205
206    pub fn call_graph(self) -> &'genv crate::call_graph::CallGraph<'tcx> {
207        self.inner.queries.call_graph(self)
208    }
209
210    /// The inferred [`PanicSpec`] for the node `key`, looked up in the local crate's
211    /// `NodeKey`-keyed map. Missing entries default to `MightPanic(NotInCallGraph)`.
212    pub fn inferred_no_panic_key(self, key: NodeKey<'tcx>) -> PanicSpec {
213        self.inferred_no_panic_local()
214            .get(&key)
215            .copied()
216            .unwrap_or(PanicSpec::MightPanic(PanicReason::NotInCallGraph))
217    }
218
219    /// The local crate's full `NodeKey`-keyed no-panic map (used by metadata encoding).
220    pub fn inferred_no_panic_local(self) -> Rc<UnordMap<NodeKey<'tcx>, PanicSpec>> {
221        self.inner.queries.inferred_no_panic(self)
222    }
223
224    /// Looks up the inferred [`PanicSpec`] for a node `key` defined in an *external* crate, from
225    /// that crate's serialized metadata table. Tries the exact key first (so a serialized
226    /// [`Mono`](NodeKey::Mono) is used when present), then for a monomorphization falls back to the
227    /// source [`Item`](NodeKey::Item) (covering instantiations the external crate could never have
228    /// analyzed, e.g. at a local type), then to `MightPanic`.
229    pub fn inferred_no_panic_external(self, key: NodeKey<'tcx>) -> PanicSpec {
230        let table = self.cstore().inferred_no_panic(key.def_id().krate);
231        if let Some(&spec) = table.get(&key) {
232            return spec;
233        }
234        if let NodeKey::Mono(instance) = key
235            && let Some(&spec) = table.get(&NodeKey::Item(instance.def_id()))
236        {
237            return spec;
238        }
239        PanicSpec::MightPanic(PanicReason::NotInCallGraph)
240    }
241
242    pub fn inlined_body(self, did: FluxDefId) -> rty::Binder<rty::Expr> {
243        self.normalized_defns(did.krate()).inlined_body(did)
244    }
245
246    pub fn normalized_info(self, did: FluxDefId) -> rty::FuncInfo {
247        self.normalized_defns(did.krate()).func_info(did).clone()
248    }
249
250    pub fn normalized_defns(self, krate: CrateNum) -> Rc<rty::NormalizedDefns> {
251        self.inner.queries.normalized_defns(self, krate)
252    }
253
254    pub fn prim_rel_for(self, op: &rty::BinOp) -> QueryResult<Option<&'genv rty::PrimRel>> {
255        Ok(self.inner.queries.prim_rel(self)?.get(op))
256    }
257
258    pub fn qualifiers(self) -> QueryResult<&'genv [rty::Qualifier]> {
259        self.inner.queries.qualifiers(self)
260    }
261
262    /// Return all the qualifiers that apply to an item, including both global and local qualifiers.
263    pub fn qualifiers_for(
264        self,
265        did: LocalDefId,
266    ) -> QueryResult<impl Iterator<Item = &'genv rty::Qualifier>> {
267        let quals = self.fhir_attr_map(did).qualifiers;
268        let names: UnordSet<_> = quals.iter().copied().collect();
269        Ok(self.qualifiers()?.iter().filter(move |qual| {
270            match qual.kind {
271                QualifierKind::Global => true,
272                QualifierKind::Hint => qual.def_id.parent() == did,
273                QualifierKind::Local => names.contains(&qual.def_id),
274            }
275        }))
276    }
277
278    /// Return the list of flux function definitions that should be revelaed for item
279    pub fn reveals_for(self, did: LocalDefId) -> &'genv [FluxDefId] {
280        self.fhir_attr_map(did).reveals
281    }
282
283    pub fn func_sort(self, def_id: impl IntoQueryKey<FluxDefId>) -> rty::PolyFuncSort {
284        self.inner.queries.func_sort(self, def_id.into_query_key())
285    }
286
287    pub fn func_span(self, def_id: impl IntoQueryKey<FluxDefId>) -> Span {
288        self.inner.queries.func_span(self, def_id.into_query_key())
289    }
290
291    pub fn should_inline_fun(self, def_id: FluxDefId) -> bool {
292        let is_poly = self.func_sort(def_id).params().len() > 0;
293        is_poly || !flux_config::smt_define_fun()
294    }
295
296    pub fn variances_of(self, did: DefId) -> &'tcx [Variance] {
297        self.tcx().variances_of(did)
298    }
299
300    pub fn mir(self, def_id: LocalDefId) -> QueryResult<Rc<mir::BodyRoot<'tcx>>> {
301        self.inner.queries.mir(self, def_id)
302    }
303
304    pub fn lower_generics_of(self, def_id: impl IntoQueryKey<DefId>) -> ty::Generics<'tcx> {
305        self.inner
306            .queries
307            .lower_generics_of(self, def_id.into_query_key())
308    }
309
310    pub fn lower_predicates_of(
311        self,
312        def_id: impl IntoQueryKey<DefId>,
313    ) -> QueryResult<ty::GenericPredicates> {
314        self.inner
315            .queries
316            .lower_predicates_of(self, def_id.into_query_key())
317    }
318
319    pub fn lower_type_of(
320        self,
321        def_id: impl IntoQueryKey<DefId>,
322    ) -> QueryResult<ty::EarlyBinder<ty::Ty>> {
323        self.inner
324            .queries
325            .lower_type_of(self, def_id.into_query_key())
326    }
327
328    pub fn lower_fn_sig(
329        self,
330        def_id: impl Into<DefId>,
331    ) -> QueryResult<ty::EarlyBinder<ty::PolyFnSig>> {
332        self.inner.queries.lower_fn_sig(self, def_id.into())
333    }
334
335    pub fn adt_def(self, def_id: impl IntoQueryKey<DefId>) -> QueryResult<rty::AdtDef> {
336        self.inner.queries.adt_def(self, def_id.into_query_key())
337    }
338
339    pub fn constant_info(self, def_id: impl IntoQueryKey<DefId>) -> QueryResult<rty::ConstantInfo> {
340        self.inner
341            .queries
342            .constant_info(self, def_id.into_query_key())
343    }
344
345    pub fn static_info(self, def_id: impl IntoQueryKey<DefId>) -> QueryResult<rty::StaticInfo> {
346        self.inner
347            .queries
348            .static_info(self, def_id.into_query_key())
349    }
350
351    pub fn adt_sort_def_of(self, def_id: impl IntoQueryKey<DefId>) -> QueryResult<rty::AdtSortDef> {
352        self.inner
353            .queries
354            .adt_sort_def_of(self, def_id.into_query_key())
355    }
356
357    pub fn sort_decl_param_count(self, def_id: impl IntoQueryKey<FluxDefId>) -> usize {
358        self.inner
359            .queries
360            .sort_decl_param_count(self, def_id.into_query_key())
361    }
362
363    pub fn check_wf(self, def_id: LocalDefId) -> QueryResult<Rc<rty::WfckResults>> {
364        self.inner.queries.check_wf(self, def_id)
365    }
366
367    pub fn impl_trait_ref(self, impl_id: DefId) -> QueryResult<rty::EarlyBinder<rty::TraitRef>> {
368        let trait_ref = self.tcx().impl_trait_ref(impl_id);
369        let trait_ref = trait_ref.skip_binder();
370        let trait_ref = trait_ref
371            .lower(self.tcx())
372            .map_err(|err| QueryErr::unsupported(impl_id, err.into_err()))?
373            .refine(&Refiner::default_for_item(self, impl_id)?)?;
374        Ok(rty::EarlyBinder(trait_ref))
375    }
376
377    pub fn generics_of(self, def_id: impl IntoQueryKey<DefId>) -> QueryResult<rty::Generics> {
378        self.inner
379            .queries
380            .generics_of(self, def_id.into_query_key())
381    }
382
383    pub fn refinement_generics_of(
384        self,
385        def_id: impl IntoQueryKey<DefId>,
386    ) -> QueryResult<rty::EarlyBinder<rty::RefinementGenerics>> {
387        self.inner
388            .queries
389            .refinement_generics_of(self, def_id.into_query_key())
390    }
391
392    pub fn predicates_of(
393        self,
394        def_id: impl IntoQueryKey<DefId>,
395    ) -> QueryResult<rty::EarlyBinder<rty::GenericPredicates>> {
396        self.inner
397            .queries
398            .predicates_of(self, def_id.into_query_key())
399    }
400
401    pub fn assoc_refinements_of(
402        self,
403        def_id: impl IntoQueryKey<DefId>,
404    ) -> QueryResult<rty::AssocRefinements> {
405        self.inner
406            .queries
407            .assoc_refinements_of(self, def_id.into_query_key())
408    }
409
410    pub fn assoc_refinement(self, assoc_id: FluxDefId) -> QueryResult<rty::AssocReft> {
411        Ok(self.assoc_refinements_of(assoc_id.parent())?.get(assoc_id))
412    }
413
414    /// Given the id of an associated refinement in a trait definition returns the body for the
415    /// corresponding associated refinement in the implementation with id `impl_id`.
416    ///
417    /// This function returns [`QueryErr::MissingAssocReft`] if the associated refinement is not
418    /// found in the implementation and there's no default body in the trait. This can happen if an
419    /// extern spec adds an associated refinement without a default body because we are currently
420    /// not checking `compare_impl_item` for those definitions.
421    pub fn assoc_refinement_body_for_impl(
422        self,
423        trait_assoc_id: FluxDefId,
424        impl_id: DefId,
425    ) -> QueryResult<rty::EarlyBinder<rty::Lambda>> {
426        // Check if the implementation has the associated refinement
427        let impl_assoc_refts = self.assoc_refinements_of(impl_id)?;
428        if let Some(impl_assoc_reft) = impl_assoc_refts.find(trait_assoc_id.name()) {
429            return self.assoc_refinement_body(impl_assoc_reft.def_id());
430        }
431
432        // Otherwise, check if the trait has a default body
433        if let Some(body) = self.default_assoc_refinement_body(trait_assoc_id)? {
434            let impl_trait_ref = self.impl_trait_ref(impl_id)?.instantiate_identity();
435            return Ok(rty::EarlyBinder(body.instantiate(self.tcx(), &impl_trait_ref.args, &[])));
436        }
437
438        Err(QueryErr::MissingAssocReft {
439            impl_id,
440            trait_id: trait_assoc_id.parent(),
441            name: trait_assoc_id.name(),
442        })
443    }
444
445    pub fn default_assoc_refinement_body(
446        self,
447        trait_assoc_id: FluxDefId,
448    ) -> QueryResult<Option<rty::EarlyBinder<rty::Lambda>>> {
449        self.inner
450            .queries
451            .default_assoc_refinement_body(self, trait_assoc_id)
452    }
453
454    pub fn assoc_refinement_body(
455        self,
456        impl_assoc_id: FluxDefId,
457    ) -> QueryResult<rty::EarlyBinder<rty::Lambda>> {
458        self.inner
459            .queries
460            .assoc_refinement_body(self, impl_assoc_id)
461    }
462
463    pub fn sort_of_assoc_reft(
464        self,
465        assoc_id: FluxDefId,
466    ) -> QueryResult<rty::EarlyBinder<rty::FuncSort>> {
467        self.inner.queries.sort_of_assoc_reft(self, assoc_id)
468    }
469
470    pub fn item_bounds(
471        self,
472        def_id: impl IntoQueryKey<DefId>,
473    ) -> QueryResult<rty::EarlyBinder<List<rty::Clause>>> {
474        self.inner
475            .queries
476            .item_bounds(self, def_id.into_query_key())
477    }
478
479    pub fn type_of(
480        self,
481        def_id: impl IntoQueryKey<DefId>,
482    ) -> QueryResult<rty::EarlyBinder<rty::TyOrCtor>> {
483        self.inner.queries.type_of(self, def_id.into_query_key())
484    }
485
486    pub fn fn_sig(
487        self,
488        def_id: impl IntoQueryKey<DefId>,
489    ) -> QueryResult<rty::EarlyBinder<rty::PolyFnSig>> {
490        self.inner.queries.fn_sig(self, def_id.into_query_key())
491    }
492
493    pub fn feed_weak_kvars(self, def_id: DefId, wk: WeakKvarMap) {
494        self.inner
495            .weak_kvars
496            .borrow_mut()
497            .insert(def_id, Rc::new(wk));
498    }
499
500    pub fn weak_kvars_for(self, def_id: DefId) -> Option<Rc<WeakKvarMap>> {
501        self.inner.weak_kvars.borrow().get(&def_id).cloned()
502    }
503
504    pub fn variants_of(
505        self,
506        def_id: impl IntoQueryKey<DefId>,
507    ) -> QueryResult<rty::Opaqueness<rty::EarlyBinder<rty::PolyVariants>>> {
508        self.inner
509            .queries
510            .variants_of(self, def_id.into_query_key())
511    }
512
513    pub fn variant_sig(
514        self,
515        def_id: DefId,
516        variant_idx: VariantIdx,
517    ) -> QueryResult<rty::Opaqueness<rty::EarlyBinder<rty::PolyVariant>>> {
518        Ok(self
519            .variants_of(def_id)?
520            .map(|variants| variants.map(|variants| variants[variant_idx.as_usize()].clone())))
521    }
522
523    /// Whether the crate has Flux metadata in the cratestore.
524    pub fn cstore_has_crate(self, krate: CrateNum) -> bool {
525        self.cstore().has_crate(krate)
526    }
527
528    /// Whether the function is marked with `#[flux::no_panic]`
529    pub fn no_panic(self, def_id: impl IntoQueryKey<DefId>) -> bool {
530        self.inner.queries.no_panic(self, def_id.into_query_key())
531    }
532
533    pub fn assume_parametric_params(self, def_id: impl IntoQueryKey<DefId>) -> UnordSet<u32> {
534        self.inner
535            .queries
536            .assume_parametric_params(self, def_id.into_query_key())
537    }
538
539    pub fn is_box(&self, res: fhir::Res) -> bool {
540        res.is_box(self.tcx())
541    }
542
543    pub fn def_id_to_param_index(&self, def_id: DefId) -> u32 {
544        let parent = self.tcx().parent(def_id);
545        let generics = self.tcx().generics_of(parent);
546        generics.param_def_id_to_index(self.tcx(), def_id).unwrap()
547    }
548
549    pub(crate) fn cstore(self) -> &'genv CrateStoreDyn<'tcx> {
550        &*self.inner.cstore
551    }
552
553    pub fn has_trusted_impl(&self, def_id: DefId) -> bool {
554        if let Some(did) = self
555            .resolve_id(def_id)
556            .as_maybe_extern()
557            .map(|id| id.local_id())
558        {
559            self.trusted_impl(did)
560        } else {
561            false
562        }
563    }
564
565    /// The `Output` associated type is defined in `FnOnce`, and `Fn`/`FnMut`
566    /// inherit it, so this should suffice to check if the `def_id`
567    /// corresponds to `LangItem::FnOnceOutput`.
568    pub fn is_fn_output(&self, def_id: DefId) -> bool {
569        let def_span = self.tcx().def_span(def_id);
570        self.tcx()
571            .require_lang_item(LangItem::FnOnceOutput, def_span)
572            == def_id
573    }
574
575    /// Returns whether `def_id` is the `call` method in the `Fn` trait,
576    /// the `call_mut` method in the `FnMut` trait,
577    /// or the `call_once` method in the `FnOnce` trait.
578    pub fn is_fn_call(&self, def_id: DefId) -> bool {
579        let methods_and_names = [
580            (LangItem::Fn, sym::call),
581            (LangItem::FnMut, sym::call_mut),
582            (LangItem::FnOnce, sym::call_once),
583        ];
584        let tcx = self.tcx();
585        let Some(assoc_item) = tcx.opt_associated_item(def_id) else { return false };
586        let Some(trait_id) = assoc_item.trait_container(tcx) else { return false };
587
588        methods_and_names.iter().any(|(lang_item, method_name)| {
589            assoc_item.name() == *method_name && tcx.is_lang_item(trait_id, *lang_item)
590        })
591    }
592
593    /// Iterator over all local def ids that are not an extern spec
594    pub fn iter_local_def_id(self) -> impl Iterator<Item = LocalDefId> + use<'tcx, 'genv> {
595        self.tcx().iter_local_def_id().filter(move |&local_def_id| {
596            self.maybe_extern_id(local_def_id).is_local() && !self.is_dummy(local_def_id)
597        })
598    }
599
600    pub fn iter_extern_def_id(self) -> impl Iterator<Item = DefId> + use<'tcx, 'genv> {
601        self.tcx()
602            .iter_local_def_id()
603            .filter_map(move |local_def_id| self.maybe_extern_id(local_def_id).as_extern())
604    }
605
606    pub fn maybe_extern_id(self, local_id: LocalDefId) -> MaybeExternId {
607        self.collect_specs()
608            .local_id_to_extern_id
609            .get(&local_id)
610            .map_or_else(
611                || MaybeExternId::Local(local_id),
612                |def_id| MaybeExternId::Extern(local_id, *def_id),
613            )
614    }
615
616    #[expect(clippy::disallowed_methods)]
617    pub fn resolve_id(self, def_id: DefId) -> ResolvedDefId {
618        let maybe_extern_spec = self
619            .collect_specs()
620            .extern_id_to_local_id
621            .get(&def_id)
622            .copied();
623        if let Some(local_id) = maybe_extern_spec {
624            ResolvedDefId::ExternSpec(local_id, def_id)
625        } else if let Some(local_id) = def_id.as_local() {
626            debug_assert!(
627                self.maybe_extern_id(local_id).is_local(),
628                "def id points to dummy local item `{def_id:?}`"
629            );
630            ResolvedDefId::Local(local_id)
631        } else {
632            ResolvedDefId::Extern(def_id)
633        }
634    }
635
636    pub fn infer_opts(self, def_id: LocalDefId) -> config::InferOpts {
637        let mut opts = config::PartialInferOpts::default();
638        self.traverse_parents(def_id, |did| {
639            if let Some(o) = self.fhir_attr_map(did).infer_opts() {
640                opts.merge(&o);
641            }
642            None::<!>
643        });
644        opts.into()
645    }
646
647    fn matches_file_path<F>(&self, def_id: MaybeExternId, matcher: F) -> bool
648    where
649        F: Fn(&Path) -> bool,
650    {
651        let def_id = def_id.local_id();
652        let tcx = self.tcx();
653        let span = tcx.def_span(def_id);
654        let sm = tcx.sess.source_map();
655        let FileName::Real(file_name) = sm.span_to_filename(span) else { return true };
656        let Some(mut file_path) = file_name.local_path() else { return true };
657
658        // If the path is absolute try to normalize it to be relative to the working_dir
659        if file_path.is_absolute() {
660            let Some(working_dir) = sm.working_dir().local_path() else { return true };
661            let Ok(p) = file_path.strip_prefix(working_dir) else { return true };
662            file_path = p;
663        }
664
665        matcher(file_path)
666    }
667
668    fn matches_def(&self, def_id: MaybeExternId, def: &str) -> bool {
669        // Does this def_id's name contain `fn_name`?
670        let def_path = self.tcx().def_path_str(def_id.local_id());
671        def_path.contains(def)
672    }
673
674    fn matches_pos(&self, def_id: MaybeExternId, line: usize, col: usize) -> bool {
675        let def_id = def_id.local_id();
676        let tcx = self.tcx();
677        let hir_id = tcx.local_def_id_to_hir_id(def_id);
678        let body_span = tcx.hir_span_with_body(hir_id);
679        let source_map = tcx.sess.source_map();
680        let lo_pos = source_map.lookup_char_pos(body_span.lo());
681        let start_line = lo_pos.line;
682        let start_col = lo_pos.col_display;
683        let hi_pos = source_map.lookup_char_pos(body_span.hi());
684        let end_line = hi_pos.line;
685        let end_col = hi_pos.col_display;
686
687        // is the line in the range of the body?
688        if start_line < end_line {
689            // multiple lines: check if the line is in the range
690            start_line <= line && line <= end_line
691        } else {
692            // single line: check if the line is the same and the column is in range
693            start_line == line && start_col <= col && col <= end_col
694        }
695    }
696
697    /// Check whether the `def_id` (or the file where `def_id` is defined)
698    /// is in the `include` pattern, and conservatively return `true` if
699    /// anything unexpected happens.
700    fn matches_pattern(&self, def_id: MaybeExternId, pattern: &IncludePattern) -> bool {
701        if self.matches_file_path(def_id, |path| pattern.glob.is_match(path)) {
702            return true;
703        }
704        if pattern.defs.iter().any(|def| self.matches_def(def_id, def)) {
705            return true;
706        }
707        if pattern.spans.iter().any(|pos| {
708            self.matches_file_path(def_id, |path| path.ends_with(&pos.file))
709                && self.matches_pos(def_id, pos.line, pos.column)
710        }) {
711            return true;
712        }
713        false
714    }
715
716    /// Check whether the `def_id` (or the file where `def_id` is defined)
717    /// is in the `include_trusted` pattern, and conservatively return `false` if
718    /// anything unexpected happens.
719    fn matches_trusted_pattern(&self, def_id: MaybeExternId) -> bool {
720        let Some(pattern) = config::trusted_pattern() else { return false };
721        self.matches_pattern(def_id, pattern)
722    }
723
724    /// Check whether the `def_id` (or the file where `def_id` is defined)
725    /// is in the `include_trusted_impl` pattern, and conservatively return `false` if
726    /// anything unexpected happens.
727    fn matches_trusted_impl_pattern(&self, def_id: MaybeExternId) -> bool {
728        let Some(pattern) = config::trusted_impl_pattern() else { return false };
729        self.matches_pattern(def_id, pattern)
730    }
731
732    /// Check whether the `def_id` (or the file where `def_id` is defined)
733    /// is in the `include` pattern, and conservatively return `true` if
734    /// anything unexpected happens.
735    fn matches_included_pattern(&self, def_id: MaybeExternId) -> bool {
736        let Some(pattern) = config::include_pattern() else { return true };
737        self.matches_pattern(def_id, pattern)
738    }
739
740    pub fn included(&self, def_id: MaybeExternId) -> bool {
741        self.matches_included_pattern(def_id) || self.matches_trusted_pattern(def_id)
742    }
743
744    /// Transitively follow the parent-chain of `def_id` to find the first containing item with an
745    /// explicit `#[flux::trusted(..)]` annotation and return whether that item is trusted or not.
746    /// If no explicit annotation is found, return `false`.
747    pub fn trusted(self, def_id: LocalDefId) -> bool {
748        let annotation = self
749            .traverse_parents(def_id, |did| self.fhir_attr_map(did).trusted())
750            .map(|trusted| trusted.to_bool())
751            .unwrap_or_else(config::trusted_default);
752        annotation || self.matches_trusted_pattern(MaybeExternId::Local(def_id))
753    }
754
755    pub fn trusted_impl(self, def_id: LocalDefId) -> bool {
756        let annotation = self
757            .traverse_parents(def_id, |did| self.fhir_attr_map(did).trusted_impl())
758            .map(|trusted| trusted.to_bool())
759            .unwrap_or(false);
760        annotation || self.matches_trusted_impl_pattern(MaybeExternId::Local(def_id))
761    }
762
763    /// Whether code generated by a `#[derive(..)]` on this ADT should be trusted.
764    /// A `#[flux::opaque]` type implicitly trusts its derives.
765    pub fn trusted_derive(self, def_id: LocalDefId) -> bool {
766        if let Some(trusted) = self.fhir_attr_map(def_id).trusted_derive() {
767            return trusted.to_bool();
768        }
769        self.adt_def(def_id)
770            .is_ok_and(|adt_def| adt_def.is_opaque())
771    }
772
773    /// For a `def_id` generated by a `#[derive(..)]`, the ADT the derive was applied to, i.e. the
774    /// self type of the enclosing impl.
775    ///
776    /// Returns `None` if `def_id` is not an impl item or if the self type is not a local ADT. A
777    /// derive is not obliged to generate impl items: a proc-macro derive can emit a free function
778    /// at module scope, or a function inside a generated trait. In those cases the parent is a
779    /// module or trait, for which `type_of` is not defined, so the parent's kind must be checked
780    /// before asking for its type.
781    pub fn derive_self_ty(self, def_id: LocalDefId) -> Option<LocalDefId> {
782        let tcx = self.tcx();
783        let impl_id = tcx.local_parent(def_id);
784        if !matches!(tcx.def_kind(impl_id), DefKind::Impl { .. }) {
785            return None;
786        }
787        let adt_def_id = tcx
788            .type_of(impl_id)
789            .instantiate_identity()
790            .skip_norm_wip()
791            .ty_adt_def()?
792            .did();
793        match self.resolve_id(adt_def_id) {
794            ResolvedDefId::Local(local_id) | ResolvedDefId::ExternSpec(local_id, _) => {
795                Some(local_id)
796            }
797            ResolvedDefId::Extern(_) => None,
798        }
799    }
800
801    /// Same behavior as [`trusted`], but for the `#[no_suggestions]` attribute.
802    pub fn no_suggestions(self, def_id: LocalDefId) -> bool {
803        self.traverse_parents(def_id, |did| {
804            // A parent has no_suggestions, we inherit it
805            if self.fhir_attr_map(did).no_suggestions() {
806                Some(true)
807            // It doesn't have it, keep trying
808            } else {
809                None
810            }
811        })
812        .unwrap_or_else(config::no_suggestions_default)
813    }
814
815    /// Whether the item is a dummy item created by the extern spec macro.
816    ///
817    /// See [`crate::Specs::dummy_extern`]
818    pub fn is_dummy(self, def_id: LocalDefId) -> bool {
819        self.traverse_parents(def_id, |did| {
820            self.collect_specs()
821                .dummy_extern
822                .contains(&did)
823                .then_some(())
824        })
825        .is_some()
826    }
827
828    /// Transitively follow the parent-chain of `def_id` to find the first containing item with an
829    /// explicit `#[flux::ignore(..)]` annotation and return whether that item is ignored or not.
830    /// If no explicit annotation is found, return `false`.
831    pub fn ignored(self, def_id: LocalDefId) -> bool {
832        self.traverse_parents(def_id, |did| self.fhir_attr_map(did).ignored())
833            .map(|ignored| ignored.to_bool())
834            .unwrap_or_else(config::ignore_default)
835    }
836
837    /// Whether the function is marked with `#[flux::should_fail]`
838    pub fn should_fail(self, def_id: LocalDefId) -> bool {
839        self.fhir_attr_map(def_id).should_fail()
840    }
841
842    /// Whether the function is marked with `#[proven_externally]`
843    pub fn proven_externally(self, def_id: LocalDefId) -> Option<Span> {
844        self.fhir_attr_map(def_id).proven_externally()
845    }
846
847    /// Get the span of the #[sig(...)] attribute for a function, if it exists.
848    /// Checks local specs (including extern spec mapping) then falls back to cross-crate metadata.
849    pub fn spec_attr_span(self, def_id: DefId) -> Option<Span> {
850        let specs = self.collect_specs();
851        specs
852            .get_spec_attr_span(def_id)
853            .or_else(|| {
854                let local_id = specs.extern_id_to_local_id.get(&def_id)?;
855                specs.get_spec_attr_span(local_id.to_def_id())
856            })
857            .or_else(|| self.cstore().spec_attr_span(def_id))
858    }
859
860    /// Get the source text of the #[sig(...)] attribute for a function.
861    /// Reconstructs the string from the spec attribute span via the source map.
862    pub fn spec_attr_string(self, def_id: DefId) -> Option<String> {
863        let span = self.spec_attr_span(def_id)?;
864        self.tcx().sess.source_map().span_to_snippet(span).ok()
865    }
866
867    /// Traverse the parent chain of `def_id` until the first node for which `f` returns [`Some`].
868    fn traverse_parents<T>(
869        self,
870        mut def_id: LocalDefId,
871        mut f: impl FnMut(LocalDefId) -> Option<T>,
872    ) -> Option<T> {
873        loop {
874            if let Some(v) = f(def_id) {
875                break Some(v);
876            }
877
878            if let Some(parent) = self.tcx().opt_local_parent(def_id) {
879                def_id = parent;
880            } else {
881                break None;
882            }
883        }
884    }
885}
886
887impl<'genv, 'tcx> GlobalEnv<'genv, 'tcx> {
888    pub fn fhir_iter_flux_items(
889        self,
890    ) -> impl Iterator<Item = (FluxLocalDefId, fhir::FluxItem<'genv>)> {
891        self.fhir_crate()
892            .items
893            .iter()
894            .map(|(id, item)| (*id, *item))
895    }
896
897    pub fn fhir_sort_decl(&self, def_id: FluxLocalDefId) -> Option<&fhir::SortDecl> {
898        self.fhir_crate().items.get(&def_id).and_then(|item| {
899            if let fhir::FluxItem::SortDecl(sort_decl) = item { Some(*sort_decl) } else { None }
900        })
901    }
902
903    pub fn fhir_spec_func_body(
904        &self,
905        def_id: FluxLocalDefId,
906    ) -> Option<&'genv fhir::SpecFunc<'genv>> {
907        self.fhir_crate()
908            .items
909            .get(&def_id)
910            .and_then(|item| if let fhir::FluxItem::Func(defn) = item { Some(*defn) } else { None })
911    }
912
913    pub fn fhir_qualifiers(self) -> impl Iterator<Item = &'genv fhir::Qualifier<'genv>> {
914        self.fhir_crate().items.values().filter_map(|item| {
915            if let fhir::FluxItem::Qualifier(qual) = item { Some(*qual) } else { None }
916        })
917    }
918
919    pub fn fhir_primop_props(self) -> impl Iterator<Item = &'genv fhir::PrimOpProp<'genv>> {
920        self.fhir_crate().items.values().filter_map(|item| {
921            if let fhir::FluxItem::PrimOpProp(prop) = item { Some(*prop) } else { None }
922        })
923    }
924
925    pub fn fhir_get_generics(
926        self,
927        def_id: LocalDefId,
928    ) -> QueryResult<Option<&'genv fhir::Generics<'genv>>> {
929        // We don't have nodes for closures and coroutines
930        if matches!(self.def_kind(def_id), DefKind::Closure) {
931            Ok(None)
932        } else {
933            Ok(Some(self.fhir_expect_owner_node(def_id)?.generics()))
934        }
935    }
936
937    pub fn fhir_expect_refinement_kind(
938        self,
939        def_id: LocalDefId,
940    ) -> QueryResult<&'genv fhir::RefinementKind<'genv>> {
941        let kind = match &self.fhir_expect_item(def_id)?.kind {
942            fhir::ItemKind::Enum(enum_def) => &enum_def.refinement,
943            fhir::ItemKind::Struct(struct_def) => &struct_def.refinement,
944            _ => bug!("expected struct, enum or type alias"),
945        };
946        Ok(kind)
947    }
948
949    pub fn fhir_expect_item(self, def_id: LocalDefId) -> QueryResult<&'genv fhir::Item<'genv>> {
950        if let fhir::Node::Item(item) = self.fhir_node(def_id)? {
951            Ok(item)
952        } else {
953            Err(query_bug!(def_id, "expected item: `{def_id:?}`"))
954        }
955    }
956
957    pub fn fhir_expect_owner_node(self, def_id: LocalDefId) -> QueryResult<fhir::OwnerNode<'genv>> {
958        let Some(owner) = self.fhir_node(def_id)?.as_owner() else {
959            return Err(query_bug!(def_id, "cannot find owner node"));
960        };
961        Ok(owner)
962    }
963
964    pub fn fhir_node(self, def_id: LocalDefId) -> QueryResult<fhir::Node<'genv>> {
965        self.desugar(def_id)
966    }
967}
968
969#[macro_export]
970macro_rules! try_alloc_slice {
971    ($genv:expr, $slice:expr, $map:expr $(,)?) => {{
972        let slice = $slice;
973        $crate::try_alloc_slice!($genv, cap: slice.len(), slice.into_iter().map($map))
974    }};
975    ($genv:expr, cap: $cap:expr, $it:expr $(,)?) => {{
976        let mut err = None;
977        let slice = $genv.alloc_slice_with_capacity($cap, $it.into_iter().collect_errors(&mut err));
978        err.map_or(Ok(slice), Err)
979    }};
980}
981
982impl ErrorEmitter for GlobalEnv<'_, '_> {
983    fn emit<'a>(&'a self, err: impl rustc_errors::Diagnostic<'a>) -> rustc_span::ErrorGuaranteed {
984        self.sess().emit(err)
985    }
986}
987
988fn lean_parent_dir(tcx: TyCtxt) -> PathBuf {
989    tcx.sess
990        .source_map()
991        .working_dir()
992        .local_path()
993        .unwrap()
994        .join(config::lean_dir())
995}