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