]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/writeback.rs
Rollup merge of #42496 - Razaekel:feature/integer_max-min, r=BurntSushi
[rust.git] / src / librustc_typeck / check / writeback.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Type resolution: the phase that finds all the types in the AST with
12 // unresolved type variables and replaces "ty_var" types with their
13 // substitutions.
14
15 use check::FnCtxt;
16 use rustc::hir;
17 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
18 use rustc::infer::{InferCtxt};
19 use rustc::ty::{self, Ty, TyCtxt};
20 use rustc::ty::fold::{TypeFolder,TypeFoldable};
21 use rustc::util::nodemap::DefIdSet;
22 use syntax::ast;
23 use syntax_pos::Span;
24 use std::mem;
25
26 ///////////////////////////////////////////////////////////////////////////
27 // Entry point
28
29 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
30     pub fn resolve_type_vars_in_body(&self, body: &'gcx hir::Body)
31                                      -> &'gcx ty::TypeckTables<'gcx> {
32         let item_id = self.tcx.hir.body_owner(body.id());
33         let item_def_id = self.tcx.hir.local_def_id(item_id);
34
35         let mut wbcx = WritebackCx::new(self, body);
36         for arg in &body.arguments {
37             wbcx.visit_node_id(arg.pat.span, arg.id);
38         }
39         wbcx.visit_body(body);
40         wbcx.visit_upvar_borrow_map();
41         wbcx.visit_closures();
42         wbcx.visit_liberated_fn_sigs();
43         wbcx.visit_fru_field_types();
44         wbcx.visit_anon_types();
45         wbcx.visit_cast_types();
46         wbcx.visit_lints();
47         wbcx.visit_free_region_map();
48
49         let used_trait_imports = mem::replace(&mut self.tables.borrow_mut().used_trait_imports,
50                                               DefIdSet());
51         debug!("used_trait_imports({:?}) = {:?}", item_def_id, used_trait_imports);
52         wbcx.tables.used_trait_imports = used_trait_imports;
53
54         wbcx.tables.tainted_by_errors = self.is_tainted_by_errors();
55
56         self.tcx.alloc_tables(wbcx.tables)
57     }
58 }
59
60 ///////////////////////////////////////////////////////////////////////////
61 // The Writerback context. This visitor walks the AST, checking the
62 // fn-specific tables to find references to types or regions. It
63 // resolves those regions to remove inference variables and writes the
64 // final result back into the master tables in the tcx. Here and
65 // there, it applies a few ad-hoc checks that were not convenient to
66 // do elsewhere.
67
68 struct WritebackCx<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
69     fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>,
70
71     tables: ty::TypeckTables<'gcx>,
72
73     body: &'gcx hir::Body,
74 }
75
76 impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
77     fn new(fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>, body: &'gcx hir::Body)
78         -> WritebackCx<'cx, 'gcx, 'tcx> {
79         WritebackCx {
80             fcx: fcx,
81             tables: ty::TypeckTables::empty(),
82             body: body
83         }
84     }
85
86     fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
87         self.fcx.tcx
88     }
89
90     fn write_ty_to_tables(&mut self, node_id: ast::NodeId, ty: Ty<'gcx>) {
91         debug!("write_ty_to_tables({}, {:?})", node_id,  ty);
92         assert!(!ty.needs_infer());
93         self.tables.node_types.insert(node_id, ty);
94     }
95
96     // Hacky hack: During type-checking, we treat *all* operators
97     // as potentially overloaded. But then, during writeback, if
98     // we observe that something like `a+b` is (known to be)
99     // operating on scalars, we clear the overload.
100     fn fix_scalar_builtin_expr(&mut self, e: &hir::Expr) {
101         match e.node {
102             hir::ExprUnary(hir::UnNeg, ref inner) |
103             hir::ExprUnary(hir::UnNot, ref inner)  => {
104                 let inner_ty = self.fcx.node_ty(inner.id);
105                 let inner_ty = self.fcx.resolve_type_vars_if_possible(&inner_ty);
106
107                 if inner_ty.is_scalar() {
108                     let mut tables = self.fcx.tables.borrow_mut();
109                     tables.type_dependent_defs.remove(&e.id);
110                     tables.node_substs.remove(&e.id);
111                 }
112             }
113             hir::ExprBinary(ref op, ref lhs, ref rhs) |
114             hir::ExprAssignOp(ref op, ref lhs, ref rhs) => {
115                 let lhs_ty = self.fcx.node_ty(lhs.id);
116                 let lhs_ty = self.fcx.resolve_type_vars_if_possible(&lhs_ty);
117
118                 let rhs_ty = self.fcx.node_ty(rhs.id);
119                 let rhs_ty = self.fcx.resolve_type_vars_if_possible(&rhs_ty);
120
121                 if lhs_ty.is_scalar() && rhs_ty.is_scalar() {
122                     let mut tables = self.fcx.tables.borrow_mut();
123                     tables.type_dependent_defs.remove(&e.id);
124                     tables.node_substs.remove(&e.id);
125
126                     match e.node {
127                         hir::ExprBinary(..) => {
128                             if !op.node.is_by_value() {
129                                 tables.adjustments.get_mut(&lhs.id).map(|a| a.pop());
130                                 tables.adjustments.get_mut(&rhs.id).map(|a| a.pop());
131                             }
132                         },
133                         hir::ExprAssignOp(..) => {
134                             tables.adjustments.get_mut(&lhs.id).map(|a| a.pop());
135                         },
136                         _ => {},
137                     }
138                 }
139             }
140             _ => {},
141         }
142     }
143 }
144
145 ///////////////////////////////////////////////////////////////////////////
146 // Impl of Visitor for Resolver
147 //
148 // This is the master code which walks the AST. It delegates most of
149 // the heavy lifting to the generic visit and resolve functions
150 // below. In general, a function is made into a `visitor` if it must
151 // traffic in node-ids or update tables in the type context etc.
152
153 impl<'cx, 'gcx, 'tcx> Visitor<'gcx> for WritebackCx<'cx, 'gcx, 'tcx> {
154     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
155         NestedVisitorMap::None
156     }
157
158     fn visit_expr(&mut self, e: &'gcx hir::Expr) {
159         self.fix_scalar_builtin_expr(e);
160
161         self.visit_node_id(e.span, e.id);
162
163         if let hir::ExprClosure(_, _, body, _) = e.node {
164             let body = self.fcx.tcx.hir.body(body);
165             for arg in &body.arguments {
166                 self.visit_node_id(e.span, arg.id);
167             }
168
169             self.visit_body(body);
170         }
171
172         intravisit::walk_expr(self, e);
173     }
174
175     fn visit_block(&mut self, b: &'gcx hir::Block) {
176         self.visit_node_id(b.span, b.id);
177         intravisit::walk_block(self, b);
178     }
179
180     fn visit_pat(&mut self, p: &'gcx hir::Pat) {
181         self.visit_node_id(p.span, p.id);
182         intravisit::walk_pat(self, p);
183     }
184
185     fn visit_local(&mut self, l: &'gcx hir::Local) {
186         intravisit::walk_local(self, l);
187         let var_ty = self.fcx.local_ty(l.span, l.id);
188         let var_ty = self.resolve(&var_ty, &l.span);
189         self.write_ty_to_tables(l.id, var_ty);
190     }
191 }
192
193 impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
194     fn visit_upvar_borrow_map(&mut self) {
195         for (upvar_id, upvar_capture) in self.fcx.tables.borrow().upvar_capture_map.iter() {
196             let new_upvar_capture = match *upvar_capture {
197                 ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue,
198                 ty::UpvarCapture::ByRef(ref upvar_borrow) => {
199                     let r = upvar_borrow.region;
200                     let r = self.resolve(&r, &upvar_id.var_id);
201                     ty::UpvarCapture::ByRef(
202                         ty::UpvarBorrow { kind: upvar_borrow.kind, region: r })
203                 }
204             };
205             debug!("Upvar capture for {:?} resolved to {:?}",
206                    upvar_id,
207                    new_upvar_capture);
208             self.tables.upvar_capture_map.insert(*upvar_id, new_upvar_capture);
209         }
210     }
211
212     fn visit_closures(&mut self) {
213         for (&id, closure_ty) in self.fcx.tables.borrow().closure_tys.iter() {
214             let closure_ty = self.resolve(closure_ty, &id);
215             self.tables.closure_tys.insert(id, closure_ty);
216         }
217
218         for (&id, &closure_kind) in self.fcx.tables.borrow().closure_kinds.iter() {
219             self.tables.closure_kinds.insert(id, closure_kind);
220         }
221     }
222
223     fn visit_cast_types(&mut self) {
224         self.tables.cast_kinds.extend(
225             self.fcx.tables.borrow().cast_kinds.iter().map(|(&key, &value)| (key, value)));
226     }
227
228     fn visit_lints(&mut self) {
229         self.fcx.tables.borrow_mut().lints.transfer(&mut self.tables.lints);
230     }
231
232     fn visit_free_region_map(&mut self) {
233         let free_region_map = self.tcx().lift_to_global(&self.fcx.tables.borrow().free_region_map);
234         let free_region_map = free_region_map.expect("all regions in free-region-map are global");
235         self.tables.free_region_map = free_region_map;
236     }
237
238     fn visit_anon_types(&mut self) {
239         let gcx = self.tcx().global_tcx();
240         for (&node_id, &concrete_ty) in self.fcx.anon_types.borrow().iter() {
241             let inside_ty = self.resolve(&concrete_ty, &node_id);
242
243             // Convert the type from the function into a type valid outside
244             // the function, by replacing invalid regions with 'static,
245             // after producing an error for each of them.
246             let outside_ty = gcx.fold_regions(&inside_ty, &mut false, |r, _| {
247                 match *r {
248                     // 'static and early-bound regions are valid.
249                     ty::ReStatic |
250                     ty::ReEarlyBound(_) |
251                     ty::ReEmpty => r,
252
253                     ty::ReFree(_) |
254                     ty::ReLateBound(..) |
255                     ty::ReScope(_) |
256                     ty::ReSkolemized(..) => {
257                         let span = node_id.to_span(&self.fcx.tcx);
258                         span_err!(self.tcx().sess, span, E0564,
259                                   "only named lifetimes are allowed in `impl Trait`, \
260                                    but `{}` was found in the type `{}`", r, inside_ty);
261                         gcx.types.re_static
262                     }
263
264                     ty::ReVar(_) |
265                     ty::ReErased => {
266                         let span = node_id.to_span(&self.fcx.tcx);
267                         span_bug!(span, "invalid region in impl Trait: {:?}", r);
268                     }
269                 }
270             });
271
272             self.tables.node_types.insert(node_id, outside_ty);
273         }
274     }
275
276     fn visit_node_id(&mut self, span: Span, node_id: ast::NodeId) {
277         // Export associated path extensions and method resultions.
278         if let Some(def) = self.fcx.tables.borrow_mut().type_dependent_defs.remove(&node_id) {
279             self.tables.type_dependent_defs.insert(node_id, def);
280         }
281
282         // Resolve any borrowings for the node with id `node_id`
283         self.visit_adjustments(span, node_id);
284
285         // Resolve the type of the node with id `node_id`
286         let n_ty = self.fcx.node_ty(node_id);
287         let n_ty = self.resolve(&n_ty, &span);
288         self.write_ty_to_tables(node_id, n_ty);
289         debug!("Node {} has type {:?}", node_id, n_ty);
290
291         // Resolve any substitutions
292         if let Some(&substs) = self.fcx.tables.borrow().node_substs.get(&node_id) {
293             let substs = self.resolve(&substs, &span);
294             debug!("write_substs_to_tcx({}, {:?})", node_id, substs);
295             assert!(!substs.needs_infer());
296             self.tables.node_substs.insert(node_id, substs);
297         }
298     }
299
300     fn visit_adjustments(&mut self, span: Span, node_id: ast::NodeId) {
301         let adjustment = self.fcx.tables.borrow_mut().adjustments.remove(&node_id);
302         match adjustment {
303             None => {
304                 debug!("No adjustments for node {}", node_id);
305             }
306
307             Some(adjustment) => {
308                 let resolved_adjustment = self.resolve(&adjustment, &span);
309                 debug!("Adjustments for node {}: {:?}", node_id, resolved_adjustment);
310                 self.tables.adjustments.insert(node_id, resolved_adjustment);
311             }
312         }
313     }
314
315     fn visit_liberated_fn_sigs(&mut self) {
316         for (&node_id, fn_sig) in self.fcx.tables.borrow().liberated_fn_sigs.iter() {
317             let fn_sig = self.resolve(fn_sig, &node_id);
318             self.tables.liberated_fn_sigs.insert(node_id, fn_sig.clone());
319         }
320     }
321
322     fn visit_fru_field_types(&mut self) {
323         for (&node_id, ftys) in self.fcx.tables.borrow().fru_field_types.iter() {
324             let ftys = self.resolve(ftys, &node_id);
325             self.tables.fru_field_types.insert(node_id, ftys);
326         }
327     }
328
329     fn resolve<T>(&self, x: &T, span: &Locatable) -> T::Lifted
330         where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
331     {
332         let x = x.fold_with(&mut Resolver::new(self.fcx, span, self.body));
333         if let Some(lifted) = self.tcx().lift_to_global(&x) {
334             lifted
335         } else {
336             span_bug!(span.to_span(&self.fcx.tcx),
337                       "writeback: `{:?}` missing from the global type context",
338                       x);
339         }
340     }
341 }
342
343 trait Locatable {
344     fn to_span(&self, tcx: &TyCtxt) -> Span;
345 }
346
347 impl Locatable for Span {
348     fn to_span(&self, _: &TyCtxt) -> Span { *self }
349 }
350
351 impl Locatable for ast::NodeId {
352     fn to_span(&self, tcx: &TyCtxt) -> Span { tcx.hir.span(*self) }
353 }
354
355 ///////////////////////////////////////////////////////////////////////////
356 // The Resolver. This is the type folding engine that detects
357 // unresolved types and so forth.
358
359 struct Resolver<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
360     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
361     infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
362     span: &'cx Locatable,
363     body: &'gcx hir::Body,
364 }
365
366 impl<'cx, 'gcx, 'tcx> Resolver<'cx, 'gcx, 'tcx> {
367     fn new(fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>, span: &'cx Locatable, body: &'gcx hir::Body)
368         -> Resolver<'cx, 'gcx, 'tcx>
369     {
370         Resolver {
371             tcx: fcx.tcx,
372             infcx: fcx,
373             span: span,
374             body: body,
375         }
376     }
377
378     fn report_error(&self, t: Ty<'tcx>) {
379         if !self.tcx.sess.has_errors() {
380             self.infcx.need_type_info(self.body.id(), self.span.to_span(&self.tcx), t);
381         }
382     }
383 }
384
385 impl<'cx, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for Resolver<'cx, 'gcx, 'tcx> {
386     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx> {
387         self.tcx
388     }
389
390     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
391         match self.infcx.fully_resolve(&t) {
392             Ok(t) => t,
393             Err(_) => {
394                 debug!("Resolver::fold_ty: input type `{:?}` not fully resolvable",
395                        t);
396                 self.report_error(t);
397                 self.tcx().types.err
398             }
399         }
400     }
401
402     // FIXME This should be carefully checked
403     // We could use `self.report_error` but it doesn't accept a ty::Region, right now.
404     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
405         match self.infcx.fully_resolve(&r) {
406             Ok(r) => r,
407             Err(_) => {
408                 self.tcx.types.re_static
409             }
410         }
411     }
412 }
413
414 ///////////////////////////////////////////////////////////////////////////
415 // During type check, we store promises with the result of trait
416 // lookup rather than the actual results (because the results are not
417 // necessarily available immediately). These routines unwind the
418 // promises. It is expected that we will have already reported any
419 // errors that may be encountered, so if the promises store an error,
420 // a dummy result is returned.