flux_middle/
global_env.rs

1use std::{alloc, ptr, rc::Rc, slice};
2
3use flux_arc_interner::List;
4use flux_common::{bug, result::ErrorEmitter};
5use flux_config as config;
6use flux_errors::FluxSession;
7use flux_rustc_bridge::{self, lowering::Lower, mir, ty};
8use rustc_data_structures::unord::UnordSet;
9use rustc_hir::{
10    def::DefKind,
11    def_id::{CrateNum, DefId, LocalDefId},
12};
13use rustc_middle::{
14    query::IntoQueryParam,
15    ty::{TyCtxt, Variance},
16};
17use rustc_span::Span;
18pub use rustc_span::{Symbol, symbol::Ident};
19
20use crate::{
21    cstore::CrateStoreDyn,
22    def_id::{FluxDefId, FluxLocalDefId, MaybeExternId, ResolvedDefId},
23    fhir::{self, VariantIdx},
24    queries::{Providers, Queries, QueryErr, QueryResult},
25    query_bug,
26    rty::{
27        self,
28        refining::{Refine as _, Refiner},
29    },
30};
31
32#[derive(Clone, Copy)]
33pub struct GlobalEnv<'genv, 'tcx> {
34    inner: &'genv GlobalEnvInner<'genv, 'tcx>,
35}
36
37struct GlobalEnvInner<'genv, 'tcx> {
38    tcx: TyCtxt<'tcx>,
39    sess: &'genv FluxSession,
40    arena: &'genv fhir::Arena,
41    cstore: Box<CrateStoreDyn>,
42    queries: Queries<'genv, 'tcx>,
43}
44
45impl<'tcx> GlobalEnv<'_, 'tcx> {
46    pub fn enter<'a, R>(
47        tcx: TyCtxt<'tcx>,
48        sess: &'a FluxSession,
49        cstore: Box<CrateStoreDyn>,
50        arena: &'a fhir::Arena,
51        providers: Providers,
52        f: impl for<'genv> FnOnce(GlobalEnv<'genv, 'tcx>) -> R,
53    ) -> R {
54        let inner = GlobalEnvInner { tcx, sess, cstore, arena, queries: Queries::new(providers) };
55        f(GlobalEnv { inner: &inner })
56    }
57}
58
59impl<'genv, 'tcx> GlobalEnv<'genv, 'tcx> {
60    pub fn tcx(self) -> TyCtxt<'tcx> {
61        self.inner.tcx
62    }
63
64    pub fn sess(self) -> &'genv FluxSession {
65        self.inner.sess
66    }
67
68    pub fn collect_specs(self) -> &'genv crate::Specs {
69        self.inner.queries.collect_specs(self)
70    }
71
72    pub fn resolve_crate(self) -> &'genv crate::ResolverOutput {
73        self.inner.queries.resolve_crate(self)
74    }
75
76    pub fn desugar(self, def_id: LocalDefId) -> QueryResult<fhir::Node<'genv>> {
77        self.inner.queries.desugar(self, def_id)
78    }
79
80    pub fn fhir_attr_map(self, def_id: LocalDefId) -> fhir::AttrMap<'genv> {
81        self.inner.queries.fhir_attr_map(self, def_id)
82    }
83
84    pub fn fhir_crate(self) -> &'genv fhir::FluxItems<'genv> {
85        self.inner.queries.fhir_crate(self)
86    }
87
88    pub fn alloc<T>(&self, val: T) -> &'genv T {
89        self.inner.arena.alloc(val)
90    }
91
92    pub fn alloc_slice<T: Copy>(self, slice: &[T]) -> &'genv [T] {
93        self.inner.arena.alloc_slice_copy(slice)
94    }
95
96    pub fn alloc_slice_fill_iter<T, I>(self, it: I) -> &'genv [T]
97    where
98        I: IntoIterator<Item = T>,
99        I::IntoIter: ExactSizeIterator,
100    {
101        self.inner.arena.alloc_slice_fill_iter(it)
102    }
103
104    pub fn def_kind(&self, def_id: impl IntoQueryParam<DefId>) -> DefKind {
105        self.tcx().def_kind(def_id.into_query_param())
106    }
107
108    /// Allocates space to store `cap` elements of type `T`.
109    ///
110    /// The elements are initialized using the supplied iterator. At most `cap` elements will be
111    /// retrieved from the iterator. If the iterator yields fewer than `cap` elements, the returned
112    /// slice will be of length less than the allocated capacity.
113    ///
114    /// ## Panics
115    ///
116    /// Panics if reserving space for the slice fails.
117    pub fn alloc_slice_with_capacity<T, I>(self, cap: usize, it: I) -> &'genv [T]
118    where
119        I: IntoIterator<Item = T>,
120    {
121        let layout = alloc::Layout::array::<T>(cap).unwrap_or_else(|_| bug!("out of memory"));
122        let dst = self.inner.arena.alloc_layout(layout).cast::<T>();
123        unsafe {
124            let mut len = 0;
125            for (i, v) in it.into_iter().take(cap).enumerate() {
126                len += 1;
127                ptr::write(dst.as_ptr().add(i), v);
128            }
129
130            slice::from_raw_parts(dst.as_ptr(), len)
131        }
132    }
133
134    pub fn normalized_info(self, did: FluxDefId) -> rty::NormalizeInfo {
135        self.normalized_defns(did.krate()).func_info(did).clone()
136    }
137
138    pub fn normalized_defns(self, krate: CrateNum) -> Rc<rty::NormalizedDefns> {
139        self.inner.queries.normalized_defns(self, krate)
140    }
141
142    pub fn prim_rel_for(self, op: &rty::BinOp) -> QueryResult<Option<&'genv rty::PrimRel>> {
143        Ok(self.inner.queries.prim_rel(self)?.get(op))
144    }
145
146    pub fn qualifiers(self) -> QueryResult<&'genv [rty::Qualifier]> {
147        self.inner.queries.qualifiers(self)
148    }
149
150    /// Return all the qualifiers that apply to an item, including both global and local qualifiers.
151    pub fn qualifiers_for(
152        self,
153        did: LocalDefId,
154    ) -> QueryResult<impl Iterator<Item = &'genv rty::Qualifier>> {
155        let quals = self.fhir_attr_map(did).qualifiers;
156        let names: UnordSet<_> = quals.iter().copied().collect();
157        Ok(self
158            .qualifiers()?
159            .iter()
160            .filter(move |qual| qual.global || names.contains(&qual.def_id)))
161    }
162
163    /// Return the list of flux function definitions that should be revelaed for item
164    pub fn reveals_for(self, did: LocalDefId) -> &'genv [FluxDefId] {
165        self.fhir_attr_map(did).reveals
166    }
167
168    pub fn func_sort(self, def_id: impl IntoQueryParam<FluxDefId>) -> rty::PolyFuncSort {
169        self.inner
170            .queries
171            .func_sort(self, def_id.into_query_param())
172    }
173
174    pub fn func_span(self, def_id: impl IntoQueryParam<FluxDefId>) -> Span {
175        self.inner
176            .queries
177            .func_span(self, def_id.into_query_param())
178    }
179
180    pub fn should_inline_fun(self, def_id: FluxDefId) -> bool {
181        let is_poly = self.func_sort(def_id).params().len() > 0;
182        is_poly || !flux_config::smt_define_fun()
183    }
184
185    pub fn variances_of(self, did: DefId) -> &'tcx [Variance] {
186        self.tcx().variances_of(did)
187    }
188
189    pub fn mir(self, def_id: LocalDefId) -> QueryResult<Rc<mir::Body<'tcx>>> {
190        self.inner.queries.mir(self, def_id)
191    }
192
193    pub fn lower_generics_of(self, def_id: impl IntoQueryParam<DefId>) -> ty::Generics<'tcx> {
194        self.inner
195            .queries
196            .lower_generics_of(self, def_id.into_query_param())
197    }
198
199    pub fn lower_predicates_of(
200        self,
201        def_id: impl IntoQueryParam<DefId>,
202    ) -> QueryResult<ty::GenericPredicates> {
203        self.inner
204            .queries
205            .lower_predicates_of(self, def_id.into_query_param())
206    }
207
208    pub fn lower_type_of(
209        self,
210        def_id: impl IntoQueryParam<DefId>,
211    ) -> QueryResult<ty::EarlyBinder<ty::Ty>> {
212        self.inner
213            .queries
214            .lower_type_of(self, def_id.into_query_param())
215    }
216
217    pub fn lower_fn_sig(
218        self,
219        def_id: impl Into<DefId>,
220    ) -> QueryResult<ty::EarlyBinder<ty::PolyFnSig>> {
221        self.inner.queries.lower_fn_sig(self, def_id.into())
222    }
223
224    pub fn adt_def(self, def_id: impl IntoQueryParam<DefId>) -> QueryResult<rty::AdtDef> {
225        self.inner.queries.adt_def(self, def_id.into_query_param())
226    }
227
228    pub fn constant_info(
229        self,
230        def_id: impl IntoQueryParam<DefId>,
231    ) -> QueryResult<rty::ConstantInfo> {
232        self.inner
233            .queries
234            .constant_info(self, def_id.into_query_param())
235    }
236
237    pub fn adt_sort_def_of(
238        self,
239        def_id: impl IntoQueryParam<DefId>,
240    ) -> QueryResult<rty::AdtSortDef> {
241        self.inner
242            .queries
243            .adt_sort_def_of(self, def_id.into_query_param())
244    }
245
246    pub fn check_wf(self, def_id: LocalDefId) -> QueryResult<Rc<rty::WfckResults>> {
247        self.inner.queries.check_wf(self, def_id)
248    }
249
250    pub fn impl_trait_ref(
251        self,
252        impl_id: DefId,
253    ) -> QueryResult<Option<rty::EarlyBinder<rty::TraitRef>>> {
254        let Some(trait_ref) = self.tcx().impl_trait_ref(impl_id) else { return Ok(None) };
255        let trait_ref = trait_ref.skip_binder();
256        let trait_ref = trait_ref
257            .lower(self.tcx())
258            .map_err(|err| QueryErr::unsupported(trait_ref.def_id, err.into_err()))?
259            .refine(&Refiner::default_for_item(self, impl_id)?)?;
260        Ok(Some(rty::EarlyBinder(trait_ref)))
261    }
262
263    pub fn generics_of(self, def_id: impl IntoQueryParam<DefId>) -> QueryResult<rty::Generics> {
264        self.inner
265            .queries
266            .generics_of(self, def_id.into_query_param())
267    }
268
269    pub fn refinement_generics_of(
270        self,
271        def_id: impl IntoQueryParam<DefId>,
272    ) -> QueryResult<rty::EarlyBinder<rty::RefinementGenerics>> {
273        self.inner
274            .queries
275            .refinement_generics_of(self, def_id.into_query_param())
276    }
277
278    pub fn predicates_of(
279        self,
280        def_id: impl IntoQueryParam<DefId>,
281    ) -> QueryResult<rty::EarlyBinder<rty::GenericPredicates>> {
282        self.inner
283            .queries
284            .predicates_of(self, def_id.into_query_param())
285    }
286
287    pub fn assoc_refinements_of(
288        self,
289        def_id: impl IntoQueryParam<DefId>,
290    ) -> QueryResult<rty::AssocRefinements> {
291        self.inner
292            .queries
293            .assoc_refinements_of(self, def_id.into_query_param())
294    }
295
296    pub fn assoc_refinement(self, assoc_id: FluxDefId) -> QueryResult<rty::AssocReft> {
297        Ok(self.assoc_refinements_of(assoc_id.parent())?.get(assoc_id))
298    }
299
300    /// Given the id of an associated refinement in a trait definition returns the body for the
301    /// corresponding associated refinement in the implementation with id `impl_id`.
302    ///
303    /// This function returns [`QueryErr::MissingAssocReft`] if the associated refinement is not
304    /// found in the implementation and there's no default body in the trait. This can happen if an
305    /// extern spec adds an associated refinement without a default body because we are currently
306    /// not checking `compare_impl_item` for those definitions.
307    pub fn assoc_refinement_body_for_impl(
308        self,
309        trait_assoc_id: FluxDefId,
310        impl_id: DefId,
311    ) -> QueryResult<rty::EarlyBinder<rty::Lambda>> {
312        // Check if the implementation has the associated refinement
313        let impl_assoc_refts = self.assoc_refinements_of(impl_id)?;
314        if let Some(impl_assoc_reft) = impl_assoc_refts.find(trait_assoc_id.name()) {
315            return self.assoc_refinement_body(impl_assoc_reft.def_id());
316        }
317
318        // Otherwise, check if the trait has a default body
319        if let Some(body) = self.default_assoc_refinement_body(trait_assoc_id)? {
320            let impl_trait_ref = self
321                .impl_trait_ref(impl_id)?
322                .unwrap()
323                .instantiate_identity();
324            return Ok(rty::EarlyBinder(body.instantiate(self.tcx(), &impl_trait_ref.args, &[])));
325        }
326
327        Err(QueryErr::MissingAssocReft {
328            impl_id,
329            trait_id: trait_assoc_id.parent(),
330            name: trait_assoc_id.name(),
331        })
332    }
333
334    pub fn default_assoc_refinement_body(
335        self,
336        trait_assoc_id: FluxDefId,
337    ) -> QueryResult<Option<rty::EarlyBinder<rty::Lambda>>> {
338        self.inner
339            .queries
340            .default_assoc_refinement_body(self, trait_assoc_id)
341    }
342
343    pub fn assoc_refinement_body(
344        self,
345        impl_assoc_id: FluxDefId,
346    ) -> QueryResult<rty::EarlyBinder<rty::Lambda>> {
347        self.inner
348            .queries
349            .assoc_refinement_body(self, impl_assoc_id)
350    }
351
352    pub fn sort_of_assoc_reft(
353        self,
354        assoc_id: FluxDefId,
355    ) -> QueryResult<rty::EarlyBinder<rty::FuncSort>> {
356        self.inner.queries.sort_of_assoc_reft(self, assoc_id)
357    }
358
359    pub fn item_bounds(self, def_id: DefId) -> QueryResult<rty::EarlyBinder<List<rty::Clause>>> {
360        self.inner.queries.item_bounds(self, def_id)
361    }
362
363    pub fn type_of(
364        self,
365        def_id: impl IntoQueryParam<DefId>,
366    ) -> QueryResult<rty::EarlyBinder<rty::TyOrCtor>> {
367        self.inner.queries.type_of(self, def_id.into_query_param())
368    }
369
370    pub fn fn_sig(
371        self,
372        def_id: impl IntoQueryParam<DefId>,
373    ) -> QueryResult<rty::EarlyBinder<rty::PolyFnSig>> {
374        self.inner.queries.fn_sig(self, def_id.into_query_param())
375    }
376
377    pub fn variants_of(
378        self,
379        def_id: impl IntoQueryParam<DefId>,
380    ) -> QueryResult<rty::Opaqueness<rty::EarlyBinder<rty::PolyVariants>>> {
381        self.inner
382            .queries
383            .variants_of(self, def_id.into_query_param())
384    }
385
386    pub fn variant_sig(
387        self,
388        def_id: DefId,
389        variant_idx: VariantIdx,
390    ) -> QueryResult<rty::Opaqueness<rty::EarlyBinder<rty::PolyVariant>>> {
391        Ok(self
392            .variants_of(def_id)?
393            .map(|variants| variants.map(|variants| variants[variant_idx.as_usize()].clone())))
394    }
395
396    pub fn lower_late_bound_vars(
397        self,
398        def_id: LocalDefId,
399    ) -> QueryResult<List<ty::BoundVariableKind>> {
400        self.inner.queries.lower_late_bound_vars(self, def_id)
401    }
402
403    pub fn is_box(&self, res: fhir::Res) -> bool {
404        res.is_box(self.tcx())
405    }
406
407    pub fn def_id_to_param_index(&self, def_id: DefId) -> u32 {
408        let parent = self.tcx().parent(def_id);
409        let generics = self.tcx().generics_of(parent);
410        generics.param_def_id_to_index(self.tcx(), def_id).unwrap()
411    }
412
413    pub(crate) fn cstore(self) -> &'genv CrateStoreDyn {
414        &*self.inner.cstore
415    }
416
417    pub fn has_trusted_impl(&self, def_id: DefId) -> bool {
418        if let Some(did) = self
419            .resolve_id(def_id)
420            .as_maybe_extern()
421            .map(|id| id.local_id())
422        {
423            self.trusted_impl(did)
424        } else {
425            false
426        }
427    }
428
429    /// The `Output` associated type is defined in `FnOnce`, and `Fn`/`FnMut`
430    /// inherit it, so this should suffice to check if the `def_id`
431    /// corresponds to `LangItem::FnOnceOutput`.
432    pub fn is_fn_output(&self, def_id: DefId) -> bool {
433        let def_span = self.tcx().def_span(def_id);
434        self.tcx()
435            .require_lang_item(rustc_hir::LangItem::FnOnceOutput, def_span)
436            == def_id
437    }
438
439    /// Iterator over all local def ids that are not a extern spec
440    pub fn iter_local_def_id(self) -> impl Iterator<Item = LocalDefId> + use<'tcx, 'genv> {
441        self.tcx().iter_local_def_id().filter(move |&local_def_id| {
442            self.maybe_extern_id(local_def_id).is_local() && !self.is_dummy(local_def_id)
443        })
444    }
445
446    pub fn iter_extern_def_id(self) -> impl Iterator<Item = DefId> + use<'tcx, 'genv> {
447        self.tcx()
448            .iter_local_def_id()
449            .filter_map(move |local_def_id| self.maybe_extern_id(local_def_id).as_extern())
450    }
451
452    pub fn maybe_extern_id(self, local_id: LocalDefId) -> MaybeExternId {
453        self.collect_specs()
454            .local_id_to_extern_id
455            .get(&local_id)
456            .map_or_else(
457                || MaybeExternId::Local(local_id),
458                |def_id| MaybeExternId::Extern(local_id, *def_id),
459            )
460    }
461
462    #[expect(clippy::disallowed_methods)]
463    pub fn resolve_id(self, def_id: DefId) -> ResolvedDefId {
464        let maybe_extern_spec = self
465            .collect_specs()
466            .extern_id_to_local_id
467            .get(&def_id)
468            .copied();
469        if let Some(local_id) = maybe_extern_spec {
470            ResolvedDefId::ExternSpec(local_id, def_id)
471        } else if let Some(local_id) = def_id.as_local() {
472            debug_assert!(
473                self.maybe_extern_id(local_id).is_local(),
474                "def id points to dummy local item `{def_id:?}`"
475            );
476            ResolvedDefId::Local(local_id)
477        } else {
478            ResolvedDefId::Extern(def_id)
479        }
480    }
481
482    pub fn infer_opts(self, def_id: LocalDefId) -> config::InferOpts {
483        let mut opts = config::PartialInferOpts::default();
484        self.traverse_parents(def_id, |did| {
485            if let Some(o) = self.fhir_attr_map(did).infer_opts() {
486                opts.merge(&o);
487            }
488            None::<!>
489        });
490        opts.into()
491    }
492
493    /// Transitively follow the parent-chain of `def_id` to find the first containing item with an
494    /// explicit `#[flux::trusted(..)]` annotation and return whether that item is trusted or not.
495    /// If no explicit annotation is found, return `false`.
496    pub fn trusted(self, def_id: LocalDefId) -> bool {
497        self.traverse_parents(def_id, |did| self.fhir_attr_map(did).trusted())
498            .map(|trusted| trusted.to_bool())
499            .unwrap_or_else(config::trusted_default)
500    }
501
502    pub fn trusted_impl(self, def_id: LocalDefId) -> bool {
503        self.traverse_parents(def_id, |did| self.fhir_attr_map(did).trusted_impl())
504            .map(|trusted| trusted.to_bool())
505            .unwrap_or(false)
506    }
507
508    /// Whether the item is a dummy item created by the extern spec macro.
509    ///
510    /// See [`crate::Specs::dummy_extern`]
511    pub fn is_dummy(self, def_id: LocalDefId) -> bool {
512        self.traverse_parents(def_id, |did| {
513            self.collect_specs()
514                .dummy_extern
515                .contains(&did)
516                .then_some(())
517        })
518        .is_some()
519    }
520
521    /// Transitively follow the parent-chain of `def_id` to find the first containing item with an
522    /// explicit `#[flux::ignore(..)]` annotation and return whether that item is ignored or not.
523    /// If no explicit annotation is found, return `false`.
524    pub fn ignored(self, def_id: LocalDefId) -> bool {
525        self.traverse_parents(def_id, |did| self.fhir_attr_map(did).ignored())
526            .map(|ignored| ignored.to_bool())
527            .unwrap_or_else(config::ignore_default)
528    }
529
530    /// Whether the function is marked with `#[flux::should_fail]`
531    pub fn should_fail(self, def_id: LocalDefId) -> bool {
532        self.fhir_attr_map(def_id).should_fail()
533    }
534
535    /// Whether the function is marked with `#[proven_externally]`
536    pub fn proven_externally(self, def_id: LocalDefId) -> bool {
537        self.fhir_attr_map(def_id).proven_externally()
538    }
539
540    /// Traverse the parent chain of `def_id` until the first node for which `f` returns [`Some`].
541    fn traverse_parents<T>(
542        self,
543        mut def_id: LocalDefId,
544        mut f: impl FnMut(LocalDefId) -> Option<T>,
545    ) -> Option<T> {
546        loop {
547            if let Some(v) = f(def_id) {
548                break Some(v);
549            }
550
551            if let Some(parent) = self.tcx().opt_local_parent(def_id) {
552                def_id = parent;
553            } else {
554                break None;
555            }
556        }
557    }
558}
559
560impl<'genv, 'tcx> GlobalEnv<'genv, 'tcx> {
561    pub fn fhir_iter_flux_items(
562        self,
563    ) -> impl Iterator<Item = (FluxLocalDefId, fhir::FluxItem<'genv>)> {
564        self.fhir_crate()
565            .items
566            .iter()
567            .map(|(id, item)| (*id, *item))
568    }
569
570    pub fn fhir_spec_func_body(
571        &self,
572        def_id: FluxLocalDefId,
573    ) -> Option<&'genv fhir::SpecFunc<'genv>> {
574        self.fhir_crate()
575            .items
576            .get(&def_id)
577            .and_then(|item| if let fhir::FluxItem::Func(defn) = item { Some(*defn) } else { None })
578    }
579
580    pub fn fhir_qualifiers(self) -> impl Iterator<Item = &'genv fhir::Qualifier<'genv>> {
581        self.fhir_crate().items.values().filter_map(|item| {
582            if let fhir::FluxItem::Qualifier(qual) = item { Some(*qual) } else { None }
583        })
584    }
585
586    pub fn fhir_primop_props(self) -> impl Iterator<Item = &'genv fhir::PrimOpProp<'genv>> {
587        self.fhir_crate().items.values().filter_map(|item| {
588            if let fhir::FluxItem::PrimOpProp(prop) = item { Some(*prop) } else { None }
589        })
590    }
591
592    pub fn fhir_get_generics(
593        self,
594        def_id: LocalDefId,
595    ) -> QueryResult<Option<&'genv fhir::Generics<'genv>>> {
596        // We don't have nodes for closures and coroutines
597        if matches!(self.def_kind(def_id), DefKind::Closure) {
598            Ok(None)
599        } else {
600            Ok(Some(self.fhir_expect_owner_node(def_id)?.generics()))
601        }
602    }
603
604    pub fn fhir_expect_refinement_kind(
605        self,
606        def_id: LocalDefId,
607    ) -> QueryResult<&'genv fhir::RefinementKind<'genv>> {
608        let kind = match &self.fhir_expect_item(def_id)?.kind {
609            fhir::ItemKind::Enum(enum_def) => &enum_def.refinement,
610            fhir::ItemKind::Struct(struct_def) => &struct_def.refinement,
611            _ => bug!("expected struct, enum or type alias"),
612        };
613        Ok(kind)
614    }
615
616    pub fn fhir_expect_item(self, def_id: LocalDefId) -> QueryResult<&'genv fhir::Item<'genv>> {
617        if let fhir::Node::Item(item) = self.fhir_node(def_id)? {
618            Ok(item)
619        } else {
620            Err(query_bug!(def_id, "expected item: `{def_id:?}`"))
621        }
622    }
623
624    pub fn fhir_expect_owner_node(self, def_id: LocalDefId) -> QueryResult<fhir::OwnerNode<'genv>> {
625        let Some(owner) = self.fhir_node(def_id)?.as_owner() else {
626            return Err(query_bug!(def_id, "cannot find owner node"));
627        };
628        Ok(owner)
629    }
630
631    pub fn fhir_node(self, def_id: LocalDefId) -> QueryResult<fhir::Node<'genv>> {
632        self.desugar(def_id)
633    }
634}
635
636#[macro_export]
637macro_rules! try_alloc_slice {
638    ($genv:expr, $slice:expr, $map:expr $(,)?) => {{
639        let slice = $slice;
640        $crate::try_alloc_slice!($genv, cap: slice.len(), slice.into_iter().map($map))
641    }};
642    ($genv:expr, cap: $cap:expr, $it:expr $(,)?) => {{
643        let mut err = None;
644        let slice = $genv.alloc_slice_with_capacity($cap, $it.into_iter().collect_errors(&mut err));
645        err.map_or(Ok(slice), Err)
646    }};
647}
648
649impl ErrorEmitter for GlobalEnv<'_, '_> {
650    fn emit<'a>(&'a self, err: impl rustc_errors::Diagnostic<'a>) -> rustc_span::ErrorGuaranteed {
651        self.sess().emit(err)
652    }
653}