]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/writeback.rs
Auto merge of #41469 - arielb1:rustc-spring-cleaning, r=eddyb
[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, MethodCall, MethodCallee};
20 use rustc::ty::adjustment;
21 use rustc::ty::fold::{TypeFolder,TypeFoldable};
22 use rustc::util::nodemap::{DefIdMap, 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.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_type_nodes();
47         wbcx.visit_cast_types();
48         wbcx.visit_lints();
49         wbcx.visit_free_region_map();
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     // Mapping from free regions of the function to the
76     // early-bound versions of them, visible from the
77     // outside of the function. This is needed by, and
78     // only populated if there are any `impl Trait`.
79     free_to_bound_regions: DefIdMap<&'gcx ty::Region>,
80
81     body: &'gcx hir::Body,
82 }
83
84 impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
85     fn new(fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>, body: &'gcx hir::Body)
86         -> WritebackCx<'cx, 'gcx, 'tcx> {
87         let mut wbcx = WritebackCx {
88             fcx: fcx,
89             tables: ty::TypeckTables::empty(),
90             free_to_bound_regions: DefIdMap(),
91             body: body
92         };
93
94         // Only build the reverse mapping if `impl Trait` is used.
95         if fcx.anon_types.borrow().is_empty() {
96             return wbcx;
97         }
98
99         let gcx = fcx.tcx.global_tcx();
100         let free_substs = fcx.parameter_environment.free_substs;
101         for (i, k) in free_substs.iter().enumerate() {
102             let r = if let Some(r) = k.as_region() {
103                 r
104             } else {
105                 continue;
106             };
107             match *r {
108                 ty::ReFree(ty::FreeRegion {
109                     bound_region: ty::BoundRegion::BrNamed(def_id, name), ..
110                 }) => {
111                     let bound_region = gcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
112                         index: i as u32,
113                         name: name,
114                     }));
115                     wbcx.free_to_bound_regions.insert(def_id, bound_region);
116                 }
117                 _ => {
118                     bug!("{:?} is not a free region for an early-bound lifetime", r);
119                 }
120             }
121         }
122
123         wbcx
124     }
125
126     fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
127         self.fcx.tcx
128     }
129
130     fn write_ty_to_tables(&mut self, node_id: ast::NodeId, ty: Ty<'gcx>) {
131         debug!("write_ty_to_tables({}, {:?})", node_id,  ty);
132         assert!(!ty.needs_infer());
133         self.tables.node_types.insert(node_id, ty);
134     }
135
136     // Hacky hack: During type-checking, we treat *all* operators
137     // as potentially overloaded. But then, during writeback, if
138     // we observe that something like `a+b` is (known to be)
139     // operating on scalars, we clear the overload.
140     fn fix_scalar_builtin_expr(&mut self, e: &hir::Expr) {
141         match e.node {
142             hir::ExprUnary(hir::UnNeg, ref inner) |
143             hir::ExprUnary(hir::UnNot, ref inner)  => {
144                 let inner_ty = self.fcx.node_ty(inner.id);
145                 let inner_ty = self.fcx.resolve_type_vars_if_possible(&inner_ty);
146
147                 if inner_ty.is_scalar() {
148                     self.fcx.tables.borrow_mut().method_map.remove(&MethodCall::expr(e.id));
149                 }
150             }
151             hir::ExprBinary(ref op, ref lhs, ref rhs) |
152             hir::ExprAssignOp(ref op, ref lhs, ref rhs) => {
153                 let lhs_ty = self.fcx.node_ty(lhs.id);
154                 let lhs_ty = self.fcx.resolve_type_vars_if_possible(&lhs_ty);
155
156                 let rhs_ty = self.fcx.node_ty(rhs.id);
157                 let rhs_ty = self.fcx.resolve_type_vars_if_possible(&rhs_ty);
158
159                 if lhs_ty.is_scalar() && rhs_ty.is_scalar() {
160                     self.fcx.tables.borrow_mut().method_map.remove(&MethodCall::expr(e.id));
161
162                     // weird but true: the by-ref binops put an
163                     // adjustment on the lhs but not the rhs; the
164                     // adjustment for rhs is kind of baked into the
165                     // system.
166                     match e.node {
167                         hir::ExprBinary(..) => {
168                             if !op.node.is_by_value() {
169                                 self.fcx.tables.borrow_mut().adjustments.remove(&lhs.id);
170                             }
171                         },
172                         hir::ExprAssignOp(..) => {
173                             self.fcx.tables.borrow_mut().adjustments.remove(&lhs.id);
174                         },
175                         _ => {},
176                     }
177                 }
178             }
179             _ => {},
180         }
181     }
182 }
183
184 ///////////////////////////////////////////////////////////////////////////
185 // Impl of Visitor for Resolver
186 //
187 // This is the master code which walks the AST. It delegates most of
188 // the heavy lifting to the generic visit and resolve functions
189 // below. In general, a function is made into a `visitor` if it must
190 // traffic in node-ids or update tables in the type context etc.
191
192 impl<'cx, 'gcx, 'tcx> Visitor<'gcx> for WritebackCx<'cx, 'gcx, 'tcx> {
193     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
194         NestedVisitorMap::None
195     }
196
197     fn visit_stmt(&mut self, s: &'gcx hir::Stmt) {
198         self.visit_node_id(s.span, s.node.id());
199         intravisit::walk_stmt(self, s);
200     }
201
202     fn visit_expr(&mut self, e: &'gcx hir::Expr) {
203         self.fix_scalar_builtin_expr(e);
204
205         self.visit_node_id(e.span, e.id);
206         self.visit_method_map_entry(e.span, MethodCall::expr(e.id));
207
208         if let hir::ExprClosure(_, _, body, _) = e.node {
209             let body = self.fcx.tcx.hir.body(body);
210             for arg in &body.arguments {
211                 self.visit_node_id(e.span, arg.id);
212             }
213
214             self.visit_body(body);
215         }
216
217         intravisit::walk_expr(self, e);
218     }
219
220     fn visit_block(&mut self, b: &'gcx hir::Block) {
221         self.visit_node_id(b.span, b.id);
222         intravisit::walk_block(self, b);
223     }
224
225     fn visit_pat(&mut self, p: &'gcx hir::Pat) {
226         self.visit_node_id(p.span, p.id);
227         intravisit::walk_pat(self, p);
228     }
229
230     fn visit_local(&mut self, l: &'gcx hir::Local) {
231         intravisit::walk_local(self, l);
232         let var_ty = self.fcx.local_ty(l.span, l.id);
233         let var_ty = self.resolve(&var_ty, &l.span);
234         self.write_ty_to_tables(l.id, var_ty);
235     }
236 }
237
238 impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
239     fn visit_upvar_borrow_map(&mut self) {
240         for (upvar_id, upvar_capture) in self.fcx.tables.borrow().upvar_capture_map.iter() {
241             let new_upvar_capture = match *upvar_capture {
242                 ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue,
243                 ty::UpvarCapture::ByRef(ref upvar_borrow) => {
244                     let r = upvar_borrow.region;
245                     let r = self.resolve(&r, &upvar_id.var_id);
246                     ty::UpvarCapture::ByRef(
247                         ty::UpvarBorrow { kind: upvar_borrow.kind, region: r })
248                 }
249             };
250             debug!("Upvar capture for {:?} resolved to {:?}",
251                    upvar_id,
252                    new_upvar_capture);
253             self.tables.upvar_capture_map.insert(*upvar_id, new_upvar_capture);
254         }
255     }
256
257     fn visit_closures(&mut self) {
258         for (&id, closure_ty) in self.fcx.tables.borrow().closure_tys.iter() {
259             let closure_ty = self.resolve(closure_ty, &id);
260             self.tables.closure_tys.insert(id, closure_ty);
261         }
262
263         for (&id, &closure_kind) in self.fcx.tables.borrow().closure_kinds.iter() {
264             self.tables.closure_kinds.insert(id, closure_kind);
265         }
266     }
267
268     fn visit_cast_types(&mut self) {
269         self.tables.cast_kinds.extend(
270             self.fcx.tables.borrow().cast_kinds.iter().map(|(&key, &value)| (key, value)));
271     }
272
273     fn visit_lints(&mut self) {
274         self.fcx.tables.borrow_mut().lints.transfer(&mut self.tables.lints);
275     }
276
277     fn visit_free_region_map(&mut self) {
278         self.tables.free_region_map = self.fcx.tables.borrow().free_region_map.clone();
279     }
280
281     fn visit_anon_types(&mut self) {
282         let gcx = self.tcx().global_tcx();
283         for (&node_id, &concrete_ty) in self.fcx.anon_types.borrow().iter() {
284             let inside_ty = self.resolve(&concrete_ty, &node_id);
285
286             // Convert the type from the function into a type valid outside
287             // the function, by replacing free regions with early-bound ones.
288             let outside_ty = gcx.fold_regions(&inside_ty, &mut false, |r, _| {
289                 match *r {
290                     // 'static is valid everywhere.
291                     ty::ReStatic => gcx.types.re_static,
292                     ty::ReEmpty => gcx.types.re_empty,
293
294                     // Free regions that come from early-bound regions are valid.
295                     ty::ReFree(ty::FreeRegion {
296                         bound_region: ty::BoundRegion::BrNamed(def_id, ..), ..
297                     }) if self.free_to_bound_regions.contains_key(&def_id) => {
298                         self.free_to_bound_regions[&def_id]
299                     }
300
301                     ty::ReFree(_) |
302                     ty::ReEarlyBound(_) |
303                     ty::ReLateBound(..) |
304                     ty::ReScope(_) |
305                     ty::ReSkolemized(..) => {
306                         let span = node_id.to_span(&self.fcx.tcx);
307                         span_err!(self.tcx().sess, span, E0564,
308                                   "only named lifetimes are allowed in `impl Trait`, \
309                                    but `{}` was found in the type `{}`", r, inside_ty);
310                         gcx.types.re_static
311                     }
312
313                     ty::ReVar(_) |
314                     ty::ReErased => {
315                         let span = node_id.to_span(&self.fcx.tcx);
316                         span_bug!(span, "invalid region in impl Trait: {:?}", r);
317                     }
318                 }
319             });
320
321             self.tables.node_types.insert(node_id, outside_ty);
322         }
323     }
324
325     fn visit_node_id(&mut self, span: Span, node_id: ast::NodeId) {
326         // Export associated path extensions.
327         if let Some(def) = self.fcx.tables.borrow_mut().type_relative_path_defs.remove(&node_id) {
328             self.tables.type_relative_path_defs.insert(node_id, def);
329         }
330
331         // Resolve any borrowings for the node with id `node_id`
332         self.visit_adjustments(span, node_id);
333
334         // Resolve the type of the node with id `node_id`
335         let n_ty = self.fcx.node_ty(node_id);
336         let n_ty = self.resolve(&n_ty, &span);
337         self.write_ty_to_tables(node_id, n_ty);
338         debug!("Node {} has type {:?}", node_id, n_ty);
339
340         // Resolve any substitutions
341         self.fcx.opt_node_ty_substs(node_id, |item_substs| {
342             let item_substs = self.resolve(item_substs, &span);
343             if !item_substs.is_noop() {
344                 debug!("write_substs_to_tcx({}, {:?})", node_id, item_substs);
345                 assert!(!item_substs.substs.needs_infer());
346                 self.tables.item_substs.insert(node_id, item_substs);
347             }
348         });
349     }
350
351     fn visit_adjustments(&mut self, span: Span, node_id: ast::NodeId) {
352         let adjustments = self.fcx.tables.borrow_mut().adjustments.remove(&node_id);
353         match adjustments {
354             None => {
355                 debug!("No adjustments for node {}", node_id);
356             }
357
358             Some(adjustment) => {
359                 let resolved_adjustment = match adjustment.kind {
360                     adjustment::Adjust::NeverToAny => {
361                         adjustment::Adjust::NeverToAny
362                     }
363
364                     adjustment::Adjust::ReifyFnPointer => {
365                         adjustment::Adjust::ReifyFnPointer
366                     }
367
368                     adjustment::Adjust::MutToConstPointer => {
369                         adjustment::Adjust::MutToConstPointer
370                     }
371
372                     adjustment::Adjust::ClosureFnPointer => {
373                         adjustment::Adjust::ClosureFnPointer
374                     }
375
376                     adjustment::Adjust::UnsafeFnPointer => {
377                         adjustment::Adjust::UnsafeFnPointer
378                     }
379
380                     adjustment::Adjust::DerefRef { autoderefs, autoref, unsize } => {
381                         for autoderef in 0..autoderefs {
382                             let method_call = MethodCall::autoderef(node_id, autoderef as u32);
383                             self.visit_method_map_entry(span, method_call);
384                         }
385
386                         adjustment::Adjust::DerefRef {
387                             autoderefs: autoderefs,
388                             autoref: self.resolve(&autoref, &span),
389                             unsize: unsize,
390                         }
391                     }
392                 };
393                 let resolved_adjustment = adjustment::Adjustment {
394                     kind: resolved_adjustment,
395                     target: self.resolve(&adjustment.target, &span)
396                 };
397                 debug!("Adjustments for node {}: {:?}", node_id, resolved_adjustment);
398                 self.tables.adjustments.insert(node_id, resolved_adjustment);
399             }
400         }
401     }
402
403     fn visit_method_map_entry(&mut self,
404                               method_span: Span,
405                               method_call: MethodCall) {
406         // Resolve any method map entry
407         let new_method = match self.fcx.tables.borrow_mut().method_map.remove(&method_call) {
408             Some(method) => {
409                 debug!("writeback::resolve_method_map_entry(call={:?}, entry={:?})",
410                        method_call,
411                        method);
412                 let new_method = MethodCallee {
413                     def_id: method.def_id,
414                     ty: self.resolve(&method.ty, &method_span),
415                     substs: self.resolve(&method.substs, &method_span),
416                 };
417
418                 Some(new_method)
419             }
420             None => None
421         };
422
423         //NB(jroesch): We need to match twice to avoid a double borrow which would cause an ICE
424         if let Some(method) = new_method {
425             self.tables.method_map.insert(method_call, method);
426         }
427     }
428
429     fn visit_liberated_fn_sigs(&mut self) {
430         for (&node_id, fn_sig) in self.fcx.tables.borrow().liberated_fn_sigs.iter() {
431             let fn_sig = self.resolve(fn_sig, &node_id);
432             self.tables.liberated_fn_sigs.insert(node_id, fn_sig.clone());
433         }
434     }
435
436     fn visit_fru_field_types(&mut self) {
437         for (&node_id, ftys) in self.fcx.tables.borrow().fru_field_types.iter() {
438             let ftys = self.resolve(ftys, &node_id);
439             self.tables.fru_field_types.insert(node_id, ftys);
440         }
441     }
442
443     fn visit_type_nodes(&self) {
444         for (&id, ty) in self.fcx.ast_ty_to_ty_cache.borrow().iter() {
445             let ty = self.resolve(ty, &id);
446             self.fcx.tcx.ast_ty_to_ty_cache.borrow_mut().insert(id, ty);
447         }
448     }
449
450     fn resolve<T>(&self, x: &T, span: &Locatable) -> T::Lifted
451         where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
452     {
453         let x = x.fold_with(&mut Resolver::new(self.fcx, span, self.body));
454         if let Some(lifted) = self.tcx().lift_to_global(&x) {
455             lifted
456         } else {
457             span_bug!(span.to_span(&self.fcx.tcx),
458                       "writeback: `{:?}` missing from the global type context",
459                       x);
460         }
461     }
462 }
463
464 trait Locatable {
465     fn to_span(&self, tcx: &TyCtxt) -> Span;
466 }
467
468 impl Locatable for Span {
469     fn to_span(&self, _: &TyCtxt) -> Span { *self }
470 }
471
472 impl Locatable for ast::NodeId {
473     fn to_span(&self, tcx: &TyCtxt) -> Span { tcx.hir.span(*self) }
474 }
475
476 ///////////////////////////////////////////////////////////////////////////
477 // The Resolver. This is the type folding engine that detects
478 // unresolved types and so forth.
479
480 struct Resolver<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
481     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
482     infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
483     span: &'cx Locatable,
484     body: &'gcx hir::Body,
485 }
486
487 impl<'cx, 'gcx, 'tcx> Resolver<'cx, 'gcx, 'tcx> {
488     fn new(fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>, span: &'cx Locatable, body: &'gcx hir::Body)
489         -> Resolver<'cx, 'gcx, 'tcx>
490     {
491         Resolver {
492             tcx: fcx.tcx,
493             infcx: fcx,
494             span: span,
495             body: body,
496         }
497     }
498
499     fn report_error(&self, t: Ty<'tcx>) {
500         if !self.tcx.sess.has_errors() {
501             self.infcx.need_type_info(self.body.id(), self.span.to_span(&self.tcx), t);
502         }
503     }
504 }
505
506 impl<'cx, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for Resolver<'cx, 'gcx, 'tcx> {
507     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx> {
508         self.tcx
509     }
510
511     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
512         match self.infcx.fully_resolve(&t) {
513             Ok(t) => t,
514             Err(_) => {
515                 debug!("Resolver::fold_ty: input type `{:?}` not fully resolvable",
516                        t);
517                 self.report_error(t);
518                 self.tcx().types.err
519             }
520         }
521     }
522
523     // FIXME This should be carefully checked
524     // We could use `self.report_error` but it doesn't accept a ty::Region, right now.
525     fn fold_region(&mut self, r: &'tcx ty::Region) -> &'tcx ty::Region {
526         match self.infcx.fully_resolve(&r) {
527             Ok(r) => r,
528             Err(_) => {
529                 self.tcx.types.re_static
530             }
531         }
532     }
533 }
534
535 ///////////////////////////////////////////////////////////////////////////
536 // During type check, we store promises with the result of trait
537 // lookup rather than the actual results (because the results are not
538 // necessarily available immediately). These routines unwind the
539 // promises. It is expected that we will have already reported any
540 // errors that may be encountered, so if the promises store an error,
541 // a dummy result is returned.