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_attr_ir::LangItem;
17use rustc_data_structures::unord::{UnordMap, UnordSet};
18use rustc_hir::{
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 cstore::CrateStoreDyn,
33 def_id::{FluxDefId, FluxLocalDefId, MaybeExternId, ResolvedDefId},
34 dep_graph::NodeKey,
35 fhir::{self, VariantIdx},
36 queries::{DispatchKey, Providers, Queries, QueryErr, QueryResult},
37 query_bug,
38 rty::{
39 self, HintKind,
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 pub solutions: Vec<rty::Binder<rty::Expr>>,
53 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 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 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 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 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 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::dep_graph::CallGraph<'tcx> {
207 self.inner.queries.call_graph(self)
208 }
209
210 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 pub fn inferred_no_panic_local(self) -> Rc<UnordMap<NodeKey<'tcx>, PanicSpec>> {
221 self.inner.queries.inferred_no_panic(self)
222 }
223
224 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> {
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 pub fn spec_func_rank(self, did: FluxDefId) -> usize {
255 self.spec_funcs(did.krate()).rank(did.index())
256 }
257
258 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(
268 self,
269 op: &rty::BinOp,
270 did: Option<LocalDefId>,
271 ) -> QueryResult<Option<rty::Binder<rty::Expr>>> {
272 let Some(prim_rel) = self.inner.queries.prim_rel(self)?.get(op) else {
273 return Ok(None);
274 };
275 let names: UnordSet<_> = did
276 .map(|did| self.fhir_attr_map(did).properties.iter().copied().collect())
277 .unwrap_or_default();
278 let bodies = prim_rel
279 .props
280 .iter()
281 .filter(|prop| {
282 match did {
283 Some(did) => self.hint_applies(prop.kind, prop.def_id, &names, did),
284 None => matches!(prop.kind, HintKind::Global),
285 }
286 })
287 .map(|prop| &prop.body);
288 Ok(rty::Expr::conjoin_bodies(bodies))
289 }
290
291 pub fn qualifiers(self) -> QueryResult<&'genv [rty::Qualifier]> {
292 self.inner.queries.qualifiers(self)
293 }
294
295 pub fn axioms(self) -> QueryResult<&'genv [rty::Axiom]> {
297 self.inner.queries.axioms(self)
298 }
299
300 pub fn axioms_for(
303 self,
304 did: LocalDefId,
305 ) -> QueryResult<impl Iterator<Item = &'genv rty::Axiom>> {
306 let names: UnordSet<_> = self.fhir_attr_map(did).axioms.iter().copied().collect();
307 Ok(self
308 .axioms()?
309 .iter()
310 .filter(move |axiom| self.hint_applies(axiom.kind, axiom.def_id, &names, did)))
311 }
312
313 pub fn qualifiers_for(
315 self,
316 did: LocalDefId,
317 ) -> QueryResult<impl Iterator<Item = &'genv rty::Qualifier>> {
318 let names: UnordSet<_> = self.fhir_attr_map(did).qualifiers.iter().copied().collect();
319 Ok(self
320 .qualifiers()?
321 .iter()
322 .filter(move |qual| self.hint_applies(qual.kind, qual.def_id, &names, did)))
323 }
324
325 fn hint_applies(
328 self,
329 kind: HintKind,
330 hint_id: FluxLocalDefId,
331 names: &UnordSet<FluxDefId>,
332 did: LocalDefId,
333 ) -> bool {
334 match kind {
335 HintKind::Global => true,
336 HintKind::Local => names.contains(&hint_id.to_def_id()),
337 HintKind::Enclosing => {
338 self.flux_item_enclosing_item(hint_id.to_def_id()) == did.to_def_id()
339 }
340 }
341 }
342
343 fn flux_item_enclosing_item(self, def_id: FluxDefId) -> DefId {
347 let declarer = def_id.parent();
348 if self.def_kind(declarer) == DefKind::Const {
349 self.tcx().typeck_root_def_id(self.tcx().parent(declarer))
350 } else {
351 declarer
352 }
353 }
354
355 pub fn reveals_for(self, did: LocalDefId) -> impl Iterator<Item = FluxDefId> + 'genv {
357 self.fhir_attr_map(did)
358 .reveals
359 .iter()
360 .map(|(def_id, _)| *def_id)
361 }
362
363 pub fn hides_for(self, did: LocalDefId) -> impl Iterator<Item = FluxDefId> + 'genv {
365 self.fhir_attr_map(did)
366 .hides
367 .iter()
368 .map(|(def_id, _)| *def_id)
369 }
370
371 pub fn func_sort(self, def_id: impl IntoQueryKey<FluxDefId>) -> rty::PolyFuncSort {
372 self.inner.queries.func_sort(self, def_id.into_query_key())
373 }
374
375 pub fn func_span(self, def_id: impl IntoQueryKey<FluxDefId>) -> Span {
376 self.inner.queries.func_span(self, def_id.into_query_key())
377 }
378
379 pub fn should_inline_fun(self, def_id: FluxDefId) -> bool {
383 self.func_sort(def_id).params().len() > 0
384 }
385
386 pub fn variances_of(self, did: DefId) -> &'tcx [Variance] {
387 self.tcx().variances_of(did)
388 }
389
390 pub fn mir(self, def_id: LocalDefId) -> QueryResult<Rc<mir::BodyRoot<'tcx>>> {
391 self.inner.queries.mir(self, def_id)
392 }
393
394 pub fn lower_generics_of(self, def_id: impl IntoQueryKey<DefId>) -> ty::Generics<'tcx> {
395 self.inner
396 .queries
397 .lower_generics_of(self, def_id.into_query_key())
398 }
399
400 pub fn lower_predicates_of(
401 self,
402 def_id: impl IntoQueryKey<DefId>,
403 ) -> QueryResult<ty::GenericPredicates> {
404 self.inner
405 .queries
406 .lower_predicates_of(self, def_id.into_query_key())
407 }
408
409 pub fn lower_type_of(
410 self,
411 def_id: impl IntoQueryKey<DefId>,
412 ) -> QueryResult<ty::EarlyBinder<ty::Ty>> {
413 self.inner
414 .queries
415 .lower_type_of(self, def_id.into_query_key())
416 }
417
418 pub fn lower_fn_sig(
419 self,
420 def_id: impl Into<DefId>,
421 ) -> QueryResult<ty::EarlyBinder<ty::PolyFnSig>> {
422 self.inner.queries.lower_fn_sig(self, def_id.into())
423 }
424
425 pub fn adt_def(self, def_id: impl IntoQueryKey<DefId>) -> QueryResult<rty::AdtDef> {
426 self.inner.queries.adt_def(self, def_id.into_query_key())
427 }
428
429 pub fn invariants_of(
430 self,
431 def_id: impl IntoQueryKey<DefId>,
432 ) -> rty::EarlyBinder<List<rty::Invariant>> {
433 self.inner
434 .queries
435 .invariants_of(self, def_id.into_query_key())
436 }
437
438 pub fn constant_info(self, def_id: impl IntoQueryKey<DefId>) -> QueryResult<rty::ConstantInfo> {
439 self.inner
440 .queries
441 .constant_info(self, def_id.into_query_key())
442 }
443
444 pub fn static_info(self, def_id: impl IntoQueryKey<DefId>) -> QueryResult<rty::Ty> {
446 self.inner
447 .queries
448 .static_info(self, def_id.into_query_key())
449 }
450
451 pub fn adt_sort_def_of(self, def_id: impl IntoQueryKey<DefId>) -> QueryResult<rty::AdtSortDef> {
452 self.inner
453 .queries
454 .adt_sort_def_of(self, def_id.into_query_key())
455 }
456
457 pub fn sort_decl_param_count(self, def_id: impl IntoQueryKey<FluxDefId>) -> usize {
458 self.inner
459 .queries
460 .sort_decl_param_count(self, def_id.into_query_key())
461 }
462
463 pub fn check_wf(self, def_id: LocalDefId) -> QueryResult<Rc<rty::WfckResults>> {
464 self.inner.queries.check_wf(self, def_id)
465 }
466
467 pub fn late_bound_refinement_params(
475 self,
476 def_id: LocalDefId,
477 ) -> QueryResult<&'genv [fhir::ParamId]> {
478 self.inner
479 .queries
480 .late_bound_refinement_params(self, def_id)
481 }
482
483 pub fn impl_trait_ref(self, impl_id: DefId) -> QueryResult<rty::EarlyBinder<rty::TraitRef>> {
484 let trait_ref = self.tcx().impl_trait_ref(impl_id);
485 let trait_ref = trait_ref.skip_binder();
486 let trait_ref = trait_ref
487 .lower(self.tcx())
488 .map_err(|err| QueryErr::unsupported(impl_id, err.into_err()))?
489 .refine(&Refiner::default_for_item(self, impl_id)?)?;
490 Ok(rty::EarlyBinder(trait_ref))
491 }
492
493 pub fn generics_of(self, def_id: impl IntoQueryKey<DefId>) -> QueryResult<rty::Generics> {
494 self.inner
495 .queries
496 .generics_of(self, def_id.into_query_key())
497 }
498
499 pub fn refinement_generics_of(
500 self,
501 def_id: impl IntoQueryKey<DefId>,
502 ) -> QueryResult<rty::EarlyBinder<rty::RefinementGenerics>> {
503 self.inner
504 .queries
505 .refinement_generics_of(self, def_id.into_query_key())
506 }
507
508 pub fn predicates_of(
509 self,
510 def_id: impl IntoQueryKey<DefId>,
511 ) -> QueryResult<rty::EarlyBinder<rty::GenericPredicates>> {
512 self.inner
513 .queries
514 .predicates_of(self, def_id.into_query_key())
515 }
516
517 pub fn assoc_refinements_of(
518 self,
519 def_id: impl IntoQueryKey<DefId>,
520 ) -> QueryResult<rty::AssocRefinements> {
521 self.inner
522 .queries
523 .assoc_refinements_of(self, def_id.into_query_key())
524 }
525
526 pub fn assoc_refinement(self, assoc_id: FluxDefId) -> QueryResult<rty::AssocReft> {
527 Ok(self.assoc_refinements_of(assoc_id.parent())?.get(assoc_id))
528 }
529
530 pub fn assoc_refinement_body_for_impl(
538 self,
539 trait_assoc_id: FluxDefId,
540 impl_id: DefId,
541 ) -> QueryResult<rty::EarlyBinder<rty::Lambda>> {
542 let impl_assoc_refts = self.assoc_refinements_of(impl_id)?;
544 if let Some(impl_assoc_reft) = impl_assoc_refts.find(trait_assoc_id.name()) {
545 return self.assoc_refinement_body(impl_assoc_reft.def_id());
546 }
547
548 if let Some(body) = self.default_assoc_refinement_body(trait_assoc_id)? {
550 let impl_trait_ref = self.impl_trait_ref(impl_id)?.instantiate_identity();
551 return Ok(rty::EarlyBinder(body.instantiate(self.tcx(), &impl_trait_ref.args, &[])));
552 }
553
554 Err(QueryErr::MissingAssocReft {
555 impl_id,
556 trait_id: trait_assoc_id.parent(),
557 name: trait_assoc_id.name(),
558 })
559 }
560
561 pub fn default_assoc_refinement_body(
562 self,
563 trait_assoc_id: FluxDefId,
564 ) -> QueryResult<Option<rty::EarlyBinder<rty::Lambda>>> {
565 self.inner
566 .queries
567 .default_assoc_refinement_body(self, trait_assoc_id)
568 }
569
570 pub fn assoc_refinement_body(
571 self,
572 impl_assoc_id: FluxDefId,
573 ) -> QueryResult<rty::EarlyBinder<rty::Lambda>> {
574 self.inner
575 .queries
576 .assoc_refinement_body(self, impl_assoc_id)
577 }
578
579 pub fn sort_of_assoc_reft(
580 self,
581 assoc_id: FluxDefId,
582 ) -> QueryResult<rty::EarlyBinder<rty::FuncSort>> {
583 self.inner.queries.sort_of_assoc_reft(self, assoc_id)
584 }
585
586 pub fn item_bounds(
587 self,
588 def_id: impl IntoQueryKey<DefId>,
589 ) -> QueryResult<rty::EarlyBinder<List<rty::Clause>>> {
590 self.inner
591 .queries
592 .item_bounds(self, def_id.into_query_key())
593 }
594
595 pub fn type_of(
596 self,
597 def_id: impl IntoQueryKey<DefId>,
598 ) -> QueryResult<rty::EarlyBinder<rty::TyOrCtor>> {
599 self.inner.queries.type_of(self, def_id.into_query_key())
600 }
601
602 pub fn fn_sig(
603 self,
604 def_id: impl IntoQueryKey<DefId>,
605 ) -> QueryResult<rty::EarlyBinder<rty::PolyFnSig>> {
606 self.inner.queries.fn_sig(self, def_id.into_query_key())
607 }
608
609 pub fn feed_weak_kvars(self, def_id: DefId, wk: WeakKvarMap) {
610 self.inner
611 .weak_kvars
612 .borrow_mut()
613 .insert(def_id, Rc::new(wk));
614 }
615
616 pub fn weak_kvars_for(self, def_id: DefId) -> Option<Rc<WeakKvarMap>> {
617 self.inner.weak_kvars.borrow().get(&def_id).cloned()
618 }
619
620 pub fn variants_of(
621 self,
622 def_id: impl IntoQueryKey<DefId>,
623 ) -> QueryResult<rty::Opaqueness<rty::EarlyBinder<rty::PolyVariants>>> {
624 self.inner
625 .queries
626 .variants_of(self, def_id.into_query_key())
627 }
628
629 pub fn variant_sig(
630 self,
631 def_id: DefId,
632 variant_idx: VariantIdx,
633 ) -> QueryResult<rty::Opaqueness<rty::EarlyBinder<rty::PolyVariant>>> {
634 Ok(self
635 .variants_of(def_id)?
636 .map(|variants| variants.map(|variants| variants[variant_idx.as_usize()].clone())))
637 }
638
639 pub fn cstore_has_crate(self, krate: CrateNum) -> bool {
641 self.cstore().has_crate(krate)
642 }
643
644 pub fn no_panic(self, def_id: impl IntoQueryKey<DefId>) -> bool {
646 self.inner.queries.no_panic(self, def_id.into_query_key())
647 }
648
649 pub fn assume_parametric_params(self, def_id: impl IntoQueryKey<DefId>) -> UnordSet<u32> {
650 self.inner
651 .queries
652 .assume_parametric_params(self, def_id.into_query_key())
653 }
654
655 pub fn is_box(&self, res: fhir::Res) -> bool {
656 res.is_box(self.tcx())
657 }
658
659 pub fn def_id_to_param_index(&self, def_id: DefId) -> u32 {
660 let parent = self.tcx().parent(def_id);
661 let generics = self.tcx().generics_of(parent);
662 generics.param_def_id_to_index(self.tcx(), def_id).unwrap()
663 }
664
665 pub(crate) fn cstore(self) -> &'genv CrateStoreDyn<'tcx> {
666 &*self.inner.cstore
667 }
668
669 pub fn has_trusted_impl(&self, def_id: DefId) -> bool {
670 if let Some(did) = self
671 .resolve_id(def_id)
672 .as_maybe_extern()
673 .map(|id| id.local_id())
674 {
675 self.trusted_impl(did)
676 } else {
677 false
678 }
679 }
680
681 pub fn is_fn_output(&self, def_id: DefId) -> bool {
685 let def_span = self.tcx().def_span(def_id);
686 self.tcx()
687 .require_lang_item(LangItem::FnOnceOutput, def_span)
688 == def_id
689 }
690
691 pub fn is_fn_call(&self, def_id: DefId) -> bool {
695 let methods_and_names = [
696 (LangItem::Fn, sym::call),
697 (LangItem::FnMut, sym::call_mut),
698 (LangItem::FnOnce, sym::call_once),
699 ];
700 let tcx = self.tcx();
701 let Some(assoc_item) = tcx.opt_associated_item(def_id) else { return false };
702 let Some(trait_id) = assoc_item.trait_container(tcx) else { return false };
703
704 methods_and_names.iter().any(|(lang_item, method_name)| {
705 assoc_item.name() == *method_name && tcx.is_lang_item(trait_id, *lang_item)
706 })
707 }
708
709 pub fn iter_local_def_id(self) -> impl Iterator<Item = LocalDefId> + use<'tcx, 'genv> {
711 self.tcx().iter_local_def_id().filter(move |&local_def_id| {
712 self.maybe_extern_id(local_def_id).is_local() && !self.is_dummy(local_def_id)
713 })
714 }
715
716 pub fn iter_extern_def_id(self) -> impl Iterator<Item = DefId> + use<'tcx, 'genv> {
717 self.tcx()
718 .iter_local_def_id()
719 .filter_map(move |local_def_id| self.maybe_extern_id(local_def_id).as_extern())
720 }
721
722 pub fn maybe_extern_id(self, local_id: LocalDefId) -> MaybeExternId {
723 self.collect_specs()
724 .local_id_to_extern_id
725 .get(&local_id)
726 .map_or_else(
727 || MaybeExternId::Local(local_id),
728 |def_id| MaybeExternId::Extern(local_id, *def_id),
729 )
730 }
731
732 #[expect(clippy::disallowed_methods)]
733 pub fn resolve_id(self, def_id: DefId) -> ResolvedDefId {
734 let maybe_extern_spec = self
735 .collect_specs()
736 .extern_id_to_local_id
737 .get(&def_id)
738 .copied();
739 if let Some(local_id) = maybe_extern_spec {
740 ResolvedDefId::ExternSpec(local_id, def_id)
741 } else if let Some(local_id) = def_id.as_local() {
742 debug_assert!(
743 self.maybe_extern_id(local_id).is_local(),
744 "def id points to dummy local item `{def_id:?}`"
745 );
746 ResolvedDefId::Local(local_id)
747 } else {
748 ResolvedDefId::Extern(def_id)
749 }
750 }
751
752 pub fn infer_opts(self, def_id: LocalDefId) -> config::InferOpts {
753 let mut opts = config::PartialInferOpts::default();
754 self.traverse_parents(def_id, |did| {
755 if let Some(o) = self.fhir_attr_map(did).infer_opts() {
756 opts.merge(&o);
757 }
758 None::<!>
759 });
760 opts.into()
761 }
762
763 fn matches_file_path<F>(&self, def_id: MaybeExternId, matcher: F) -> bool
764 where
765 F: Fn(&Path) -> bool,
766 {
767 let def_id = def_id.local_id();
768 let tcx = self.tcx();
769 let span = tcx.def_span(def_id);
770 let sm = tcx.sess.source_map();
771 let FileName::Real(file_name) = sm.span_to_filename(span) else { return true };
772 let Some(mut file_path) = file_name.local_path() else { return true };
773
774 if file_path.is_absolute() {
776 let Some(working_dir) = sm.working_dir().local_path() else { return true };
777 let Ok(p) = file_path.strip_prefix(working_dir) else { return true };
778 file_path = p;
779 }
780
781 matcher(file_path)
782 }
783
784 fn matches_def(&self, def_id: MaybeExternId, def: &str) -> bool {
785 let def_path = self.tcx().def_path_str(def_id.local_id());
787 def_path.contains(def)
788 }
789
790 fn matches_pos(&self, def_id: MaybeExternId, line: usize, col: usize) -> bool {
791 let def_id = def_id.local_id();
792 let tcx = self.tcx();
793 let hir_id = tcx.local_def_id_to_hir_id(def_id);
794 let body_span = tcx.hir_span_with_body(hir_id);
795 let source_map = tcx.sess.source_map();
796 let lo_pos = source_map.lookup_char_pos(body_span.lo());
797 let start_line = lo_pos.line;
798 let start_col = lo_pos.col_display;
799 let hi_pos = source_map.lookup_char_pos(body_span.hi());
800 let end_line = hi_pos.line;
801 let end_col = hi_pos.col_display;
802
803 if start_line < end_line {
805 start_line <= line && line <= end_line
807 } else {
808 start_line == line && start_col <= col && col <= end_col
810 }
811 }
812
813 fn matches_pattern(&self, def_id: MaybeExternId, pattern: &IncludePattern) -> bool {
817 if self.matches_file_path(def_id, |path| pattern.glob.is_match(path)) {
818 return true;
819 }
820 if pattern.defs.iter().any(|def| self.matches_def(def_id, def)) {
821 return true;
822 }
823 if pattern.spans.iter().any(|pos| {
824 self.matches_file_path(def_id, |path| path.ends_with(&pos.file))
825 && self.matches_pos(def_id, pos.line, pos.column)
826 }) {
827 return true;
828 }
829 false
830 }
831
832 fn matches_trusted_pattern(&self, def_id: MaybeExternId) -> bool {
836 let Some(pattern) = config::trusted_pattern() else { return false };
837 self.matches_pattern(def_id, pattern)
838 }
839
840 fn matches_trusted_impl_pattern(&self, def_id: MaybeExternId) -> bool {
844 let Some(pattern) = config::trusted_impl_pattern() else { return false };
845 self.matches_pattern(def_id, pattern)
846 }
847
848 fn matches_included_pattern(&self, def_id: MaybeExternId) -> bool {
852 let Some(pattern) = config::include_pattern() else { return true };
853 self.matches_pattern(def_id, pattern)
854 }
855
856 pub fn included(&self, def_id: MaybeExternId) -> bool {
857 self.matches_included_pattern(def_id) || self.matches_trusted_pattern(def_id)
858 }
859
860 pub fn trusted(self, def_id: LocalDefId) -> bool {
864 let annotation = self
865 .traverse_parents(def_id, |did| self.fhir_attr_map(did).trusted())
866 .map(|trusted| trusted.to_bool())
867 .unwrap_or_else(config::trusted_default);
868 annotation || self.matches_trusted_pattern(MaybeExternId::Local(def_id))
869 }
870
871 pub fn trusted_impl(self, def_id: LocalDefId) -> bool {
872 let annotation = self
873 .traverse_parents(def_id, |did| self.fhir_attr_map(did).trusted_impl())
874 .map(|trusted| trusted.to_bool())
875 .unwrap_or(false);
876 annotation || self.matches_trusted_impl_pattern(MaybeExternId::Local(def_id))
877 }
878
879 pub fn trusted_derive(self, def_id: LocalDefId) -> bool {
882 if let Some(trusted) = self.fhir_attr_map(def_id).trusted_derive() {
883 return trusted.to_bool();
884 }
885 self.adt_def(def_id)
886 .is_ok_and(|adt_def| adt_def.is_opaque())
887 }
888
889 pub fn derive_self_ty(self, def_id: LocalDefId) -> Option<LocalDefId> {
898 let tcx = self.tcx();
899 let impl_id = tcx.local_parent(def_id);
900 if !matches!(tcx.def_kind(impl_id), DefKind::Impl { .. }) {
901 return None;
902 }
903 let adt_def_id = tcx
904 .type_of(impl_id)
905 .instantiate_identity()
906 .skip_norm_wip()
907 .ty_adt_def()?
908 .did();
909 match self.resolve_id(adt_def_id) {
910 ResolvedDefId::Local(local_id) | ResolvedDefId::ExternSpec(local_id, _) => {
911 Some(local_id)
912 }
913 ResolvedDefId::Extern(_) => None,
914 }
915 }
916
917 pub fn no_suggestions(self, def_id: LocalDefId) -> bool {
920 if !config::suggestions() {
921 return true;
922 }
923 self.traverse_parents(def_id, |did| {
924 if self.fhir_attr_map(did).no_suggestions() {
926 Some(true)
927 } else {
929 None
930 }
931 })
932 .unwrap_or(false)
933 }
934
935 pub fn is_dummy(self, def_id: LocalDefId) -> bool {
939 self.traverse_parents(def_id, |did| {
940 self.collect_specs()
941 .dummy_extern
942 .contains(&did)
943 .then_some(())
944 })
945 .is_some()
946 }
947
948 pub fn ignored(self, def_id: LocalDefId) -> bool {
952 self.traverse_parents(def_id, |did| self.fhir_attr_map(did).ignored())
953 .map(|ignored| ignored.to_bool())
954 .unwrap_or_else(config::ignore_default)
955 }
956
957 pub fn should_fail(self, def_id: LocalDefId) -> bool {
959 self.fhir_attr_map(def_id).should_fail()
960 }
961
962 pub fn proven_externally(self, def_id: LocalDefId) -> Option<Span> {
964 self.fhir_attr_map(def_id).proven_externally()
965 }
966
967 pub fn spec_attr_span(self, def_id: DefId) -> Option<Span> {
970 let specs = self.collect_specs();
971 specs
972 .get_spec_attr_span(def_id)
973 .or_else(|| {
974 let local_id = specs.extern_id_to_local_id.get(&def_id)?;
975 specs.get_spec_attr_span(local_id.to_def_id())
976 })
977 .or_else(|| self.cstore().spec_attr_span(def_id))
978 }
979
980 pub fn spec_attr_string(self, def_id: DefId) -> Option<String> {
983 let span = self.spec_attr_span(def_id)?;
984 self.tcx().sess.source_map().span_to_snippet(span).ok()
985 }
986
987 fn traverse_parents<T>(
989 self,
990 mut def_id: LocalDefId,
991 mut f: impl FnMut(LocalDefId) -> Option<T>,
992 ) -> Option<T> {
993 loop {
994 if let Some(v) = f(def_id) {
995 break Some(v);
996 }
997
998 if let Some(parent) = self.tcx().opt_local_parent(def_id) {
999 def_id = parent;
1000 } else {
1001 break None;
1002 }
1003 }
1004 }
1005}
1006
1007impl<'genv, 'tcx> GlobalEnv<'genv, 'tcx> {
1008 pub fn fhir_iter_flux_items(
1009 self,
1010 ) -> impl Iterator<Item = (FluxLocalDefId, fhir::FluxItem<'genv>)> {
1011 self.fhir_crate()
1012 .items
1013 .iter()
1014 .map(|(id, item)| (*id, *item))
1015 }
1016
1017 pub fn fhir_sort_decl(&self, def_id: FluxLocalDefId) -> Option<&fhir::SortDecl> {
1018 self.fhir_crate().items.get(&def_id).and_then(|item| {
1019 if let fhir::FluxItem::SortDecl(sort_decl) = item { Some(*sort_decl) } else { None }
1020 })
1021 }
1022
1023 pub fn fhir_spec_func_body(
1024 &self,
1025 def_id: FluxLocalDefId,
1026 ) -> Option<&'genv fhir::SpecFunc<'genv>> {
1027 self.fhir_crate()
1028 .items
1029 .get(&def_id)
1030 .and_then(|item| if let fhir::FluxItem::Func(defn) = item { Some(*defn) } else { None })
1031 }
1032
1033 pub fn fhir_qualifiers(self) -> impl Iterator<Item = &'genv fhir::Qualifier<'genv>> {
1034 self.fhir_crate().items.values().filter_map(|item| {
1035 if let fhir::FluxItem::Qualifier(qual) = item { Some(*qual) } else { None }
1036 })
1037 }
1038
1039 pub fn fhir_primop_props(self) -> impl Iterator<Item = &'genv fhir::PrimOpProp<'genv>> {
1040 self.fhir_crate().items.values().filter_map(|item| {
1041 if let fhir::FluxItem::PrimOpProp(prop) = item { Some(*prop) } else { None }
1042 })
1043 }
1044
1045 pub fn fhir_axioms(self) -> impl Iterator<Item = &'genv fhir::Axiom<'genv>> {
1046 self.fhir_crate().items.values().filter_map(|item| {
1047 if let fhir::FluxItem::Axiom(axiom) = item { Some(*axiom) } else { None }
1048 })
1049 }
1050
1051 pub fn fhir_get_generics(
1052 self,
1053 def_id: LocalDefId,
1054 ) -> QueryResult<Option<&'genv fhir::Generics<'genv>>> {
1055 if matches!(self.def_kind(def_id), DefKind::Closure) {
1057 Ok(None)
1058 } else {
1059 Ok(Some(self.fhir_expect_owner_node(def_id)?.generics()))
1060 }
1061 }
1062
1063 pub fn fhir_split_refinement_params(
1067 self,
1068 def_id: LocalDefId,
1069 ) -> QueryResult<(Vec<fhir::RefineParam<'genv>>, Vec<fhir::RefineParam<'genv>>)> {
1070 let Some(generics) = self.fhir_get_generics(def_id)? else {
1071 return Ok((vec![], vec![]));
1072 };
1073 let late_bound = self.late_bound_refinement_params(def_id)?;
1074 Ok(generics
1075 .refinement_params
1076 .iter()
1077 .copied()
1078 .partition(|param| !late_bound.contains(¶m.id)))
1079 }
1080
1081 pub fn fhir_expect_refinement_kind(
1082 self,
1083 def_id: LocalDefId,
1084 ) -> QueryResult<&'genv fhir::RefinementKind<'genv>> {
1085 let kind = match &self.fhir_expect_item(def_id)?.kind {
1086 fhir::ItemKind::Enum(enum_def) => &enum_def.refinement,
1087 fhir::ItemKind::Struct(struct_def) => &struct_def.refinement,
1088 _ => bug!("expected struct, enum or type alias"),
1089 };
1090 Ok(kind)
1091 }
1092
1093 pub fn fhir_expect_item(self, def_id: LocalDefId) -> QueryResult<&'genv fhir::Item<'genv>> {
1094 if let fhir::Node::Item(item) = self.fhir_node(def_id)? {
1095 Ok(item)
1096 } else {
1097 Err(query_bug!(def_id, "expected item: `{def_id:?}`"))
1098 }
1099 }
1100
1101 pub fn fhir_expect_owner_node(self, def_id: LocalDefId) -> QueryResult<fhir::OwnerNode<'genv>> {
1102 let Some(owner) = self.fhir_node(def_id)?.as_owner() else {
1103 return Err(query_bug!(def_id, "cannot find owner node"));
1104 };
1105 Ok(owner)
1106 }
1107
1108 pub fn fhir_node(self, def_id: LocalDefId) -> QueryResult<fhir::Node<'genv>> {
1109 self.desugar(def_id)
1110 }
1111}
1112
1113#[macro_export]
1114macro_rules! try_alloc_slice {
1115 ($genv:expr, $slice:expr, $map:expr $(,)?) => {{
1116 let slice = $slice;
1117 $crate::try_alloc_slice!($genv, cap: slice.len(), slice.into_iter().map($map))
1118 }};
1119 ($genv:expr, cap: $cap:expr, $it:expr $(,)?) => {{
1120 let mut err = None;
1121 let slice = $genv.alloc_slice_with_capacity($cap, $it.into_iter().collect_errors(&mut err));
1122 err.map_or(Ok(slice), Err)
1123 }};
1124}
1125
1126impl ErrorEmitter for GlobalEnv<'_, '_> {
1127 fn emit<'a>(&'a self, err: impl rustc_errors::Diagnostic<'a>) -> rustc_span::ErrorGuaranteed {
1128 self.sess().emit(err)
1129 }
1130}
1131
1132fn lean_parent_dir(tcx: TyCtxt) -> PathBuf {
1133 tcx.sess
1134 .source_map()
1135 .working_dir()
1136 .local_path()
1137 .unwrap()
1138 .join(config::lean_dir())
1139}