]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/writeback.rs
Use ItemLocalId as key for TypeckTables::fru_field_types.
[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::def_id::DefId;
18 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
19 use rustc::infer::{InferCtxt};
20 use rustc::ty::{self, Ty, TyCtxt};
21 use rustc::ty::fold::{TypeFolder,TypeFoldable};
22 use rustc::util::nodemap::DefIdSet;
23 use syntax::ast;
24 use syntax_pos::Span;
25 use std::mem;
26
27 ///////////////////////////////////////////////////////////////////////////
28 // Entry point
29
30 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
31     pub fn resolve_type_vars_in_body(&self, body: &'gcx hir::Body)
32                                      -> &'gcx ty::TypeckTables<'gcx> {
33         let item_id = self.tcx.hir.body_owner(body.id());
34         let item_def_id = self.tcx.hir.local_def_id(item_id);
35
36         let mut wbcx = WritebackCx::new(self, body);
37         for arg in &body.arguments {
38             wbcx.visit_node_id(arg.pat.span, arg.hir_id);
39         }
40         wbcx.visit_body(body);
41         wbcx.visit_upvar_borrow_map();
42         wbcx.visit_closures();
43         wbcx.visit_liberated_fn_sigs();
44         wbcx.visit_fru_field_types();
45         wbcx.visit_anon_types();
46         wbcx.visit_cast_types();
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     {
80         let owner = fcx.tcx.hir.definitions().node_to_hir_id(body.id().node_id);
81
82         WritebackCx {
83             fcx: fcx,
84             tables: ty::TypeckTables::empty(DefId::local(owner.owner)),
85             body: body
86         }
87     }
88
89     fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
90         self.fcx.tcx
91     }
92
93     fn write_ty_to_tables(&mut self, hir_id: hir::HirId, ty: Ty<'gcx>) {
94         debug!("write_ty_to_tables({:?}, {:?})", hir_id,  ty);
95         assert!(!ty.needs_infer());
96         self.tables.validate_hir_id(hir_id);
97         self.tables.node_types.insert(hir_id.local_id, ty);
98     }
99
100     // Hacky hack: During type-checking, we treat *all* operators
101     // as potentially overloaded. But then, during writeback, if
102     // we observe that something like `a+b` is (known to be)
103     // operating on scalars, we clear the overload.
104     fn fix_scalar_builtin_expr(&mut self, e: &hir::Expr) {
105         match e.node {
106             hir::ExprUnary(hir::UnNeg, ref inner) |
107             hir::ExprUnary(hir::UnNot, ref inner)  => {
108                 let inner_ty = self.fcx.node_ty(inner.hir_id);
109                 let inner_ty = self.fcx.resolve_type_vars_if_possible(&inner_ty);
110
111                 if inner_ty.is_scalar() {
112                     let mut tables = self.fcx.tables.borrow_mut();
113                     tables.validate_hir_id(e.hir_id);
114                     tables.type_dependent_defs.remove(&e.hir_id.local_id);
115                     tables.node_substs.remove(&e.hir_id.local_id);
116                 }
117             }
118             hir::ExprBinary(ref op, ref lhs, ref rhs) |
119             hir::ExprAssignOp(ref op, ref lhs, ref rhs) => {
120                 let lhs_ty = self.fcx.node_ty(lhs.hir_id);
121                 let lhs_ty = self.fcx.resolve_type_vars_if_possible(&lhs_ty);
122
123                 let rhs_ty = self.fcx.node_ty(rhs.hir_id);
124                 let rhs_ty = self.fcx.resolve_type_vars_if_possible(&rhs_ty);
125
126                 if lhs_ty.is_scalar() && rhs_ty.is_scalar() {
127                     let mut tables = self.fcx.tables.borrow_mut();
128                     tables.validate_hir_id(e.hir_id);
129                     tables.type_dependent_defs.remove(&e.hir_id.local_id);
130                     tables.node_substs.remove(&e.hir_id.local_id);
131
132                     match e.node {
133                         hir::ExprBinary(..) => {
134                             if !op.node.is_by_value() {
135                                 tables.adjustments.get_mut(&lhs.hir_id.local_id).map(|a| a.pop());
136                                 tables.adjustments.get_mut(&rhs.hir_id.local_id).map(|a| a.pop());
137                             }
138                         },
139                         hir::ExprAssignOp(..) => {
140                             tables.adjustments.get_mut(&lhs.hir_id.local_id).map(|a| a.pop());
141                         },
142                         _ => {},
143                     }
144                 }
145             }
146             _ => {},
147         }
148     }
149 }
150
151 ///////////////////////////////////////////////////////////////////////////
152 // Impl of Visitor for Resolver
153 //
154 // This is the master code which walks the AST. It delegates most of
155 // the heavy lifting to the generic visit and resolve functions
156 // below. In general, a function is made into a `visitor` if it must
157 // traffic in node-ids or update tables in the type context etc.
158
159 impl<'cx, 'gcx, 'tcx> Visitor<'gcx> for WritebackCx<'cx, 'gcx, 'tcx> {
160     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
161         NestedVisitorMap::None
162     }
163
164     fn visit_expr(&mut self, e: &'gcx hir::Expr) {
165         self.fix_scalar_builtin_expr(e);
166
167         self.visit_node_id(e.span, e.hir_id);
168
169         if let hir::ExprClosure(_, _, body, _) = e.node {
170             let body = self.fcx.tcx.hir.body(body);
171             for arg in &body.arguments {
172                 self.visit_node_id(e.span, arg.hir_id);
173             }
174
175             self.visit_body(body);
176         }
177
178         intravisit::walk_expr(self, e);
179     }
180
181     fn visit_block(&mut self, b: &'gcx hir::Block) {
182         self.visit_node_id(b.span, b.hir_id);
183         intravisit::walk_block(self, b);
184     }
185
186     fn visit_pat(&mut self, p: &'gcx hir::Pat) {
187         match p.node {
188             hir::PatKind::Binding(..) => {
189                 let bm = {
190                     let fcx_tables = self.fcx.tables.borrow();
191                     fcx_tables.validate_hir_id(p.hir_id);
192                     *fcx_tables.pat_binding_modes.get(&p.hir_id.local_id)
193                                                  .expect("missing binding mode")
194                 };
195                 self.tables.validate_hir_id(p.hir_id);
196                 self.tables.pat_binding_modes.insert(p.hir_id.local_id, bm);
197             }
198             _ => {}
199         };
200
201         self.visit_node_id(p.span, p.hir_id);
202         intravisit::walk_pat(self, p);
203     }
204
205     fn visit_local(&mut self, l: &'gcx hir::Local) {
206         intravisit::walk_local(self, l);
207         let var_ty = self.fcx.local_ty(l.span, l.id);
208         let var_ty = self.resolve(&var_ty, &l.span);
209         self.write_ty_to_tables(l.hir_id, var_ty);
210     }
211 }
212
213 impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
214     fn visit_upvar_borrow_map(&mut self) {
215         for (upvar_id, upvar_capture) in self.fcx.tables.borrow().upvar_capture_map.iter() {
216             let new_upvar_capture = match *upvar_capture {
217                 ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue,
218                 ty::UpvarCapture::ByRef(ref upvar_borrow) => {
219                     let r = upvar_borrow.region;
220                     let r = self.resolve(&r, &upvar_id.var_id);
221                     ty::UpvarCapture::ByRef(
222                         ty::UpvarBorrow { kind: upvar_borrow.kind, region: r })
223                 }
224             };
225             debug!("Upvar capture for {:?} resolved to {:?}",
226                    upvar_id,
227                    new_upvar_capture);
228             self.tables.upvar_capture_map.insert(*upvar_id, new_upvar_capture);
229         }
230     }
231
232     fn visit_closures(&mut self) {
233         let fcx_tables = self.fcx.tables.borrow();
234         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
235
236         for (&id, closure_ty) in fcx_tables.closure_tys.iter() {
237             let hir_id = hir::HirId {
238                 owner: fcx_tables.local_id_root.index,
239                 local_id: id,
240             };
241             let closure_ty = self.resolve(closure_ty, &hir_id);
242             self.tables.closure_tys.insert(id, closure_ty);
243         }
244
245         for (&id, &closure_kind) in fcx_tables.closure_kinds.iter() {
246             self.tables.closure_kinds.insert(id, closure_kind);
247         }
248     }
249
250     fn visit_cast_types(&mut self) {
251         self.tables.cast_kinds.extend(
252             self.fcx.tables.borrow().cast_kinds.iter().map(|(&key, &value)| (key, value)));
253     }
254
255     fn visit_free_region_map(&mut self) {
256         let free_region_map = self.tcx().lift_to_global(&self.fcx.tables.borrow().free_region_map);
257         let free_region_map = free_region_map.expect("all regions in free-region-map are global");
258         self.tables.free_region_map = free_region_map;
259     }
260
261     fn visit_anon_types(&mut self) {
262         let gcx = self.tcx().global_tcx();
263         for (&node_id, &concrete_ty) in self.fcx.anon_types.borrow().iter() {
264             let inside_ty = self.resolve(&concrete_ty, &node_id);
265
266             // Convert the type from the function into a type valid outside
267             // the function, by replacing invalid regions with 'static,
268             // after producing an error for each of them.
269             let outside_ty = gcx.fold_regions(&inside_ty, &mut false, |r, _| {
270                 match *r {
271                     // 'static and early-bound regions are valid.
272                     ty::ReStatic |
273                     ty::ReEarlyBound(_) |
274                     ty::ReEmpty => r,
275
276                     ty::ReFree(_) |
277                     ty::ReLateBound(..) |
278                     ty::ReScope(_) |
279                     ty::ReSkolemized(..) => {
280                         let span = node_id.to_span(&self.fcx.tcx);
281                         span_err!(self.tcx().sess, span, E0564,
282                                   "only named lifetimes are allowed in `impl Trait`, \
283                                    but `{}` was found in the type `{}`", r, inside_ty);
284                         gcx.types.re_static
285                     }
286
287                     ty::ReVar(_) |
288                     ty::ReErased => {
289                         let span = node_id.to_span(&self.fcx.tcx);
290                         span_bug!(span, "invalid region in impl Trait: {:?}", r);
291                     }
292                 }
293             });
294
295             let hir_id = self.tcx().hir.node_to_hir_id(node_id);
296             self.tables.validate_hir_id(hir_id);
297             self.tables.node_types.insert(hir_id.local_id, outside_ty);
298         }
299     }
300
301     fn visit_node_id(&mut self, span: Span, hir_id: hir::HirId) {
302         {
303             let mut fcx_tables = self.fcx.tables.borrow_mut();
304             fcx_tables.validate_hir_id(hir_id);
305             // Export associated path extensions and method resultions.
306             if let Some(def) = fcx_tables.type_dependent_defs.remove(&hir_id.local_id) {
307                 self.tables.validate_hir_id(hir_id);
308                 self.tables.type_dependent_defs.insert(hir_id.local_id, def);
309             }
310         }
311
312         // Resolve any borrowings for the node with id `node_id`
313         self.visit_adjustments(span, hir_id);
314
315         // Resolve the type of the node with id `node_id`
316         let n_ty = self.fcx.node_ty(hir_id);
317         let n_ty = self.resolve(&n_ty, &span);
318         self.write_ty_to_tables(hir_id, n_ty);
319         debug!("Node {:?} has type {:?}", hir_id, n_ty);
320
321         // Resolve any substitutions
322         if let Some(&substs) = self.fcx.tables.borrow().node_substs.get(&hir_id.local_id) {
323             let substs = self.resolve(&substs, &span);
324             debug!("write_substs_to_tcx({:?}, {:?})", hir_id, substs);
325             assert!(!substs.needs_infer());
326             self.tables.node_substs.insert(hir_id.local_id, substs);
327         }
328     }
329
330     fn visit_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
331         let adjustment = {
332             let mut fcx_tables = self.fcx.tables.borrow_mut();
333             fcx_tables.validate_hir_id(hir_id);
334             fcx_tables.adjustments.remove(&hir_id.local_id)
335         };
336         match adjustment {
337             None => {
338                 debug!("No adjustments for node {:?}", hir_id);
339             }
340
341             Some(adjustment) => {
342                 let resolved_adjustment = self.resolve(&adjustment, &span);
343                 debug!("Adjustments for node {:?}: {:?}", hir_id, resolved_adjustment);
344                 self.tables.validate_hir_id(hir_id);
345                 self.tables.adjustments.insert(hir_id.local_id, resolved_adjustment);
346             }
347         }
348     }
349
350     fn visit_liberated_fn_sigs(&mut self) {
351         let fcx_tables = self.fcx.tables.borrow();
352         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
353
354         for (&local_id, fn_sig) in fcx_tables.liberated_fn_sigs.iter() {
355             let hir_id = hir::HirId {
356                 owner: fcx_tables.local_id_root.index,
357                 local_id,
358             };
359             let fn_sig = self.resolve(fn_sig, &hir_id);
360             self.tables.liberated_fn_sigs.insert(local_id, fn_sig.clone());
361         }
362     }
363
364     fn visit_fru_field_types(&mut self) {
365         let fcx_tables = self.fcx.tables.borrow();
366         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
367
368         for (&local_id, ftys) in fcx_tables.fru_field_types.iter() {
369             let hir_id = hir::HirId {
370                 owner: fcx_tables.local_id_root.index,
371                 local_id,
372             };
373             let ftys = self.resolve(ftys, &hir_id);
374             self.tables.fru_field_types.insert(local_id, ftys);
375         }
376     }
377
378     fn resolve<T>(&self, x: &T, span: &Locatable) -> T::Lifted
379         where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
380     {
381         let x = x.fold_with(&mut Resolver::new(self.fcx, span, self.body));
382         if let Some(lifted) = self.tcx().lift_to_global(&x) {
383             lifted
384         } else {
385             span_bug!(span.to_span(&self.fcx.tcx),
386                       "writeback: `{:?}` missing from the global type context",
387                       x);
388         }
389     }
390 }
391
392 trait Locatable {
393     fn to_span(&self, tcx: &TyCtxt) -> Span;
394 }
395
396 impl Locatable for Span {
397     fn to_span(&self, _: &TyCtxt) -> Span { *self }
398 }
399
400 impl Locatable for ast::NodeId {
401     fn to_span(&self, tcx: &TyCtxt) -> Span { tcx.hir.span(*self) }
402 }
403
404 impl Locatable for hir::HirId {
405     fn to_span(&self, tcx: &TyCtxt) -> Span {
406         let node_id = tcx.hir.definitions().find_node_for_hir_id(*self);
407         tcx.hir.span(node_id)
408     }
409 }
410
411 ///////////////////////////////////////////////////////////////////////////
412 // The Resolver. This is the type folding engine that detects
413 // unresolved types and so forth.
414
415 struct Resolver<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
416     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
417     infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
418     span: &'cx Locatable,
419     body: &'gcx hir::Body,
420 }
421
422 impl<'cx, 'gcx, 'tcx> Resolver<'cx, 'gcx, 'tcx> {
423     fn new(fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>, span: &'cx Locatable, body: &'gcx hir::Body)
424         -> Resolver<'cx, 'gcx, 'tcx>
425     {
426         Resolver {
427             tcx: fcx.tcx,
428             infcx: fcx,
429             span: span,
430             body: body,
431         }
432     }
433
434     fn report_error(&self, t: Ty<'tcx>) {
435         if !self.tcx.sess.has_errors() {
436             self.infcx.need_type_info(Some(self.body.id()), self.span.to_span(&self.tcx), t);
437         }
438     }
439 }
440
441 impl<'cx, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for Resolver<'cx, 'gcx, 'tcx> {
442     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx> {
443         self.tcx
444     }
445
446     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
447         match self.infcx.fully_resolve(&t) {
448             Ok(t) => t,
449             Err(_) => {
450                 debug!("Resolver::fold_ty: input type `{:?}` not fully resolvable",
451                        t);
452                 self.report_error(t);
453                 self.tcx().types.err
454             }
455         }
456     }
457
458     // FIXME This should be carefully checked
459     // We could use `self.report_error` but it doesn't accept a ty::Region, right now.
460     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
461         match self.infcx.fully_resolve(&r) {
462             Ok(r) => r,
463             Err(_) => {
464                 self.tcx.types.re_static
465             }
466         }
467     }
468 }
469
470 ///////////////////////////////////////////////////////////////////////////
471 // During type check, we store promises with the result of trait
472 // lookup rather than the actual results (because the results are not
473 // necessarily available immediately). These routines unwind the
474 // promises. It is expected that we will have already reported any
475 // errors that may be encountered, so if the promises store an error,
476 // a dummy result is returned.