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    LangItem,
19    def::DefKind,
20    def_id::{CrateNum, DefId, LocalDefId},
21};
22use rustc_middle::{
23    query::IntoQueryParam,
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 IntoQueryParam<DefId>) -> DefKind {
177        self.tcx().def_kind(def_id.into_query_param())
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 IntoQueryParam<FluxDefId>) -> rty::PolyFuncSort {
284        self.inner
285            .queries
286            .func_sort(self, def_id.into_query_param())
287    }
288
289    pub fn func_span(self, def_id: impl IntoQueryParam<FluxDefId>) -> Span {
290        self.inner
291            .queries
292            .func_span(self, def_id.into_query_param())
293    }
294
295    pub fn should_inline_fun(self, def_id: FluxDefId) -> bool {
296        let is_poly = self.func_sort(def_id).params().len() > 0;
297        is_poly || !flux_config::smt_define_fun()
298    }
299
300    pub fn variances_of(self, did: DefId) -> &'tcx [Variance] {
301        self.tcx().variances_of(did)
302    }
303
304    pub fn mir(self, def_id: LocalDefId) -> QueryResult<Rc<mir::BodyRoot<'tcx>>> {
305        self.inner.queries.mir(self, def_id)
306    }
307
308    pub fn lower_generics_of(self, def_id: impl IntoQueryParam<DefId>) -> ty::Generics<'tcx> {
309        self.inner
310            .queries
311            .lower_generics_of(self, def_id.into_query_param())
312    }
313
314    pub fn lower_predicates_of(
315        self,
316        def_id: impl IntoQueryParam<DefId>,
317    ) -> QueryResult<ty::GenericPredicates> {
318        self.inner
319            .queries
320            .lower_predicates_of(self, def_id.into_query_param())
321    }
322
323    pub fn lower_type_of(
324        self,
325        def_id: impl IntoQueryParam<DefId>,
326    ) -> QueryResult<ty::EarlyBinder<ty::Ty>> {
327        self.inner
328            .queries
329            .lower_type_of(self, def_id.into_query_param())
330    }
331
332    pub fn lower_fn_sig(
333        self,
334        def_id: impl Into<DefId>,
335    ) -> QueryResult<ty::EarlyBinder<ty::PolyFnSig>> {
336        self.inner.queries.lower_fn_sig(self, def_id.into())
337    }
338
339    pub fn adt_def(self, def_id: impl IntoQueryParam<DefId>) -> QueryResult<rty::AdtDef> {
340        self.inner.queries.adt_def(self, def_id.into_query_param())
341    }
342
343    pub fn constant_info(
344        self,
345        def_id: impl IntoQueryParam<DefId>,
346    ) -> QueryResult<rty::ConstantInfo> {
347        self.inner
348            .queries
349            .constant_info(self, def_id.into_query_param())
350    }
351
352    pub fn static_info(self, def_id: impl IntoQueryParam<DefId>) -> QueryResult<rty::StaticInfo> {
353        self.inner
354            .queries
355            .static_info(self, def_id.into_query_param())
356    }
357
358    pub fn adt_sort_def_of(
359        self,
360        def_id: impl IntoQueryParam<DefId>,
361    ) -> QueryResult<rty::AdtSortDef> {
362        self.inner
363            .queries
364            .adt_sort_def_of(self, def_id.into_query_param())
365    }
366
367    pub fn sort_decl_param_count(self, def_id: impl IntoQueryParam<FluxDefId>) -> usize {
368        self.inner
369            .queries
370            .sort_decl_param_count(self, def_id.into_query_param())
371    }
372
373    pub fn check_wf(self, def_id: LocalDefId) -> QueryResult<Rc<rty::WfckResults>> {
374        self.inner.queries.check_wf(self, def_id)
375    }
376
377    pub fn impl_trait_ref(self, impl_id: DefId) -> QueryResult<rty::EarlyBinder<rty::TraitRef>> {
378        let trait_ref = self.tcx().impl_trait_ref(impl_id);
379        let trait_ref = trait_ref.skip_binder();
380        let trait_ref = trait_ref
381            .lower(self.tcx())
382            .map_err(|err| QueryErr::unsupported(impl_id, err.into_err()))?
383            .refine(&Refiner::default_for_item(self, impl_id)?)?;
384        Ok(rty::EarlyBinder(trait_ref))
385    }
386
387    pub fn generics_of(self, def_id: impl IntoQueryParam<DefId>) -> QueryResult<rty::Generics> {
388        self.inner
389            .queries
390            .generics_of(self, def_id.into_query_param())
391    }
392
393    pub fn refinement_generics_of(
394        self,
395        def_id: impl IntoQueryParam<DefId>,
396    ) -> QueryResult<rty::EarlyBinder<rty::RefinementGenerics>> {
397        self.inner
398            .queries
399            .refinement_generics_of(self, def_id.into_query_param())
400    }
401
402    pub fn predicates_of(
403        self,
404        def_id: impl IntoQueryParam<DefId>,
405    ) -> QueryResult<rty::EarlyBinder<rty::GenericPredicates>> {
406        self.inner
407            .queries
408            .predicates_of(self, def_id.into_query_param())
409    }
410
411    pub fn assoc_refinements_of(
412        self,
413        def_id: impl IntoQueryParam<DefId>,
414    ) -> QueryResult<rty::AssocRefinements> {
415        self.inner
416            .queries
417            .assoc_refinements_of(self, def_id.into_query_param())
418    }
419
420    pub fn assoc_refinement(self, assoc_id: FluxDefId) -> QueryResult<rty::AssocReft> {
421        Ok(self.assoc_refinements_of(assoc_id.parent())?.get(assoc_id))
422    }
423
424    /// Given the id of an associated refinement in a trait definition returns the body for the
425    /// corresponding associated refinement in the implementation with id `impl_id`.
426    ///
427    /// This function returns [`QueryErr::MissingAssocReft`] if the associated refinement is not
428    /// found in the implementation and there's no default body in the trait. This can happen if an
429    /// extern spec adds an associated refinement without a default body because we are currently
430    /// not checking `compare_impl_item` for those definitions.
431    pub fn assoc_refinement_body_for_impl(
432        self,
433        trait_assoc_id: FluxDefId,
434        impl_id: DefId,
435    ) -> QueryResult<rty::EarlyBinder<rty::Lambda>> {
436        // Check if the implementation has the associated refinement
437        let impl_assoc_refts = self.assoc_refinements_of(impl_id)?;
438        if let Some(impl_assoc_reft) = impl_assoc_refts.find(trait_assoc_id.name()) {
439            return self.assoc_refinement_body(impl_assoc_reft.def_id());
440        }
441
442        // Otherwise, check if the trait has a default body
443        if let Some(body) = self.default_assoc_refinement_body(trait_assoc_id)? {
444            let impl_trait_ref = self.impl_trait_ref(impl_id)?.instantiate_identity();
445            return Ok(rty::EarlyBinder(body.instantiate(self.tcx(), &impl_trait_ref.args, &[])));
446        }
447
448        Err(QueryErr::MissingAssocReft {
449            impl_id,
450            trait_id: trait_assoc_id.parent(),
451            name: trait_assoc_id.name(),
452        })
453    }
454
455    pub fn default_assoc_refinement_body(
456        self,
457        trait_assoc_id: FluxDefId,
458    ) -> QueryResult<Option<rty::EarlyBinder<rty::Lambda>>> {
459        self.inner
460            .queries
461            .default_assoc_refinement_body(self, trait_assoc_id)
462    }
463
464    pub fn assoc_refinement_body(
465        self,
466        impl_assoc_id: FluxDefId,
467    ) -> QueryResult<rty::EarlyBinder<rty::Lambda>> {
468        self.inner
469            .queries
470            .assoc_refinement_body(self, impl_assoc_id)
471    }
472
473    pub fn sort_of_assoc_reft(
474        self,
475        assoc_id: FluxDefId,
476    ) -> QueryResult<rty::EarlyBinder<rty::FuncSort>> {
477        self.inner.queries.sort_of_assoc_reft(self, assoc_id)
478    }
479
480    pub fn item_bounds(
481        self,
482        def_id: impl IntoQueryParam<DefId>,
483    ) -> QueryResult<rty::EarlyBinder<List<rty::Clause>>> {
484        self.inner
485            .queries
486            .item_bounds(self, def_id.into_query_param())
487    }
488
489    pub fn type_of(
490        self,
491        def_id: impl IntoQueryParam<DefId>,
492    ) -> QueryResult<rty::EarlyBinder<rty::TyOrCtor>> {
493        self.inner.queries.type_of(self, def_id.into_query_param())
494    }
495
496    pub fn fn_sig(
497        self,
498        def_id: impl IntoQueryParam<DefId>,
499    ) -> QueryResult<rty::EarlyBinder<rty::PolyFnSig>> {
500        self.inner.queries.fn_sig(self, def_id.into_query_param())
501    }
502
503    pub fn feed_weak_kvars(self, def_id: DefId, wk: WeakKvarMap) {
504        self.inner
505            .weak_kvars
506            .borrow_mut()
507            .insert(def_id, Rc::new(wk));
508    }
509
510    pub fn weak_kvars_for(self, def_id: DefId) -> Option<Rc<WeakKvarMap>> {
511        self.inner.weak_kvars.borrow().get(&def_id).cloned()
512    }
513
514    pub fn variants_of(
515        self,
516        def_id: impl IntoQueryParam<DefId>,
517    ) -> QueryResult<rty::Opaqueness<rty::EarlyBinder<rty::PolyVariants>>> {
518        self.inner
519            .queries
520            .variants_of(self, def_id.into_query_param())
521    }
522
523    pub fn variant_sig(
524        self,
525        def_id: DefId,
526        variant_idx: VariantIdx,
527    ) -> QueryResult<rty::Opaqueness<rty::EarlyBinder<rty::PolyVariant>>> {
528        Ok(self
529            .variants_of(def_id)?
530            .map(|variants| variants.map(|variants| variants[variant_idx.as_usize()].clone())))
531    }
532
533    /// Whether the crate has Flux metadata in the cratestore.
534    pub fn cstore_has_crate(self, krate: CrateNum) -> bool {
535        self.cstore().has_crate(krate)
536    }
537
538    /// Whether the function is marked with `#[flux::no_panic]`
539    pub fn no_panic(self, def_id: impl IntoQueryParam<DefId>) -> bool {
540        self.inner.queries.no_panic(self, def_id.into_query_param())
541    }
542
543    pub fn assume_parametric_params(self, def_id: impl IntoQueryParam<DefId>) -> UnordSet<u32> {
544        self.inner
545            .queries
546            .assume_parametric_params(self, def_id.into_query_param())
547    }
548
549    pub fn is_box(&self, res: fhir::Res) -> bool {
550        res.is_box(self.tcx())
551    }
552
553    pub fn def_id_to_param_index(&self, def_id: DefId) -> u32 {
554        let parent = self.tcx().parent(def_id);
555        let generics = self.tcx().generics_of(parent);
556        generics.param_def_id_to_index(self.tcx(), def_id).unwrap()
557    }
558
559    pub(crate) fn cstore(self) -> &'genv CrateStoreDyn<'tcx> {
560        &*self.inner.cstore
561    }
562
563    pub fn has_trusted_impl(&self, def_id: DefId) -> bool {
564        if let Some(did) = self
565            .resolve_id(def_id)
566            .as_maybe_extern()
567            .map(|id| id.local_id())
568        {
569            self.trusted_impl(did)
570        } else {
571            false
572        }
573    }
574
575    /// The `Output` associated type is defined in `FnOnce`, and `Fn`/`FnMut`
576    /// inherit it, so this should suffice to check if the `def_id`
577    /// corresponds to `LangItem::FnOnceOutput`.
578    pub fn is_fn_output(&self, def_id: DefId) -> bool {
579        let def_span = self.tcx().def_span(def_id);
580        self.tcx()
581            .require_lang_item(LangItem::FnOnceOutput, def_span)
582            == def_id
583    }
584
585    /// Returns whether `def_id` is the `call` method in the `Fn` trait,
586    /// the `call_mut` method in the `FnMut` trait,
587    /// or the `call_once` method in the `FnOnce` trait.
588    pub fn is_fn_call(&self, def_id: DefId) -> bool {
589        let methods_and_names = [
590            (LangItem::Fn, sym::call),
591            (LangItem::FnMut, sym::call_mut),
592            (LangItem::FnOnce, sym::call_once),
593        ];
594        let tcx = self.tcx();
595        let Some(assoc_item) = tcx.opt_associated_item(def_id) else { return false };
596        let Some(trait_id) = assoc_item.trait_container(tcx) else { return false };
597
598        methods_and_names.iter().any(|(lang_item, method_name)| {
599            assoc_item.name() == *method_name && tcx.is_lang_item(trait_id, *lang_item)
600        })
601    }
602
603    /// Iterator over all local def ids that are not an extern spec
604    pub fn iter_local_def_id(self) -> impl Iterator<Item = LocalDefId> + use<'tcx, 'genv> {
605        self.tcx().iter_local_def_id().filter(move |&local_def_id| {
606            self.maybe_extern_id(local_def_id).is_local() && !self.is_dummy(local_def_id)
607        })
608    }
609
610    pub fn iter_extern_def_id(self) -> impl Iterator<Item = DefId> + use<'tcx, 'genv> {
611        self.tcx()
612            .iter_local_def_id()
613            .filter_map(move |local_def_id| self.maybe_extern_id(local_def_id).as_extern())
614    }
615
616    pub fn maybe_extern_id(self, local_id: LocalDefId) -> MaybeExternId {
617        self.collect_specs()
618            .local_id_to_extern_id
619            .get(&local_id)
620            .map_or_else(
621                || MaybeExternId::Local(local_id),
622                |def_id| MaybeExternId::Extern(local_id, *def_id),
623            )
624    }
625
626    #[expect(clippy::disallowed_methods)]
627    pub fn resolve_id(self, def_id: DefId) -> ResolvedDefId {
628        let maybe_extern_spec = self
629            .collect_specs()
630            .extern_id_to_local_id
631            .get(&def_id)
632            .copied();
633        if let Some(local_id) = maybe_extern_spec {
634            ResolvedDefId::ExternSpec(local_id, def_id)
635        } else if let Some(local_id) = def_id.as_local() {
636            debug_assert!(
637                self.maybe_extern_id(local_id).is_local(),
638                "def id points to dummy local item `{def_id:?}`"
639            );
640            ResolvedDefId::Local(local_id)
641        } else {
642            ResolvedDefId::Extern(def_id)
643        }
644    }
645
646    pub fn infer_opts(self, def_id: LocalDefId) -> config::InferOpts {
647        let mut opts = config::PartialInferOpts::default();
648        self.traverse_parents(def_id, |did| {
649            if let Some(o) = self.fhir_attr_map(did).infer_opts() {
650                opts.merge(&o);
651            }
652            None::<!>
653        });
654        opts.into()
655    }
656
657    fn matches_file_path<F>(&self, def_id: MaybeExternId, matcher: F) -> bool
658    where
659        F: Fn(&Path) -> bool,
660    {
661        let def_id = def_id.local_id();
662        let tcx = self.tcx();
663        let span = tcx.def_span(def_id);
664        let sm = tcx.sess.source_map();
665        let FileName::Real(file_name) = sm.span_to_filename(span) else { return true };
666        let Some(mut file_path) = file_name.local_path() else { return true };
667
668        // If the path is absolute try to normalize it to be relative to the working_dir
669        if file_path.is_absolute() {
670            let Some(working_dir) = sm.working_dir().local_path() else { return true };
671            let Ok(p) = file_path.strip_prefix(working_dir) else { return true };
672            file_path = p;
673        }
674
675        matcher(file_path)
676    }
677
678    fn matches_def(&self, def_id: MaybeExternId, def: &str) -> bool {
679        // Does this def_id's name contain `fn_name`?
680        let def_path = self.tcx().def_path_str(def_id.local_id());
681        def_path.contains(def)
682    }
683
684    fn matches_pos(&self, def_id: MaybeExternId, line: usize, col: usize) -> bool {
685        let def_id = def_id.local_id();
686        let tcx = self.tcx();
687        let hir_id = tcx.local_def_id_to_hir_id(def_id);
688        let body_span = tcx.hir_span_with_body(hir_id);
689        let source_map = tcx.sess.source_map();
690        let lo_pos = source_map.lookup_char_pos(body_span.lo());
691        let start_line = lo_pos.line;
692        let start_col = lo_pos.col_display;
693        let hi_pos = source_map.lookup_char_pos(body_span.hi());
694        let end_line = hi_pos.line;
695        let end_col = hi_pos.col_display;
696
697        // is the line in the range of the body?
698        if start_line < end_line {
699            // multiple lines: check if the line is in the range
700            start_line <= line && line <= end_line
701        } else {
702            // single line: check if the line is the same and the column is in range
703            start_line == line && start_col <= col && col <= end_col
704        }
705    }
706
707    /// Check whether the `def_id` (or the file where `def_id` is defined)
708    /// is in the `include` pattern, and conservatively return `true` if
709    /// anything unexpected happens.
710    fn matches_pattern(&self, def_id: MaybeExternId, pattern: &IncludePattern) -> bool {
711        if self.matches_file_path(def_id, |path| pattern.glob.is_match(path)) {
712            return true;
713        }
714        if pattern.defs.iter().any(|def| self.matches_def(def_id, def)) {
715            return true;
716        }
717        if pattern.spans.iter().any(|pos| {
718            self.matches_file_path(def_id, |path| path.ends_with(&pos.file))
719                && self.matches_pos(def_id, pos.line, pos.column)
720        }) {
721            return true;
722        }
723        false
724    }
725
726    /// Check whether the `def_id` (or the file where `def_id` is defined)
727    /// is in the `include_trusted` pattern, and conservatively return `false` if
728    /// anything unexpected happens.
729    fn matches_trusted_pattern(&self, def_id: MaybeExternId) -> bool {
730        let Some(pattern) = config::trusted_pattern() else { return false };
731        self.matches_pattern(def_id, pattern)
732    }
733
734    /// Check whether the `def_id` (or the file where `def_id` is defined)
735    /// is in the `include_trusted_impl` pattern, and conservatively return `false` if
736    /// anything unexpected happens.
737    fn matches_trusted_impl_pattern(&self, def_id: MaybeExternId) -> bool {
738        let Some(pattern) = config::trusted_impl_pattern() else { return false };
739        self.matches_pattern(def_id, pattern)
740    }
741
742    /// Check whether the `def_id` (or the file where `def_id` is defined)
743    /// is in the `include` pattern, and conservatively return `true` if
744    /// anything unexpected happens.
745    fn matches_included_pattern(&self, def_id: MaybeExternId) -> bool {
746        let Some(pattern) = config::include_pattern() else { return true };
747        self.matches_pattern(def_id, pattern)
748    }
749
750    pub fn included(&self, def_id: MaybeExternId) -> bool {
751        self.matches_included_pattern(def_id) || self.matches_trusted_pattern(def_id)
752    }
753
754    /// Transitively follow the parent-chain of `def_id` to find the first containing item with an
755    /// explicit `#[flux::trusted(..)]` annotation and return whether that item is trusted or not.
756    /// If no explicit annotation is found, return `false`.
757    pub fn trusted(self, def_id: LocalDefId) -> bool {
758        let annotation = self
759            .traverse_parents(def_id, |did| self.fhir_attr_map(did).trusted())
760            .map(|trusted| trusted.to_bool())
761            .unwrap_or_else(config::trusted_default);
762        annotation || self.matches_trusted_pattern(MaybeExternId::Local(def_id))
763    }
764
765    pub fn trusted_impl(self, def_id: LocalDefId) -> bool {
766        let annotation = self
767            .traverse_parents(def_id, |did| self.fhir_attr_map(did).trusted_impl())
768            .map(|trusted| trusted.to_bool())
769            .unwrap_or(false);
770        annotation || self.matches_trusted_impl_pattern(MaybeExternId::Local(def_id))
771    }
772
773    /// Same behavior as [`trusted`], but for the `#[no_suggestions]` attribute.
774    pub fn no_suggestions(self, def_id: LocalDefId) -> bool {
775        self.traverse_parents(def_id, |did| {
776            // A parent has no_suggestions, we inherit it
777            if self.fhir_attr_map(did).no_suggestions() {
778                Some(true)
779            // It doesn't have it, keep trying
780            } else {
781                None
782            }
783        })
784        .unwrap_or_else(config::no_suggestions_default)
785    }
786
787    /// Whether the item is a dummy item created by the extern spec macro.
788    ///
789    /// See [`crate::Specs::dummy_extern`]
790    pub fn is_dummy(self, def_id: LocalDefId) -> bool {
791        self.traverse_parents(def_id, |did| {
792            self.collect_specs()
793                .dummy_extern
794                .contains(&did)
795                .then_some(())
796        })
797        .is_some()
798    }
799
800    /// Transitively follow the parent-chain of `def_id` to find the first containing item with an
801    /// explicit `#[flux::ignore(..)]` annotation and return whether that item is ignored or not.
802    /// If no explicit annotation is found, return `false`.
803    pub fn ignored(self, def_id: LocalDefId) -> bool {
804        self.traverse_parents(def_id, |did| self.fhir_attr_map(did).ignored())
805            .map(|ignored| ignored.to_bool())
806            .unwrap_or_else(config::ignore_default)
807    }
808
809    /// Whether the function is marked with `#[flux::should_fail]`
810    pub fn should_fail(self, def_id: LocalDefId) -> bool {
811        self.fhir_attr_map(def_id).should_fail()
812    }
813
814    /// Whether the function is marked with `#[proven_externally]`
815    pub fn proven_externally(self, def_id: LocalDefId) -> Option<Span> {
816        self.fhir_attr_map(def_id).proven_externally()
817    }
818
819    /// Get the span of the #[sig(...)] attribute for a function, if it exists.
820    /// Checks local specs (including extern spec mapping) then falls back to cross-crate metadata.
821    pub fn spec_attr_span(self, def_id: DefId) -> Option<Span> {
822        let specs = self.collect_specs();
823        specs
824            .get_spec_attr_span(def_id)
825            .or_else(|| {
826                let local_id = specs.extern_id_to_local_id.get(&def_id)?;
827                specs.get_spec_attr_span(local_id.to_def_id())
828            })
829            .or_else(|| self.cstore().spec_attr_span(def_id))
830    }
831
832    /// Get the source text of the #[sig(...)] attribute for a function.
833    /// Reconstructs the string from the spec attribute span via the source map.
834    pub fn spec_attr_string(self, def_id: DefId) -> Option<String> {
835        let span = self.spec_attr_span(def_id)?;
836        self.tcx().sess.source_map().span_to_snippet(span).ok()
837    }
838
839    /// Traverse the parent chain of `def_id` until the first node for which `f` returns [`Some`].
840    fn traverse_parents<T>(
841        self,
842        mut def_id: LocalDefId,
843        mut f: impl FnMut(LocalDefId) -> Option<T>,
844    ) -> Option<T> {
845        loop {
846            if let Some(v) = f(def_id) {
847                break Some(v);
848            }
849
850            if let Some(parent) = self.tcx().opt_local_parent(def_id) {
851                def_id = parent;
852            } else {
853                break None;
854            }
855        }
856    }
857}
858
859impl<'genv, 'tcx> GlobalEnv<'genv, 'tcx> {
860    pub fn fhir_iter_flux_items(
861        self,
862    ) -> impl Iterator<Item = (FluxLocalDefId, fhir::FluxItem<'genv>)> {
863        self.fhir_crate()
864            .items
865            .iter()
866            .map(|(id, item)| (*id, *item))
867    }
868
869    pub fn fhir_sort_decl(&self, def_id: FluxLocalDefId) -> Option<&fhir::SortDecl> {
870        self.fhir_crate().items.get(&def_id).and_then(|item| {
871            if let fhir::FluxItem::SortDecl(sort_decl) = item { Some(*sort_decl) } else { None }
872        })
873    }
874
875    pub fn fhir_spec_func_body(
876        &self,
877        def_id: FluxLocalDefId,
878    ) -> Option<&'genv fhir::SpecFunc<'genv>> {
879        self.fhir_crate()
880            .items
881            .get(&def_id)
882            .and_then(|item| if let fhir::FluxItem::Func(defn) = item { Some(*defn) } else { None })
883    }
884
885    pub fn fhir_qualifiers(self) -> impl Iterator<Item = &'genv fhir::Qualifier<'genv>> {
886        self.fhir_crate().items.values().filter_map(|item| {
887            if let fhir::FluxItem::Qualifier(qual) = item { Some(*qual) } else { None }
888        })
889    }
890
891    pub fn fhir_primop_props(self) -> impl Iterator<Item = &'genv fhir::PrimOpProp<'genv>> {
892        self.fhir_crate().items.values().filter_map(|item| {
893            if let fhir::FluxItem::PrimOpProp(prop) = item { Some(*prop) } else { None }
894        })
895    }
896
897    pub fn fhir_get_generics(
898        self,
899        def_id: LocalDefId,
900    ) -> QueryResult<Option<&'genv fhir::Generics<'genv>>> {
901        // We don't have nodes for closures and coroutines
902        if matches!(self.def_kind(def_id), DefKind::Closure) {
903            Ok(None)
904        } else {
905            Ok(Some(self.fhir_expect_owner_node(def_id)?.generics()))
906        }
907    }
908
909    pub fn fhir_expect_refinement_kind(
910        self,
911        def_id: LocalDefId,
912    ) -> QueryResult<&'genv fhir::RefinementKind<'genv>> {
913        let kind = match &self.fhir_expect_item(def_id)?.kind {
914            fhir::ItemKind::Enum(enum_def) => &enum_def.refinement,
915            fhir::ItemKind::Struct(struct_def) => &struct_def.refinement,
916            _ => bug!("expected struct, enum or type alias"),
917        };
918        Ok(kind)
919    }
920
921    pub fn fhir_expect_item(self, def_id: LocalDefId) -> QueryResult<&'genv fhir::Item<'genv>> {
922        if let fhir::Node::Item(item) = self.fhir_node(def_id)? {
923            Ok(item)
924        } else {
925            Err(query_bug!(def_id, "expected item: `{def_id:?}`"))
926        }
927    }
928
929    pub fn fhir_expect_owner_node(self, def_id: LocalDefId) -> QueryResult<fhir::OwnerNode<'genv>> {
930        let Some(owner) = self.fhir_node(def_id)?.as_owner() else {
931            return Err(query_bug!(def_id, "cannot find owner node"));
932        };
933        Ok(owner)
934    }
935
936    pub fn fhir_node(self, def_id: LocalDefId) -> QueryResult<fhir::Node<'genv>> {
937        self.desugar(def_id)
938    }
939}
940
941#[macro_export]
942macro_rules! try_alloc_slice {
943    ($genv:expr, $slice:expr, $map:expr $(,)?) => {{
944        let slice = $slice;
945        $crate::try_alloc_slice!($genv, cap: slice.len(), slice.into_iter().map($map))
946    }};
947    ($genv:expr, cap: $cap:expr, $it:expr $(,)?) => {{
948        let mut err = None;
949        let slice = $genv.alloc_slice_with_capacity($cap, $it.into_iter().collect_errors(&mut err));
950        err.map_or(Ok(slice), Err)
951    }};
952}
953
954impl ErrorEmitter for GlobalEnv<'_, '_> {
955    fn emit<'a>(&'a self, err: impl rustc_errors::Diagnostic<'a>) -> rustc_span::ErrorGuaranteed {
956        self.sess().emit(err)
957    }
958}
959
960fn lean_parent_dir(tcx: TyCtxt) -> PathBuf {
961    tcx.sess
962        .source_map()
963        .working_dir()
964        .local_path()
965        .unwrap()
966        .join(config::lean_dir())
967}