7 pub use suggestions::*;
9 use crate::astconv::AstConv;
10 use crate::check::coercion::DynamicCoerceMany;
11 use crate::check::{Diverges, EnclosingBreakables, Inherited, UnsafetyState};
14 use rustc_hir::def_id::DefId;
15 use rustc_infer::infer;
16 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
17 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind};
18 use rustc_middle::ty::subst::GenericArgKind;
19 use rustc_middle::ty::visit::TypeVisitable;
20 use rustc_middle::ty::{self, Const, Ty, TyCtxt};
21 use rustc_session::Session;
22 use rustc_span::symbol::Ident;
23 use rustc_span::{self, Span};
24 use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode};
26 use std::cell::{Cell, RefCell};
29 /// The `FnCtxt` stores type-checking context needed to type-check bodies of
30 /// functions, closures, and `const`s, including performing type inference
31 /// with [`InferCtxt`].
33 /// This is in contrast to [`ItemCtxt`], which is used to type-check item *signatures*
34 /// and thus does not perform type inference.
36 /// See [`ItemCtxt`]'s docs for more.
38 /// [`ItemCtxt`]: crate::collect::ItemCtxt
39 /// [`InferCtxt`]: infer::InferCtxt
40 pub struct FnCtxt<'a, 'tcx> {
41 pub(super) body_id: hir::HirId,
43 /// The parameter environment used for proving trait obligations
44 /// in this function. This can change when we descend into
45 /// closures (as they bring new things into scope), hence it is
46 /// not part of `Inherited` (as of the time of this writing,
47 /// closures do not yet change the environment, but they will
49 pub(super) param_env: ty::ParamEnv<'tcx>,
51 /// Number of errors that had been reported when we started
52 /// checking this function. On exit, if we find that *more* errors
53 /// have been reported, we will skip regionck and other work that
54 /// expects the types within the function to be consistent.
55 // FIXME(matthewjasper) This should not exist, and it's not correct
56 // if type checking is run in parallel.
57 err_count_on_creation: usize,
59 /// If `Some`, this stores coercion information for returned
60 /// expressions. If `None`, this is in a context where return is
61 /// inappropriate, such as a const expression.
63 /// This is a `RefCell<DynamicCoerceMany>`, which means that we
64 /// can track all the return expressions and then use them to
65 /// compute a useful coercion from the set, similar to a match
66 /// expression or other branching context. You can use methods
67 /// like `expected_ty` to access the declared return type (if
69 pub(super) ret_coercion: Option<RefCell<DynamicCoerceMany<'tcx>>>,
71 /// Used exclusively to reduce cost of advanced evaluation used for
72 /// more helpful diagnostics.
73 pub(super) in_tail_expr: bool,
75 /// First span of a return site that we find. Used in error messages.
76 pub(super) ret_coercion_span: Cell<Option<Span>>,
78 pub(super) resume_yield_tys: Option<(Ty<'tcx>, Ty<'tcx>)>,
80 pub(super) ps: Cell<UnsafetyState>,
82 /// Whether the last checked node generates a divergence (e.g.,
83 /// `return` will set this to `Always`). In general, when entering
84 /// an expression or other node in the tree, the initial value
85 /// indicates whether prior parts of the containing expression may
86 /// have diverged. It is then typically set to `Maybe` (and the
87 /// old value remembered) for processing the subparts of the
88 /// current expression. As each subpart is processed, they may set
89 /// the flag to `Always`, etc. Finally, at the end, we take the
90 /// result and "union" it with the original value, so that when we
91 /// return the flag indicates if any subpart of the parent
92 /// expression (up to and including this part) has diverged. So,
93 /// if you read it after evaluating a subexpression `X`, the value
94 /// you get indicates whether any subexpression that was
95 /// evaluating up to and including `X` diverged.
97 /// We currently use this flag only for diagnostic purposes:
99 /// - To warn about unreachable code: if, after processing a
100 /// sub-expression but before we have applied the effects of the
101 /// current node, we see that the flag is set to `Always`, we
102 /// can issue a warning. This corresponds to something like
103 /// `foo(return)`; we warn on the `foo()` expression. (We then
104 /// update the flag to `WarnedAlways` to suppress duplicate
105 /// reports.) Similarly, if we traverse to a fresh statement (or
106 /// tail expression) from an `Always` setting, we will issue a
107 /// warning. This corresponds to something like `{return;
108 /// foo();}` or `{return; 22}`, where we would warn on the
111 /// An expression represents dead code if, after checking it,
112 /// the diverges flag is set to something other than `Maybe`.
113 pub(super) diverges: Cell<Diverges>,
115 /// Whether any child nodes have any type errors.
116 pub(super) has_errors: Cell<bool>,
118 pub(super) enclosing_breakables: RefCell<EnclosingBreakables<'tcx>>,
120 pub(super) inh: &'a Inherited<'a, 'tcx>,
122 /// True if the function or closure's return type is known before
123 /// entering the function/closure, i.e. if the return type is
124 /// either given explicitly or inferred from, say, an `Fn*` trait
125 /// bound. Used for diagnostic purposes only.
126 pub(super) return_type_pre_known: bool,
128 /// True if the return type has an Opaque type
129 pub(super) return_type_has_opaque: bool,
132 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
134 inh: &'a Inherited<'a, 'tcx>,
135 param_env: ty::ParamEnv<'tcx>,
137 ) -> FnCtxt<'a, 'tcx> {
141 err_count_on_creation: inh.tcx.sess.err_count(),
144 ret_coercion_span: Cell::new(None),
145 resume_yield_tys: None,
146 ps: Cell::new(UnsafetyState::function(hir::Unsafety::Normal, hir::CRATE_HIR_ID)),
147 diverges: Cell::new(Diverges::Maybe),
148 has_errors: Cell::new(false),
149 enclosing_breakables: RefCell::new(EnclosingBreakables {
151 by_id: Default::default(),
154 return_type_pre_known: true,
155 return_type_has_opaque: false,
159 pub fn cause(&self, span: Span, code: ObligationCauseCode<'tcx>) -> ObligationCause<'tcx> {
160 ObligationCause::new(span, self.body_id, code)
163 pub fn misc(&self, span: Span) -> ObligationCause<'tcx> {
164 self.cause(span, ObligationCauseCode::MiscObligation)
167 pub fn sess(&self) -> &Session {
171 pub fn errors_reported_since_creation(&self) -> bool {
172 self.tcx.sess.err_count() > self.err_count_on_creation
176 impl<'a, 'tcx> Deref for FnCtxt<'a, 'tcx> {
177 type Target = Inherited<'a, 'tcx>;
178 fn deref(&self) -> &Self::Target {
183 impl<'a, 'tcx> AstConv<'tcx> for FnCtxt<'a, 'tcx> {
184 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
188 fn item_def_id(&self) -> Option<DefId> {
192 fn get_type_parameter_bounds(
197 ) -> ty::GenericPredicates<'tcx> {
199 let item_def_id = tcx.hir().ty_param_owner(def_id.expect_local());
200 let generics = tcx.generics_of(item_def_id);
201 let index = generics.param_def_id_to_index[&def_id];
202 ty::GenericPredicates {
204 predicates: tcx.arena.alloc_from_iter(
205 self.param_env.caller_bounds().iter().filter_map(|predicate| {
206 match predicate.kind().skip_binder() {
207 ty::PredicateKind::Trait(data) if data.self_ty().is_param(index) => {
208 // HACK(eddyb) should get the original `Span`.
209 let span = tcx.def_span(def_id);
210 Some((predicate, span))
219 fn re_infer(&self, def: Option<&ty::GenericParamDef>, span: Span) -> Option<ty::Region<'tcx>> {
221 Some(def) => infer::EarlyBoundRegion(span, def.name),
222 None => infer::MiscVariable(span),
224 Some(self.next_region_var(v))
227 fn allow_ty_infer(&self) -> bool {
231 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
232 if let Some(param) = param {
233 if let GenericArgKind::Type(ty) = self.var_for_def(span, param).unpack() {
238 self.next_ty_var(TypeVariableOrigin {
239 kind: TypeVariableOriginKind::TypeInference,
248 param: Option<&ty::GenericParamDef>,
251 if let Some(param) = param {
252 if let GenericArgKind::Const(ct) = self.var_for_def(span, param).unpack() {
259 ConstVariableOrigin { kind: ConstVariableOriginKind::ConstInference, span },
264 fn projected_ty_from_poly_trait_ref(
268 item_segment: &hir::PathSegment<'_>,
269 poly_trait_ref: ty::PolyTraitRef<'tcx>,
271 let trait_ref = self.replace_bound_vars_with_fresh_vars(
273 infer::LateBoundRegionConversionTime::AssocTypeProjection(item_def_id),
277 let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
285 self.tcx().mk_projection(item_def_id, item_substs)
288 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
289 if ty.has_escaping_bound_vars() {
290 ty // FIXME: normalization and escaping regions
292 self.normalize_associated_types_in(span, ty)
296 fn set_tainted_by_errors(&self) {
297 self.infcx.set_tainted_by_errors()
300 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, _span: Span) {
301 self.write_ty(hir_id, ty)