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