]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/writeback.rs
Auto merge of #45063 - michaelwoerister:bring-back-incremental-info, r=nikomatsakis
[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, DefIndex};
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         wbcx.visit_generator_sigs();
49         wbcx.visit_generator_interiors();
50
51         let used_trait_imports = mem::replace(&mut self.tables.borrow_mut().used_trait_imports,
52                                               DefIdSet());
53         debug!("used_trait_imports({:?}) = {:?}", item_def_id, used_trait_imports);
54         wbcx.tables.used_trait_imports = used_trait_imports;
55
56         wbcx.tables.tainted_by_errors = self.is_tainted_by_errors();
57
58         self.tcx.alloc_tables(wbcx.tables)
59     }
60 }
61
62 ///////////////////////////////////////////////////////////////////////////
63 // The Writerback context. This visitor walks the AST, checking the
64 // fn-specific tables to find references to types or regions. It
65 // resolves those regions to remove inference variables and writes the
66 // final result back into the master tables in the tcx. Here and
67 // there, it applies a few ad-hoc checks that were not convenient to
68 // do elsewhere.
69
70 struct WritebackCx<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
71     fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>,
72
73     tables: ty::TypeckTables<'gcx>,
74
75     body: &'gcx hir::Body,
76 }
77
78 impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
79     fn new(fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>, body: &'gcx hir::Body)
80         -> WritebackCx<'cx, 'gcx, 'tcx>
81     {
82         let owner = fcx.tcx.hir.definitions().node_to_hir_id(body.id().node_id);
83
84         WritebackCx {
85             fcx,
86             tables: ty::TypeckTables::empty(Some(DefId::local(owner.owner))),
87             body,
88         }
89     }
90
91     fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
92         self.fcx.tcx
93     }
94
95     fn write_ty_to_tables(&mut self, hir_id: hir::HirId, ty: Ty<'gcx>) {
96         debug!("write_ty_to_tables({:?}, {:?})", hir_id,  ty);
97         assert!(!ty.needs_infer());
98         self.tables.node_types_mut().insert(hir_id, ty);
99     }
100
101     // Hacky hack: During type-checking, we treat *all* operators
102     // as potentially overloaded. But then, during writeback, if
103     // we observe that something like `a+b` is (known to be)
104     // operating on scalars, we clear the overload.
105     fn fix_scalar_builtin_expr(&mut self, e: &hir::Expr) {
106         match e.node {
107             hir::ExprUnary(hir::UnNeg, ref inner) |
108             hir::ExprUnary(hir::UnNot, ref inner)  => {
109                 let inner_ty = self.fcx.node_ty(inner.hir_id);
110                 let inner_ty = self.fcx.resolve_type_vars_if_possible(&inner_ty);
111
112                 if inner_ty.is_scalar() {
113                     let mut tables = self.fcx.tables.borrow_mut();
114                     tables.type_dependent_defs_mut().remove(e.hir_id);
115                     tables.node_substs_mut().remove(e.hir_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.type_dependent_defs_mut().remove(e.hir_id);
129                     tables.node_substs_mut().remove(e.hir_id);
130
131                     match e.node {
132                         hir::ExprBinary(..) => {
133                             if !op.node.is_by_value() {
134                                 let mut adjustments = tables.adjustments_mut();
135                                 adjustments.get_mut(lhs.hir_id).map(|a| a.pop());
136                                 adjustments.get_mut(rhs.hir_id).map(|a| a.pop());
137                             }
138                         },
139                         hir::ExprAssignOp(..) => {
140                             tables.adjustments_mut().get_mut(lhs.hir_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 = *self.fcx
190                               .tables
191                               .borrow()
192                               .pat_binding_modes()
193                               .get(p.hir_id)
194                               .expect("missing binding mode");
195                 self.tables.pat_binding_modes_mut().insert(p.hir_id, bm);
196             }
197             _ => {}
198         };
199
200         self.visit_pat_adjustments(p.span, p.hir_id);
201
202         self.visit_node_id(p.span, p.hir_id);
203         intravisit::walk_pat(self, p);
204     }
205
206     fn visit_local(&mut self, l: &'gcx hir::Local) {
207         intravisit::walk_local(self, l);
208         let var_ty = self.fcx.local_ty(l.span, l.id);
209         let var_ty = self.resolve(&var_ty, &l.span);
210         self.write_ty_to_tables(l.hir_id, var_ty);
211     }
212
213     fn visit_ty(&mut self, hir_ty: &'gcx hir::Ty) {
214         intravisit::walk_ty(self, hir_ty);
215         let ty = self.fcx.node_ty(hir_ty.hir_id);
216         let ty = self.resolve(&ty, &hir_ty.span);
217         self.write_ty_to_tables(hir_ty.hir_id, ty);
218     }
219 }
220
221 impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
222     fn visit_upvar_borrow_map(&mut self) {
223         for (upvar_id, upvar_capture) in self.fcx.tables.borrow().upvar_capture_map.iter() {
224             let new_upvar_capture = match *upvar_capture {
225                 ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue,
226                 ty::UpvarCapture::ByRef(ref upvar_borrow) => {
227                     let r = upvar_borrow.region;
228                     let r = self.resolve(&r, &upvar_id.var_id);
229                     ty::UpvarCapture::ByRef(
230                         ty::UpvarBorrow { kind: upvar_borrow.kind, region: r })
231                 }
232             };
233             debug!("Upvar capture for {:?} resolved to {:?}",
234                    upvar_id,
235                    new_upvar_capture);
236             self.tables.upvar_capture_map.insert(*upvar_id, new_upvar_capture);
237         }
238     }
239
240     fn visit_closures(&mut self) {
241         let fcx_tables = self.fcx.tables.borrow();
242         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
243         let common_local_id_root = fcx_tables.local_id_root.unwrap();
244
245         for (&id, closure_ty) in fcx_tables.closure_tys().iter() {
246             let hir_id = hir::HirId {
247                 owner: common_local_id_root.index,
248                 local_id: id,
249             };
250             let closure_ty = self.resolve(closure_ty, &hir_id);
251             self.tables.closure_tys_mut().insert(hir_id, closure_ty);
252         }
253
254         for (&id, &closure_kind) in fcx_tables.closure_kinds().iter() {
255             let hir_id = hir::HirId {
256                 owner: common_local_id_root.index,
257                 local_id: id,
258             };
259             self.tables.closure_kinds_mut().insert(hir_id, closure_kind);
260         }
261     }
262
263     fn visit_cast_types(&mut self) {
264         let fcx_tables = self.fcx.tables.borrow();
265         let fcx_cast_kinds = fcx_tables.cast_kinds();
266         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
267         let mut self_cast_kinds = self.tables.cast_kinds_mut();
268         let common_local_id_root = fcx_tables.local_id_root.unwrap();
269
270         for (&local_id, &cast_kind) in fcx_cast_kinds.iter() {
271             let hir_id = hir::HirId {
272                 owner: common_local_id_root.index,
273                 local_id,
274             };
275             self_cast_kinds.insert(hir_id, cast_kind);
276         }
277     }
278
279     fn visit_free_region_map(&mut self) {
280         let free_region_map = self.tcx().lift_to_global(&self.fcx.tables.borrow().free_region_map);
281         let free_region_map = free_region_map.expect("all regions in free-region-map are global");
282         self.tables.free_region_map = free_region_map;
283     }
284
285     fn visit_anon_types(&mut self) {
286         let gcx = self.tcx().global_tcx();
287         for (&node_id, &concrete_ty) in self.fcx.anon_types.borrow().iter() {
288             let inside_ty = self.resolve(&concrete_ty, &node_id);
289
290             // Convert the type from the function into a type valid outside
291             // the function, by replacing invalid regions with 'static,
292             // after producing an error for each of them.
293             let outside_ty = gcx.fold_regions(&inside_ty, &mut false, |r, _| {
294                 match *r {
295                     // 'static and early-bound regions are valid.
296                     ty::ReStatic |
297                     ty::ReEarlyBound(_) |
298                     ty::ReEmpty => r,
299
300                     ty::ReFree(_) |
301                     ty::ReLateBound(..) |
302                     ty::ReScope(_) |
303                     ty::ReSkolemized(..) => {
304                         let span = node_id.to_span(&self.fcx.tcx);
305                         span_err!(self.tcx().sess, span, E0564,
306                                   "only named lifetimes are allowed in `impl Trait`, \
307                                    but `{}` was found in the type `{}`", r, inside_ty);
308                         gcx.types.re_static
309                     }
310
311                     ty::ReVar(_) |
312                     ty::ReErased => {
313                         let span = node_id.to_span(&self.fcx.tcx);
314                         span_bug!(span, "invalid region in impl Trait: {:?}", r);
315                     }
316                 }
317             });
318
319             let hir_id = self.tcx().hir.node_to_hir_id(node_id);
320             self.tables.node_types_mut().insert(hir_id, outside_ty);
321         }
322     }
323
324     fn visit_node_id(&mut self, span: Span, hir_id: hir::HirId) {
325         // Export associated path extensions and method resultions.
326         if let Some(def) = self.fcx
327                                .tables
328                                .borrow_mut()
329                                .type_dependent_defs_mut()
330                                .remove(hir_id) {
331             self.tables.type_dependent_defs_mut().insert(hir_id, def);
332         }
333
334         // Resolve any borrowings for the node with id `node_id`
335         self.visit_adjustments(span, hir_id);
336
337         // Resolve the type of the node with id `node_id`
338         let n_ty = self.fcx.node_ty(hir_id);
339         let n_ty = self.resolve(&n_ty, &span);
340         self.write_ty_to_tables(hir_id, n_ty);
341         debug!("Node {:?} has type {:?}", hir_id, n_ty);
342
343         // Resolve any substitutions
344         if let Some(substs) = self.fcx.tables.borrow().node_substs_opt(hir_id) {
345             let substs = self.resolve(&substs, &span);
346             debug!("write_substs_to_tcx({:?}, {:?})", hir_id, substs);
347             assert!(!substs.needs_infer());
348             self.tables.node_substs_mut().insert(hir_id, substs);
349         }
350     }
351
352     fn visit_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
353         let adjustment = self.fcx
354                              .tables
355                              .borrow_mut()
356                              .adjustments_mut()
357                              .remove(hir_id);
358         match adjustment {
359             None => {
360                 debug!("No adjustments for node {:?}", hir_id);
361             }
362
363             Some(adjustment) => {
364                 let resolved_adjustment = self.resolve(&adjustment, &span);
365                 debug!("Adjustments for node {:?}: {:?}", hir_id, resolved_adjustment);
366                 self.tables.adjustments_mut().insert(hir_id, resolved_adjustment);
367             }
368         }
369     }
370
371     fn visit_pat_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
372         let adjustment = self.fcx
373                              .tables
374                              .borrow_mut()
375                              .pat_adjustments_mut()
376                              .remove(hir_id);
377         match adjustment {
378             None => {
379                 debug!("No pat_adjustments for node {:?}", hir_id);
380             }
381
382             Some(adjustment) => {
383                 let resolved_adjustment = self.resolve(&adjustment, &span);
384                 debug!("pat_adjustments for node {:?}: {:?}", hir_id, resolved_adjustment);
385                 self.tables.pat_adjustments_mut().insert(hir_id, resolved_adjustment);
386             }
387         }
388     }
389
390     fn visit_generator_interiors(&mut self) {
391         let common_local_id_root = self.fcx.tables.borrow().local_id_root.unwrap();
392         for (&id, interior) in self.fcx.tables.borrow().generator_interiors().iter() {
393             let hir_id = hir::HirId {
394                 owner: common_local_id_root.index,
395                 local_id: id,
396             };
397             let interior = self.resolve(interior, &hir_id);
398             self.tables.generator_interiors_mut().insert(hir_id, interior);
399         }
400     }
401
402     fn visit_generator_sigs(&mut self) {
403         let common_local_id_root = self.fcx.tables.borrow().local_id_root.unwrap();
404         for (&id, gen_sig) in self.fcx.tables.borrow().generator_sigs().iter() {
405             let hir_id = hir::HirId {
406                 owner: common_local_id_root.index,
407                 local_id: id,
408             };
409             let gen_sig = gen_sig.map(|s| ty::GenSig {
410                 yield_ty: self.resolve(&s.yield_ty, &hir_id),
411                 return_ty: self.resolve(&s.return_ty, &hir_id),
412             });
413             self.tables.generator_sigs_mut().insert(hir_id, gen_sig);
414         }
415     }
416
417     fn visit_liberated_fn_sigs(&mut self) {
418         let fcx_tables = self.fcx.tables.borrow();
419         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
420         let common_local_id_root = fcx_tables.local_id_root.unwrap();
421
422         for (&local_id, fn_sig) in fcx_tables.liberated_fn_sigs().iter() {
423             let hir_id = hir::HirId {
424                 owner: common_local_id_root.index,
425                 local_id,
426             };
427             let fn_sig = self.resolve(fn_sig, &hir_id);
428             self.tables.liberated_fn_sigs_mut().insert(hir_id, fn_sig.clone());
429         }
430     }
431
432     fn visit_fru_field_types(&mut self) {
433         let fcx_tables = self.fcx.tables.borrow();
434         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
435         let common_local_id_root = fcx_tables.local_id_root.unwrap();
436
437         for (&local_id, ftys) in fcx_tables.fru_field_types().iter() {
438             let hir_id = hir::HirId {
439                 owner: common_local_id_root.index,
440                 local_id,
441             };
442             let ftys = self.resolve(ftys, &hir_id);
443             self.tables.fru_field_types_mut().insert(hir_id, ftys);
444         }
445     }
446
447     fn resolve<T>(&self, x: &T, span: &Locatable) -> T::Lifted
448         where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
449     {
450         let x = x.fold_with(&mut Resolver::new(self.fcx, span, self.body));
451         if let Some(lifted) = self.tcx().lift_to_global(&x) {
452             lifted
453         } else {
454             span_bug!(span.to_span(&self.fcx.tcx),
455                       "writeback: `{:?}` missing from the global type context",
456                       x);
457         }
458     }
459 }
460
461 trait Locatable {
462     fn to_span(&self, tcx: &TyCtxt) -> Span;
463 }
464
465 impl Locatable for Span {
466     fn to_span(&self, _: &TyCtxt) -> Span { *self }
467 }
468
469 impl Locatable for ast::NodeId {
470     fn to_span(&self, tcx: &TyCtxt) -> Span { tcx.hir.span(*self) }
471 }
472
473 impl Locatable for DefIndex {
474     fn to_span(&self, tcx: &TyCtxt) -> Span {
475         let node_id = tcx.hir.def_index_to_node_id(*self);
476         tcx.hir.span(node_id)
477     }
478 }
479
480 impl Locatable for hir::HirId {
481     fn to_span(&self, tcx: &TyCtxt) -> Span {
482         let node_id = tcx.hir.definitions().find_node_for_hir_id(*self);
483         tcx.hir.span(node_id)
484     }
485 }
486
487 ///////////////////////////////////////////////////////////////////////////
488 // The Resolver. This is the type folding engine that detects
489 // unresolved types and so forth.
490
491 struct Resolver<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
492     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
493     infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
494     span: &'cx Locatable,
495     body: &'gcx hir::Body,
496 }
497
498 impl<'cx, 'gcx, 'tcx> Resolver<'cx, 'gcx, 'tcx> {
499     fn new(fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>, span: &'cx Locatable, body: &'gcx hir::Body)
500         -> Resolver<'cx, 'gcx, 'tcx>
501     {
502         Resolver {
503             tcx: fcx.tcx,
504             infcx: fcx,
505             span,
506             body,
507         }
508     }
509
510     fn report_error(&self, t: Ty<'tcx>) {
511         if !self.tcx.sess.has_errors() {
512             self.infcx.need_type_info(Some(self.body.id()), self.span.to_span(&self.tcx), t);
513         }
514     }
515 }
516
517 impl<'cx, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for Resolver<'cx, 'gcx, 'tcx> {
518     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx> {
519         self.tcx
520     }
521
522     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
523         match self.infcx.fully_resolve(&t) {
524             Ok(t) => t,
525             Err(_) => {
526                 debug!("Resolver::fold_ty: input type `{:?}` not fully resolvable",
527                        t);
528                 self.report_error(t);
529                 self.tcx().types.err
530             }
531         }
532     }
533
534     // FIXME This should be carefully checked
535     // We could use `self.report_error` but it doesn't accept a ty::Region, right now.
536     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
537         match self.infcx.fully_resolve(&r) {
538             Ok(r) => r,
539             Err(_) => {
540                 self.tcx.types.re_static
541             }
542         }
543     }
544 }
545
546 ///////////////////////////////////////////////////////////////////////////
547 // During type check, we store promises with the result of trait
548 // lookup rather than the actual results (because the results are not
549 // necessarily available immediately). These routines unwind the
550 // promises. It is expected that we will have already reported any
551 // errors that may be encountered, so if the promises store an error,
552 // a dummy result is returned.