]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/fn_ctxt/mod.rs
Merge commit 'f51aade56f93175dde89177a92e3669ebd8e7592' into clippyup
[rust.git] / compiler / rustc_typeck / src / check / fn_ctxt / mod.rs
1 mod _impl;
2 mod arg_matrix;
3 mod checks;
4 mod suggestions;
5
6 pub use _impl::*;
7 pub use suggestions::*;
8
9 use crate::astconv::AstConv;
10 use crate::check::coercion::DynamicCoerceMany;
11 use crate::check::{Diverges, EnclosingBreakables, Inherited, UnsafetyState};
12
13 use rustc_hir as hir;
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};
25
26 use std::cell::{Cell, RefCell};
27 use std::ops::Deref;
28
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`].
32 ///
33 /// This is in contrast to [`ItemCtxt`], which is used to type-check item *signatures*
34 /// and thus does not perform type inference.
35 ///
36 /// See [`ItemCtxt`]'s docs for more.
37 ///
38 /// [`ItemCtxt`]: crate::collect::ItemCtxt
39 /// [`InferCtxt`]: infer::InferCtxt
40 pub struct FnCtxt<'a, 'tcx> {
41     pub(super) body_id: hir::HirId,
42
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
48     /// eventually).
49     pub(super) param_env: ty::ParamEnv<'tcx>,
50
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,
58
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.
62     ///
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
68     /// any).
69     pub(super) ret_coercion: Option<RefCell<DynamicCoerceMany<'tcx>>>,
70
71     pub(super) ret_type_span: Option<Span>,
72
73     /// Used exclusively to reduce cost of advanced evaluation used for
74     /// more helpful diagnostics.
75     pub(super) in_tail_expr: bool,
76
77     /// First span of a return site that we find. Used in error messages.
78     pub(super) ret_coercion_span: Cell<Option<Span>>,
79
80     pub(super) resume_yield_tys: Option<(Ty<'tcx>, Ty<'tcx>)>,
81
82     pub(super) ps: Cell<UnsafetyState>,
83
84     /// Whether the last checked node generates a divergence (e.g.,
85     /// `return` will set this to `Always`). In general, when entering
86     /// an expression or other node in the tree, the initial value
87     /// indicates whether prior parts of the containing expression may
88     /// have diverged. It is then typically set to `Maybe` (and the
89     /// old value remembered) for processing the subparts of the
90     /// current expression. As each subpart is processed, they may set
91     /// the flag to `Always`, etc. Finally, at the end, we take the
92     /// result and "union" it with the original value, so that when we
93     /// return the flag indicates if any subpart of the parent
94     /// expression (up to and including this part) has diverged. So,
95     /// if you read it after evaluating a subexpression `X`, the value
96     /// you get indicates whether any subexpression that was
97     /// evaluating up to and including `X` diverged.
98     ///
99     /// We currently use this flag only for diagnostic purposes:
100     ///
101     /// - To warn about unreachable code: if, after processing a
102     ///   sub-expression but before we have applied the effects of the
103     ///   current node, we see that the flag is set to `Always`, we
104     ///   can issue a warning. This corresponds to something like
105     ///   `foo(return)`; we warn on the `foo()` expression. (We then
106     ///   update the flag to `WarnedAlways` to suppress duplicate
107     ///   reports.) Similarly, if we traverse to a fresh statement (or
108     ///   tail expression) from an `Always` setting, we will issue a
109     ///   warning. This corresponds to something like `{return;
110     ///   foo();}` or `{return; 22}`, where we would warn on the
111     ///   `foo()` or `22`.
112     ///
113     /// An expression represents dead code if, after checking it,
114     /// the diverges flag is set to something other than `Maybe`.
115     pub(super) diverges: Cell<Diverges>,
116
117     /// Whether any child nodes have any type errors.
118     pub(super) has_errors: Cell<bool>,
119
120     pub(super) enclosing_breakables: RefCell<EnclosingBreakables<'tcx>>,
121
122     pub(super) inh: &'a Inherited<'a, 'tcx>,
123
124     /// True if the function or closure's return type is known before
125     /// entering the function/closure, i.e. if the return type is
126     /// either given explicitly or inferred from, say, an `Fn*` trait
127     /// bound. Used for diagnostic purposes only.
128     pub(super) return_type_pre_known: bool,
129
130     /// True if the return type has an Opaque type
131     pub(super) return_type_has_opaque: bool,
132 }
133
134 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
135     pub fn new(
136         inh: &'a Inherited<'a, 'tcx>,
137         param_env: ty::ParamEnv<'tcx>,
138         body_id: hir::HirId,
139     ) -> FnCtxt<'a, 'tcx> {
140         FnCtxt {
141             body_id,
142             param_env,
143             err_count_on_creation: inh.tcx.sess.err_count(),
144             ret_coercion: None,
145             ret_type_span: None,
146             in_tail_expr: false,
147             ret_coercion_span: Cell::new(None),
148             resume_yield_tys: None,
149             ps: Cell::new(UnsafetyState::function(hir::Unsafety::Normal, hir::CRATE_HIR_ID)),
150             diverges: Cell::new(Diverges::Maybe),
151             has_errors: Cell::new(false),
152             enclosing_breakables: RefCell::new(EnclosingBreakables {
153                 stack: Vec::new(),
154                 by_id: Default::default(),
155             }),
156             inh,
157             return_type_pre_known: true,
158             return_type_has_opaque: false,
159         }
160     }
161
162     pub fn cause(&self, span: Span, code: ObligationCauseCode<'tcx>) -> ObligationCause<'tcx> {
163         ObligationCause::new(span, self.body_id, code)
164     }
165
166     pub fn misc(&self, span: Span) -> ObligationCause<'tcx> {
167         self.cause(span, ObligationCauseCode::MiscObligation)
168     }
169
170     pub fn sess(&self) -> &Session {
171         &self.tcx.sess
172     }
173
174     pub fn errors_reported_since_creation(&self) -> bool {
175         self.tcx.sess.err_count() > self.err_count_on_creation
176     }
177 }
178
179 impl<'a, 'tcx> Deref for FnCtxt<'a, 'tcx> {
180     type Target = Inherited<'a, 'tcx>;
181     fn deref(&self) -> &Self::Target {
182         &self.inh
183     }
184 }
185
186 impl<'a, 'tcx> AstConv<'tcx> for FnCtxt<'a, 'tcx> {
187     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
188         self.tcx
189     }
190
191     fn item_def_id(&self) -> Option<DefId> {
192         None
193     }
194
195     fn get_type_parameter_bounds(
196         &self,
197         _: Span,
198         def_id: DefId,
199         _: Ident,
200     ) -> ty::GenericPredicates<'tcx> {
201         let tcx = self.tcx;
202         let item_def_id = tcx.hir().ty_param_owner(def_id.expect_local());
203         let generics = tcx.generics_of(item_def_id);
204         let index = generics.param_def_id_to_index[&def_id];
205         ty::GenericPredicates {
206             parent: None,
207             predicates: tcx.arena.alloc_from_iter(
208                 self.param_env.caller_bounds().iter().filter_map(|predicate| {
209                     match predicate.kind().skip_binder() {
210                         ty::PredicateKind::Trait(data) if data.self_ty().is_param(index) => {
211                             // HACK(eddyb) should get the original `Span`.
212                             let span = tcx.def_span(def_id);
213                             Some((predicate, span))
214                         }
215                         _ => None,
216                     }
217                 }),
218             ),
219         }
220     }
221
222     fn re_infer(&self, def: Option<&ty::GenericParamDef>, span: Span) -> Option<ty::Region<'tcx>> {
223         let v = match def {
224             Some(def) => infer::EarlyBoundRegion(span, def.name),
225             None => infer::MiscVariable(span),
226         };
227         Some(self.next_region_var(v))
228     }
229
230     fn allow_ty_infer(&self) -> bool {
231         true
232     }
233
234     fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
235         if let Some(param) = param {
236             if let GenericArgKind::Type(ty) = self.var_for_def(span, param).unpack() {
237                 return ty;
238             }
239             unreachable!()
240         } else {
241             self.next_ty_var(TypeVariableOrigin {
242                 kind: TypeVariableOriginKind::TypeInference,
243                 span,
244             })
245         }
246     }
247
248     fn ct_infer(
249         &self,
250         ty: Ty<'tcx>,
251         param: Option<&ty::GenericParamDef>,
252         span: Span,
253     ) -> Const<'tcx> {
254         if let Some(param) = param {
255             if let GenericArgKind::Const(ct) = self.var_for_def(span, param).unpack() {
256                 return ct;
257             }
258             unreachable!()
259         } else {
260             self.next_const_var(
261                 ty,
262                 ConstVariableOrigin { kind: ConstVariableOriginKind::ConstInference, span },
263             )
264         }
265     }
266
267     fn projected_ty_from_poly_trait_ref(
268         &self,
269         span: Span,
270         item_def_id: DefId,
271         item_segment: &hir::PathSegment<'_>,
272         poly_trait_ref: ty::PolyTraitRef<'tcx>,
273     ) -> Ty<'tcx> {
274         let trait_ref = self.replace_bound_vars_with_fresh_vars(
275             span,
276             infer::LateBoundRegionConversionTime::AssocTypeProjection(item_def_id),
277             poly_trait_ref,
278         );
279
280         let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
281             self,
282             self.tcx,
283             span,
284             item_def_id,
285             item_segment,
286             trait_ref.substs,
287         );
288
289         self.tcx().mk_projection(item_def_id, item_substs)
290     }
291
292     fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
293         if ty.has_escaping_bound_vars() {
294             ty // FIXME: normalization and escaping regions
295         } else {
296             self.normalize_associated_types_in(span, ty)
297         }
298     }
299
300     fn set_tainted_by_errors(&self) {
301         self.infcx.set_tainted_by_errors()
302     }
303
304     fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, _span: Span) {
305         self.write_ty(hir_id, ty)
306     }
307 }