Skip to main content

rustc_hir_typeck/
typeck_root_ctxt.rs

1use std::cell::{Cell, RefCell};
2use std::ops::Deref;
3
4use rustc_hir::def_id::LocalDefId;
5use rustc_hir::{self as hir, HirId, HirIdMap};
6use rustc_infer::infer::{InferCtxt, InferOk, OpaqueTypeStorageEntries, TyCtxtInferExt};
7use rustc_middle::ty::{self, Ty, TyCtxt, TyVid, TypeVisitableExt, TypingMode};
8use rustc_span::def_id::{LocalDefIdMap, LocalModId};
9use rustc_span::{Span, span_bug};
10use rustc_trait_selection::traits::{self, FulfillmentEngine, FulfillmentError, TraitEngine};
11use tracing::instrument;
12
13use super::callee::DeferredCallResolution;
14
15/// Data shared between a "typeck root" and its nested bodies,
16/// e.g. closures defined within the function. For example:
17/// ```ignore (illustrative)
18/// fn foo() {
19///     bar(move || { ... })
20/// }
21/// ```
22/// Here, the function `foo()` and the closure passed to
23/// `bar()` will each have their own `FnCtxt`, but they will
24/// share the inference context, will process obligations together,
25/// can access each other's local types (scoping permitted), etc.
26pub(crate) struct TypeckRootCtxt<'tcx> {
27    pub(super) infcx: InferCtxt<'tcx>,
28
29    pub(super) typeck_results: RefCell<ty::TypeckResults<'tcx>>,
30
31    pub(super) locals: RefCell<HirIdMap<Ty<'tcx>>>,
32
33    pub(super) fulfillment_cx: RefCell<FulfillmentEngine<'tcx, FulfillmentError<'tcx>>>,
34
35    // Used to detect opaque types uses added after we've already checked them.
36    //
37    // See [FnCtxt::detect_opaque_types_added_during_writeback] for more details.
38    pub(super) checked_opaque_types_storage_entries: Cell<Option<OpaqueTypeStorageEntries>>,
39
40    /// Some additional `Sized` obligations badly affect type inference.
41    /// These obligations are added in a later stage of typeck.
42    /// Removing these may also cause additional complications, see #101066.
43    pub(super) deferred_sized_obligations:
44        RefCell<Vec<(Ty<'tcx>, Span, traits::ObligationCauseCode<'tcx>)>>,
45
46    /// When we process a call like `c()` where `c` is a closure type,
47    /// we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
48    /// `FnOnce` closure. In that case, we defer full resolution of the
49    /// call until upvar inference can kick in and make the
50    /// decision. We keep these deferred resolutions grouped by the
51    /// def-id of the closure, so that once we decide, we can easily go
52    /// back and process them.
53    pub(super) deferred_call_resolutions: RefCell<LocalDefIdMap<Vec<DeferredCallResolution<'tcx>>>>,
54
55    pub(super) deferred_cast_checks: RefCell<Vec<super::cast::CastCheck<'tcx>>>,
56
57    pub(super) deferred_transmute_checks: RefCell<Vec<(Ty<'tcx>, Ty<'tcx>, HirId)>>,
58
59    pub(super) deferred_offload_checks: RefCell<Vec<(Ty<'tcx>, Ty<'tcx>, Ty<'tcx>, HirId)>>,
60
61    pub(super) deferred_asm_checks: RefCell<Vec<(&'tcx hir::InlineAsm<'tcx>, HirId)>>,
62
63    pub(super) deferred_repeat_expr_checks:
64        RefCell<Vec<(&'tcx hir::Expr<'tcx>, Ty<'tcx>, ty::Const<'tcx>)>>,
65
66    /// Whenever we introduce an adjustment from `!` into a type variable,
67    /// we record that type variable here. This is later used to inform
68    /// fallback. See the `fallback` module for details.
69    pub(super) diverging_type_vars: RefCell<Vec<TyVid>>,
70
71    /// Parent module
72    pub(super) mod_id: LocalModId,
73}
74
75impl<'tcx> Deref for TypeckRootCtxt<'tcx> {
76    type Target = InferCtxt<'tcx>;
77    fn deref(&self) -> &Self::Target {
78        &self.infcx
79    }
80}
81
82impl<'tcx> TypeckRootCtxt<'tcx> {
83    pub(crate) fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self {
84        let mod_id = tcx.parent_module_from_def_id(def_id);
85        let hir_owner = tcx.local_def_id_to_hir_id(def_id).owner;
86
87        let infcx = tcx
88            .infer_ctxt()
89            .ignoring_regions()
90            .in_hir_typeck()
91            .build(TypingMode::typeck_for_body(tcx, def_id));
92        let typeck_results = RefCell::new(ty::TypeckResults::new(hir_owner));
93        let fulfillment_cx = RefCell::new(FulfillmentEngine::new(&infcx));
94
95        TypeckRootCtxt {
96            infcx,
97            typeck_results,
98            locals: RefCell::new(Default::default()),
99            fulfillment_cx,
100            checked_opaque_types_storage_entries: Cell::new(None),
101            deferred_sized_obligations: RefCell::new(Vec::new()),
102            deferred_call_resolutions: RefCell::new(Default::default()),
103            deferred_cast_checks: RefCell::new(Vec::new()),
104            deferred_transmute_checks: RefCell::new(Vec::new()),
105            deferred_offload_checks: RefCell::new(Vec::new()),
106            deferred_asm_checks: RefCell::new(Vec::new()),
107            deferred_repeat_expr_checks: RefCell::new(Vec::new()),
108            diverging_type_vars: RefCell::new(Default::default()),
109            mod_id,
110        }
111    }
112
113    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("register_predicate",
                                    "rustc_hir_typeck::typeck_root_ctxt",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs"),
                                    ::tracing_core::__macro_support::Option::Some(113u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::typeck_root_ctxt"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("obligation")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("obligation");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if obligation.has_escaping_bound_vars() {
                ::rustc_span::macros::bug_impl(Some(obligation.cause.span),
                    format_args!("escaping bound vars in predicate {0:?}",
                        obligation), Location::caller());
            }
            self.fulfillment_cx.borrow_mut().register_predicate_obligation(self,
                obligation);
        }
    }
}#[instrument(level = "debug", skip(self))]
114    pub(super) fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
115        if obligation.has_escaping_bound_vars() {
116            span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation);
117        }
118
119        self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
120    }
121
122    pub(super) fn register_predicates<I>(&self, obligations: I)
123    where
124        I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
125    {
126        for obligation in obligations {
127            self.register_predicate(obligation);
128        }
129    }
130
131    pub(super) fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
132        self.register_predicates(infer_ok.obligations);
133        infer_ok.value
134    }
135}