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