]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/inherited.rs
Rollup merge of #99861 - lcnr:orphan-check-cg, r=jackh726
[rust.git] / compiler / rustc_typeck / src / check / inherited.rs
1 use super::callee::DeferredCallResolution;
2
3 use rustc_data_structures::fx::FxHashSet;
4 use rustc_hir as hir;
5 use rustc_hir::def_id::LocalDefId;
6 use rustc_hir::HirIdMap;
7 use rustc_infer::infer;
8 use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
9 use rustc_middle::ty::fold::TypeFoldable;
10 use rustc_middle::ty::visit::TypeVisitable;
11 use rustc_middle::ty::{self, Ty, TyCtxt};
12 use rustc_span::def_id::LocalDefIdMap;
13 use rustc_span::{self, Span};
14 use rustc_trait_selection::infer::InferCtxtExt as _;
15 use rustc_trait_selection::traits::{self, ObligationCause, TraitEngine, TraitEngineExt};
16
17 use std::cell::RefCell;
18 use std::ops::Deref;
19
20 /// Closures defined within the function. For example:
21 /// ```ignore (illustrative)
22 /// fn foo() {
23 ///     bar(move|| { ... })
24 /// }
25 /// ```
26 /// Here, the function `foo()` and the closure passed to
27 /// `bar()` will each have their own `FnCtxt`, but they will
28 /// share the inherited fields.
29 pub struct Inherited<'a, 'tcx> {
30     pub(super) infcx: InferCtxt<'a, 'tcx>,
31
32     pub(super) typeck_results: &'a RefCell<ty::TypeckResults<'tcx>>,
33
34     pub(super) locals: RefCell<HirIdMap<super::LocalTy<'tcx>>>,
35
36     pub(super) fulfillment_cx: RefCell<Box<dyn TraitEngine<'tcx>>>,
37
38     // Some additional `Sized` obligations badly affect type inference.
39     // These obligations are added in a later stage of typeck.
40     pub(super) deferred_sized_obligations:
41         RefCell<Vec<(Ty<'tcx>, Span, traits::ObligationCauseCode<'tcx>)>>,
42
43     // When we process a call like `c()` where `c` is a closure type,
44     // we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
45     // `FnOnce` closure. In that case, we defer full resolution of the
46     // call until upvar inference can kick in and make the
47     // decision. We keep these deferred resolutions grouped by the
48     // def-id of the closure, so that once we decide, we can easily go
49     // back and process them.
50     pub(super) deferred_call_resolutions: RefCell<LocalDefIdMap<Vec<DeferredCallResolution<'tcx>>>>,
51
52     pub(super) deferred_cast_checks: RefCell<Vec<super::cast::CastCheck<'tcx>>>,
53
54     pub(super) deferred_transmute_checks: RefCell<Vec<(Ty<'tcx>, Ty<'tcx>, Span)>>,
55
56     pub(super) deferred_asm_checks: RefCell<Vec<(&'tcx hir::InlineAsm<'tcx>, hir::HirId)>>,
57
58     pub(super) deferred_generator_interiors:
59         RefCell<Vec<(hir::BodyId, Ty<'tcx>, hir::GeneratorKind)>>,
60
61     pub(super) body_id: Option<hir::BodyId>,
62
63     /// Whenever we introduce an adjustment from `!` into a type variable,
64     /// we record that type variable here. This is later used to inform
65     /// fallback. See the `fallback` module for details.
66     pub(super) diverging_type_vars: RefCell<FxHashSet<Ty<'tcx>>>,
67 }
68
69 impl<'a, 'tcx> Deref for Inherited<'a, 'tcx> {
70     type Target = InferCtxt<'a, 'tcx>;
71     fn deref(&self) -> &Self::Target {
72         &self.infcx
73     }
74 }
75
76 /// A temporary returned by `Inherited::build(...)`. This is necessary
77 /// for multiple `InferCtxt` to share the same `in_progress_typeck_results`
78 /// without using `Rc` or something similar.
79 pub struct InheritedBuilder<'tcx> {
80     infcx: infer::InferCtxtBuilder<'tcx>,
81     def_id: LocalDefId,
82 }
83
84 impl<'tcx> Inherited<'_, 'tcx> {
85     pub fn build(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> InheritedBuilder<'tcx> {
86         let hir_owner = tcx.hir().local_def_id_to_hir_id(def_id).owner;
87
88         InheritedBuilder {
89             infcx: tcx
90                 .infer_ctxt()
91                 .ignoring_regions()
92                 .with_fresh_in_progress_typeck_results(hir_owner),
93             def_id,
94         }
95     }
96 }
97
98 impl<'tcx> InheritedBuilder<'tcx> {
99     pub fn enter<F, R>(&mut self, f: F) -> R
100     where
101         F: for<'a> FnOnce(Inherited<'a, 'tcx>) -> R,
102     {
103         let def_id = self.def_id;
104         self.infcx.enter(|infcx| f(Inherited::new(infcx, def_id)))
105     }
106 }
107
108 impl<'a, 'tcx> Inherited<'a, 'tcx> {
109     fn new(infcx: InferCtxt<'a, 'tcx>, def_id: LocalDefId) -> Self {
110         let tcx = infcx.tcx;
111         let body_id = tcx.hir().maybe_body_owned_by(def_id);
112         let typeck_results =
113             infcx.in_progress_typeck_results.expect("building `FnCtxt` without typeck results");
114
115         Inherited {
116             typeck_results,
117             infcx,
118             fulfillment_cx: RefCell::new(<dyn TraitEngine<'_>>::new(tcx)),
119             locals: RefCell::new(Default::default()),
120             deferred_sized_obligations: RefCell::new(Vec::new()),
121             deferred_call_resolutions: RefCell::new(Default::default()),
122             deferred_cast_checks: RefCell::new(Vec::new()),
123             deferred_transmute_checks: RefCell::new(Vec::new()),
124             deferred_asm_checks: RefCell::new(Vec::new()),
125             deferred_generator_interiors: RefCell::new(Vec::new()),
126             diverging_type_vars: RefCell::new(Default::default()),
127             body_id,
128         }
129     }
130
131     #[instrument(level = "debug", skip(self))]
132     pub(super) fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
133         if obligation.has_escaping_bound_vars() {
134             span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation);
135         }
136         self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
137     }
138
139     pub(super) fn register_predicates<I>(&self, obligations: I)
140     where
141         I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
142     {
143         for obligation in obligations {
144             self.register_predicate(obligation);
145         }
146     }
147
148     pub(super) fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
149         self.register_predicates(infer_ok.obligations);
150         infer_ok.value
151     }
152
153     pub(super) fn normalize_associated_types_in<T>(
154         &self,
155         span: Span,
156         body_id: hir::HirId,
157         param_env: ty::ParamEnv<'tcx>,
158         value: T,
159     ) -> T
160     where
161         T: TypeFoldable<'tcx>,
162     {
163         self.normalize_associated_types_in_with_cause(
164             ObligationCause::misc(span, body_id),
165             param_env,
166             value,
167         )
168     }
169
170     pub(super) fn normalize_associated_types_in_with_cause<T>(
171         &self,
172         cause: ObligationCause<'tcx>,
173         param_env: ty::ParamEnv<'tcx>,
174         value: T,
175     ) -> T
176     where
177         T: TypeFoldable<'tcx>,
178     {
179         let ok = self.partially_normalize_associated_types_in(cause, param_env, value);
180         debug!(?ok);
181         self.register_infer_ok_obligations(ok)
182     }
183 }