]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/writeback.rs
Fix impl Trait Lifetime Handling
[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::ty::subst::{Kind, Substs};
23 use rustc::util::nodemap::{DefIdSet, FxHashMap};
24 use syntax::ast;
25 use syntax_pos::Span;
26 use std::mem;
27 use std::rc::Rc;
28
29 ///////////////////////////////////////////////////////////////////////////
30 // Entry point
31
32 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
33     pub fn resolve_type_vars_in_body(&self, body: &'gcx hir::Body)
34                                      -> &'gcx ty::TypeckTables<'gcx> {
35         let item_id = self.tcx.hir.body_owner(body.id());
36         let item_def_id = self.tcx.hir.local_def_id(item_id);
37
38         let mut wbcx = WritebackCx::new(self, body);
39         for arg in &body.arguments {
40             wbcx.visit_node_id(arg.pat.span, arg.hir_id);
41         }
42         wbcx.visit_body(body);
43         wbcx.visit_upvar_borrow_map();
44         wbcx.visit_closures();
45         wbcx.visit_liberated_fn_sigs();
46         wbcx.visit_fru_field_types();
47         wbcx.visit_anon_types();
48         wbcx.visit_cast_types();
49         wbcx.visit_free_region_map();
50         wbcx.visit_generator_sigs();
51         wbcx.visit_generator_interiors();
52
53         let used_trait_imports = mem::replace(&mut self.tables.borrow_mut().used_trait_imports,
54                                               Rc::new(DefIdSet()));
55         debug!("used_trait_imports({:?}) = {:?}", item_def_id, used_trait_imports);
56         wbcx.tables.used_trait_imports = used_trait_imports;
57
58         wbcx.tables.tainted_by_errors = self.is_tainted_by_errors();
59
60         self.tcx.alloc_tables(wbcx.tables)
61     }
62 }
63
64 ///////////////////////////////////////////////////////////////////////////
65 // The Writerback context. This visitor walks the AST, checking the
66 // fn-specific tables to find references to types or regions. It
67 // resolves those regions to remove inference variables and writes the
68 // final result back into the master tables in the tcx. Here and
69 // there, it applies a few ad-hoc checks that were not convenient to
70 // do elsewhere.
71
72 struct WritebackCx<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
73     fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>,
74
75     tables: ty::TypeckTables<'gcx>,
76
77     body: &'gcx hir::Body,
78 }
79
80 impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
81     fn new(fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>, body: &'gcx hir::Body)
82         -> WritebackCx<'cx, 'gcx, 'tcx>
83     {
84         let owner = fcx.tcx.hir.definitions().node_to_hir_id(body.id().node_id);
85
86         WritebackCx {
87             fcx,
88             tables: ty::TypeckTables::empty(Some(DefId::local(owner.owner))),
89             body,
90         }
91     }
92
93     fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
94         self.fcx.tcx
95     }
96
97     fn write_ty_to_tables(&mut self, hir_id: hir::HirId, ty: Ty<'gcx>) {
98         debug!("write_ty_to_tables({:?}, {:?})", hir_id,  ty);
99         assert!(!ty.needs_infer());
100         self.tables.node_types_mut().insert(hir_id, ty);
101     }
102
103     // Hacky hack: During type-checking, we treat *all* operators
104     // as potentially overloaded. But then, during writeback, if
105     // we observe that something like `a+b` is (known to be)
106     // operating on scalars, we clear the overload.
107     fn fix_scalar_builtin_expr(&mut self, e: &hir::Expr) {
108         match e.node {
109             hir::ExprUnary(hir::UnNeg, ref inner) |
110             hir::ExprUnary(hir::UnNot, ref inner)  => {
111                 let inner_ty = self.fcx.node_ty(inner.hir_id);
112                 let inner_ty = self.fcx.resolve_type_vars_if_possible(&inner_ty);
113
114                 if inner_ty.is_scalar() {
115                     let mut tables = self.fcx.tables.borrow_mut();
116                     tables.type_dependent_defs_mut().remove(e.hir_id);
117                     tables.node_substs_mut().remove(e.hir_id);
118                 }
119             }
120             hir::ExprBinary(ref op, ref lhs, ref rhs) |
121             hir::ExprAssignOp(ref op, ref lhs, ref rhs) => {
122                 let lhs_ty = self.fcx.node_ty(lhs.hir_id);
123                 let lhs_ty = self.fcx.resolve_type_vars_if_possible(&lhs_ty);
124
125                 let rhs_ty = self.fcx.node_ty(rhs.hir_id);
126                 let rhs_ty = self.fcx.resolve_type_vars_if_possible(&rhs_ty);
127
128                 if lhs_ty.is_scalar() && rhs_ty.is_scalar() {
129                     let mut tables = self.fcx.tables.borrow_mut();
130                     tables.type_dependent_defs_mut().remove(e.hir_id);
131                     tables.node_substs_mut().remove(e.hir_id);
132
133                     match e.node {
134                         hir::ExprBinary(..) => {
135                             if !op.node.is_by_value() {
136                                 let mut adjustments = tables.adjustments_mut();
137                                 adjustments.get_mut(lhs.hir_id).map(|a| a.pop());
138                                 adjustments.get_mut(rhs.hir_id).map(|a| a.pop());
139                             }
140                         },
141                         hir::ExprAssignOp(..) => {
142                             tables.adjustments_mut().get_mut(lhs.hir_id).map(|a| a.pop());
143                         },
144                         _ => {},
145                     }
146                 }
147             }
148             _ => {},
149         }
150     }
151 }
152
153 ///////////////////////////////////////////////////////////////////////////
154 // Impl of Visitor for Resolver
155 //
156 // This is the master code which walks the AST. It delegates most of
157 // the heavy lifting to the generic visit and resolve functions
158 // below. In general, a function is made into a `visitor` if it must
159 // traffic in node-ids or update tables in the type context etc.
160
161 impl<'cx, 'gcx, 'tcx> Visitor<'gcx> for WritebackCx<'cx, 'gcx, 'tcx> {
162     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
163         NestedVisitorMap::None
164     }
165
166     fn visit_expr(&mut self, e: &'gcx hir::Expr) {
167         self.fix_scalar_builtin_expr(e);
168
169         self.visit_node_id(e.span, e.hir_id);
170
171         if let hir::ExprClosure(_, _, body, _, _) = e.node {
172             let body = self.fcx.tcx.hir.body(body);
173             for arg in &body.arguments {
174                 self.visit_node_id(e.span, arg.hir_id);
175             }
176
177             self.visit_body(body);
178         }
179
180         intravisit::walk_expr(self, e);
181     }
182
183     fn visit_block(&mut self, b: &'gcx hir::Block) {
184         self.visit_node_id(b.span, b.hir_id);
185         intravisit::walk_block(self, b);
186     }
187
188     fn visit_pat(&mut self, p: &'gcx hir::Pat) {
189         match p.node {
190             hir::PatKind::Binding(..) => {
191                 let bm = *self.fcx
192                               .tables
193                               .borrow()
194                               .pat_binding_modes()
195                               .get(p.hir_id)
196                               .expect("missing binding mode");
197                 self.tables.pat_binding_modes_mut().insert(p.hir_id, bm);
198             }
199             _ => {}
200         };
201
202         self.visit_pat_adjustments(p.span, p.hir_id);
203
204         self.visit_node_id(p.span, p.hir_id);
205         intravisit::walk_pat(self, p);
206     }
207
208     fn visit_local(&mut self, l: &'gcx hir::Local) {
209         intravisit::walk_local(self, l);
210         let var_ty = self.fcx.local_ty(l.span, l.id);
211         let var_ty = self.resolve(&var_ty, &l.span);
212         self.write_ty_to_tables(l.hir_id, var_ty);
213     }
214
215     fn visit_ty(&mut self, hir_ty: &'gcx hir::Ty) {
216         intravisit::walk_ty(self, hir_ty);
217         let ty = self.fcx.node_ty(hir_ty.hir_id);
218         let ty = self.resolve(&ty, &hir_ty.span);
219         self.write_ty_to_tables(hir_ty.hir_id, ty);
220     }
221 }
222
223 impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
224     fn visit_upvar_borrow_map(&mut self) {
225         for (upvar_id, upvar_capture) in self.fcx.tables.borrow().upvar_capture_map.iter() {
226             let new_upvar_capture = match *upvar_capture {
227                 ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue,
228                 ty::UpvarCapture::ByRef(ref upvar_borrow) => {
229                     let r = upvar_borrow.region;
230                     let r = self.resolve(&r, &upvar_id.var_id);
231                     ty::UpvarCapture::ByRef(
232                         ty::UpvarBorrow { kind: upvar_borrow.kind, region: r })
233                 }
234             };
235             debug!("Upvar capture for {:?} resolved to {:?}",
236                    upvar_id,
237                    new_upvar_capture);
238             self.tables.upvar_capture_map.insert(*upvar_id, new_upvar_capture);
239         }
240     }
241
242     fn visit_closures(&mut self) {
243         let fcx_tables = self.fcx.tables.borrow();
244         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
245         let common_local_id_root = fcx_tables.local_id_root.unwrap();
246
247         for (&id, closure_ty) in fcx_tables.closure_tys().iter() {
248             let hir_id = hir::HirId {
249                 owner: common_local_id_root.index,
250                 local_id: id,
251             };
252             let closure_ty = self.resolve(closure_ty, &hir_id);
253             self.tables.closure_tys_mut().insert(hir_id, closure_ty);
254         }
255
256         for (&id, &closure_kind) in fcx_tables.closure_kinds().iter() {
257             let hir_id = hir::HirId {
258                 owner: common_local_id_root.index,
259                 local_id: id,
260             };
261             self.tables.closure_kinds_mut().insert(hir_id, closure_kind);
262         }
263     }
264
265     fn visit_cast_types(&mut self) {
266         let fcx_tables = self.fcx.tables.borrow();
267         let fcx_cast_kinds = fcx_tables.cast_kinds();
268         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
269         let mut self_cast_kinds = self.tables.cast_kinds_mut();
270         let common_local_id_root = fcx_tables.local_id_root.unwrap();
271
272         for (&local_id, &cast_kind) in fcx_cast_kinds.iter() {
273             let hir_id = hir::HirId {
274                 owner: common_local_id_root.index,
275                 local_id,
276             };
277             self_cast_kinds.insert(hir_id, cast_kind);
278         }
279     }
280
281     fn visit_free_region_map(&mut self) {
282         let free_region_map = self.tcx().lift_to_global(&self.fcx.tables.borrow().free_region_map);
283         let free_region_map = free_region_map.expect("all regions in free-region-map are global");
284         self.tables.free_region_map = free_region_map;
285     }
286
287     fn visit_anon_types(&mut self) {
288         let gcx = self.tcx().global_tcx();
289         for (&def_id, anon_defn) in self.fcx.anon_types.borrow().iter() {
290             let node_id = gcx.hir.as_local_node_id(def_id).unwrap();
291             let inside_ty = self.resolve(&anon_defn.concrete_ty, &node_id);
292
293             // Use substs to build up a reverse map from regions
294             // to their identity mappings.
295             // This is necessary because of `impl Trait` lifetimes
296             // are computed by replacing existing lifetimes with 'static
297             // and remapping only those used in the `impl Trait` return type,
298             // resulting in the parameters shifting.
299             let id_substs = Substs::identity_for_item(gcx, def_id);
300             let map: FxHashMap<Kind<'tcx>, Kind<'gcx>> =
301                 anon_defn.substs
302                          .iter()
303                          .enumerate()
304                          .map(|(index, subst)| (*subst, id_substs[index]))
305                          .collect();
306
307             // Convert the type from the function into a type valid outside
308             // the function, by replacing invalid regions with 'static,
309             // after producing an error for each of them.
310             let outside_ty = gcx.fold_regions(&inside_ty, &mut false, |r, _| {
311                 match *r {
312                     // 'static and early-bound regions are valid.
313                     ty::ReStatic |
314                     ty::ReEmpty => r,
315
316                     // All other regions, we map them appropriately to their adjusted
317                     // indices, erroring if we find any lifetimes that were not mapped
318                     // into the new set.
319                     _ => if let Some(r1) =
320                             map.get(&Kind::from(r)).and_then(|k| k.as_region()) { r1 } else
321                         {
322                             // No mapping was found. This means that
323                             // it is either a disallowed lifetime,
324                             // which will be caught by regionck, or it
325                             // is a region in a non-upvar closure
326                             // generic, which is explicitly
327                             // allowed. If that surprises you, read
328                             // on.
329                             //
330                             // The case of closure is a somewhat
331                             // subtle (read: hacky) consideration. The
332                             // problem is that our closure types
333                             // currently include all the lifetime
334                             // parameters declared on the enclosing
335                             // function, even if they are unused by
336                             // the closure itself. We can't readily
337                             // filter them out, so here we replace
338                             // those values with `'empty`. This can't
339                             // really make a difference to the rest of
340                             // the compiler; those regions are ignored
341                             // for the outlives relation, and hence
342                             // don't affect trait selection or auto
343                             // traits, and they are erased during
344                             // trans.
345                             gcx.types.re_empty
346                         },
347                 }
348             });
349
350             let hir_id = self.tcx().hir.node_to_hir_id(node_id);
351             self.tables.node_types_mut().insert(hir_id, outside_ty);
352         }
353     }
354
355     fn visit_node_id(&mut self, span: Span, hir_id: hir::HirId) {
356         // Export associated path extensions and method resultions.
357         if let Some(def) = self.fcx
358                                .tables
359                                .borrow_mut()
360                                .type_dependent_defs_mut()
361                                .remove(hir_id) {
362             self.tables.type_dependent_defs_mut().insert(hir_id, def);
363         }
364
365         // Resolve any borrowings for the node with id `node_id`
366         self.visit_adjustments(span, hir_id);
367
368         // Resolve the type of the node with id `node_id`
369         let n_ty = self.fcx.node_ty(hir_id);
370         let n_ty = self.resolve(&n_ty, &span);
371         self.write_ty_to_tables(hir_id, n_ty);
372         debug!("Node {:?} has type {:?}", hir_id, n_ty);
373
374         // Resolve any substitutions
375         if let Some(substs) = self.fcx.tables.borrow().node_substs_opt(hir_id) {
376             let substs = self.resolve(&substs, &span);
377             debug!("write_substs_to_tcx({:?}, {:?})", hir_id, substs);
378             assert!(!substs.needs_infer());
379             self.tables.node_substs_mut().insert(hir_id, substs);
380         }
381     }
382
383     fn visit_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
384         let adjustment = self.fcx
385                              .tables
386                              .borrow_mut()
387                              .adjustments_mut()
388                              .remove(hir_id);
389         match adjustment {
390             None => {
391                 debug!("No adjustments for node {:?}", hir_id);
392             }
393
394             Some(adjustment) => {
395                 let resolved_adjustment = self.resolve(&adjustment, &span);
396                 debug!("Adjustments for node {:?}: {:?}", hir_id, resolved_adjustment);
397                 self.tables.adjustments_mut().insert(hir_id, resolved_adjustment);
398             }
399         }
400     }
401
402     fn visit_pat_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
403         let adjustment = self.fcx
404                              .tables
405                              .borrow_mut()
406                              .pat_adjustments_mut()
407                              .remove(hir_id);
408         match adjustment {
409             None => {
410                 debug!("No pat_adjustments for node {:?}", hir_id);
411             }
412
413             Some(adjustment) => {
414                 let resolved_adjustment = self.resolve(&adjustment, &span);
415                 debug!("pat_adjustments for node {:?}: {:?}", hir_id, resolved_adjustment);
416                 self.tables.pat_adjustments_mut().insert(hir_id, resolved_adjustment);
417             }
418         }
419     }
420
421     fn visit_generator_interiors(&mut self) {
422         let common_local_id_root = self.fcx.tables.borrow().local_id_root.unwrap();
423         for (&id, interior) in self.fcx.tables.borrow().generator_interiors().iter() {
424             let hir_id = hir::HirId {
425                 owner: common_local_id_root.index,
426                 local_id: id,
427             };
428             let interior = self.resolve(interior, &hir_id);
429             self.tables.generator_interiors_mut().insert(hir_id, interior);
430         }
431     }
432
433     fn visit_generator_sigs(&mut self) {
434         let common_local_id_root = self.fcx.tables.borrow().local_id_root.unwrap();
435         for (&id, gen_sig) in self.fcx.tables.borrow().generator_sigs().iter() {
436             let hir_id = hir::HirId {
437                 owner: common_local_id_root.index,
438                 local_id: id,
439             };
440             let gen_sig = gen_sig.map(|s| ty::GenSig {
441                 yield_ty: self.resolve(&s.yield_ty, &hir_id),
442                 return_ty: self.resolve(&s.return_ty, &hir_id),
443             });
444             self.tables.generator_sigs_mut().insert(hir_id, gen_sig);
445         }
446     }
447
448     fn visit_liberated_fn_sigs(&mut self) {
449         let fcx_tables = self.fcx.tables.borrow();
450         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
451         let common_local_id_root = fcx_tables.local_id_root.unwrap();
452
453         for (&local_id, fn_sig) in fcx_tables.liberated_fn_sigs().iter() {
454             let hir_id = hir::HirId {
455                 owner: common_local_id_root.index,
456                 local_id,
457             };
458             let fn_sig = self.resolve(fn_sig, &hir_id);
459             self.tables.liberated_fn_sigs_mut().insert(hir_id, fn_sig.clone());
460         }
461     }
462
463     fn visit_fru_field_types(&mut self) {
464         let fcx_tables = self.fcx.tables.borrow();
465         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
466         let common_local_id_root = fcx_tables.local_id_root.unwrap();
467
468         for (&local_id, ftys) in fcx_tables.fru_field_types().iter() {
469             let hir_id = hir::HirId {
470                 owner: common_local_id_root.index,
471                 local_id,
472             };
473             let ftys = self.resolve(ftys, &hir_id);
474             self.tables.fru_field_types_mut().insert(hir_id, ftys);
475         }
476     }
477
478     fn resolve<T>(&self, x: &T, span: &Locatable) -> T::Lifted
479         where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
480     {
481         let x = x.fold_with(&mut Resolver::new(self.fcx, span, self.body));
482         if let Some(lifted) = self.tcx().lift_to_global(&x) {
483             lifted
484         } else {
485             span_bug!(span.to_span(&self.fcx.tcx),
486                       "writeback: `{:?}` missing from the global type context",
487                       x);
488         }
489     }
490 }
491
492 trait Locatable {
493     fn to_span(&self, tcx: &TyCtxt) -> Span;
494 }
495
496 impl Locatable for Span {
497     fn to_span(&self, _: &TyCtxt) -> Span { *self }
498 }
499
500 impl Locatable for ast::NodeId {
501     fn to_span(&self, tcx: &TyCtxt) -> Span { tcx.hir.span(*self) }
502 }
503
504 impl Locatable for DefIndex {
505     fn to_span(&self, tcx: &TyCtxt) -> Span {
506         let node_id = tcx.hir.def_index_to_node_id(*self);
507         tcx.hir.span(node_id)
508     }
509 }
510
511 impl Locatable for hir::HirId {
512     fn to_span(&self, tcx: &TyCtxt) -> Span {
513         let node_id = tcx.hir.definitions().find_node_for_hir_id(*self);
514         tcx.hir.span(node_id)
515     }
516 }
517
518 ///////////////////////////////////////////////////////////////////////////
519 // The Resolver. This is the type folding engine that detects
520 // unresolved types and so forth.
521
522 struct Resolver<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
523     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
524     infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
525     span: &'cx Locatable,
526     body: &'gcx hir::Body,
527 }
528
529 impl<'cx, 'gcx, 'tcx> Resolver<'cx, 'gcx, 'tcx> {
530     fn new(fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>, span: &'cx Locatable, body: &'gcx hir::Body)
531         -> Resolver<'cx, 'gcx, 'tcx>
532     {
533         Resolver {
534             tcx: fcx.tcx,
535             infcx: fcx,
536             span,
537             body,
538         }
539     }
540
541     fn report_error(&self, t: Ty<'tcx>) {
542         if !self.tcx.sess.has_errors() {
543             self.infcx.need_type_info(Some(self.body.id()), self.span.to_span(&self.tcx), t);
544         }
545     }
546 }
547
548 impl<'cx, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for Resolver<'cx, 'gcx, 'tcx> {
549     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx> {
550         self.tcx
551     }
552
553     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
554         match self.infcx.fully_resolve(&t) {
555             Ok(t) => t,
556             Err(_) => {
557                 debug!("Resolver::fold_ty: input type `{:?}` not fully resolvable",
558                        t);
559                 self.report_error(t);
560                 self.tcx().types.err
561             }
562         }
563     }
564
565     // FIXME This should be carefully checked
566     // We could use `self.report_error` but it doesn't accept a ty::Region, right now.
567     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
568         match self.infcx.fully_resolve(&r) {
569             Ok(r) => r,
570             Err(_) => {
571                 self.tcx.types.re_static
572             }
573         }
574     }
575 }
576
577 ///////////////////////////////////////////////////////////////////////////
578 // During type check, we store promises with the result of trait
579 // lookup rather than the actual results (because the results are not
580 // necessarily available immediately). These routines unwind the
581 // promises. It is expected that we will have already reported any
582 // errors that may be encountered, so if the promises store an error,
583 // a dummy result is returned.