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.
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.
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
17 use rustc::hir::def_id::DefId;
18 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
19 use rustc::infer::{InferCtxt};
20 use rustc::ty::{self, Ty, TyCtxt};
21 use rustc::ty::fold::{TypeFolder,TypeFoldable};
22 use rustc::util::nodemap::DefIdSet;
27 ///////////////////////////////////////////////////////////////////////////
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);
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);
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();
49 let used_trait_imports = mem::replace(&mut self.tables.borrow_mut().used_trait_imports,
51 debug!("used_trait_imports({:?}) = {:?}", item_def_id, used_trait_imports);
52 wbcx.tables.used_trait_imports = used_trait_imports;
54 wbcx.tables.tainted_by_errors = self.is_tainted_by_errors();
56 self.tcx.alloc_tables(wbcx.tables)
60 ///////////////////////////////////////////////////////////////////////////
61 // The Writerback context. This visitor walks the AST, checking the
62 // fn-specific tables to find references to types or regions. It
63 // resolves those regions to remove inference variables and writes the
64 // final result back into the master tables in the tcx. Here and
65 // there, it applies a few ad-hoc checks that were not convenient to
68 struct WritebackCx<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
69 fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>,
71 tables: ty::TypeckTables<'gcx>,
73 body: &'gcx hir::Body,
76 impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
77 fn new(fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>, body: &'gcx hir::Body)
78 -> WritebackCx<'cx, 'gcx, 'tcx>
80 let owner = fcx.tcx.hir.definitions().node_to_hir_id(body.id().node_id);
84 tables: ty::TypeckTables::empty(DefId::local(owner.owner)),
89 fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
93 fn write_ty_to_tables(&mut self, hir_id: hir::HirId, ty: Ty<'gcx>) {
94 debug!("write_ty_to_tables({:?}, {:?})", hir_id, ty);
95 assert!(!ty.needs_infer());
96 self.tables.validate_hir_id(hir_id);
97 self.tables.node_types.insert(hir_id.local_id, ty);
100 // Hacky hack: During type-checking, we treat *all* operators
101 // as potentially overloaded. But then, during writeback, if
102 // we observe that something like `a+b` is (known to be)
103 // operating on scalars, we clear the overload.
104 fn fix_scalar_builtin_expr(&mut self, e: &hir::Expr) {
106 hir::ExprUnary(hir::UnNeg, ref inner) |
107 hir::ExprUnary(hir::UnNot, ref inner) => {
108 let inner_ty = self.fcx.node_ty(inner.hir_id);
109 let inner_ty = self.fcx.resolve_type_vars_if_possible(&inner_ty);
111 if inner_ty.is_scalar() {
112 let mut tables = self.fcx.tables.borrow_mut();
113 tables.validate_hir_id(e.hir_id);
114 tables.type_dependent_defs.remove(&e.hir_id.local_id);
115 tables.node_substs.remove(&e.hir_id.local_id);
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);
123 let rhs_ty = self.fcx.node_ty(rhs.hir_id);
124 let rhs_ty = self.fcx.resolve_type_vars_if_possible(&rhs_ty);
126 if lhs_ty.is_scalar() && rhs_ty.is_scalar() {
127 let mut tables = self.fcx.tables.borrow_mut();
128 tables.validate_hir_id(e.hir_id);
129 tables.type_dependent_defs.remove(&e.hir_id.local_id);
130 tables.node_substs.remove(&e.hir_id.local_id);
133 hir::ExprBinary(..) => {
134 if !op.node.is_by_value() {
135 tables.adjustments.get_mut(&lhs.hir_id.local_id).map(|a| a.pop());
136 tables.adjustments.get_mut(&rhs.hir_id.local_id).map(|a| a.pop());
139 hir::ExprAssignOp(..) => {
140 tables.adjustments.get_mut(&lhs.hir_id.local_id).map(|a| a.pop());
151 ///////////////////////////////////////////////////////////////////////////
152 // Impl of Visitor for Resolver
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.
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
164 fn visit_expr(&mut self, e: &'gcx hir::Expr) {
165 self.fix_scalar_builtin_expr(e);
167 self.visit_node_id(e.span, e.hir_id);
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);
175 self.visit_body(body);
178 intravisit::walk_expr(self, e);
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);
186 fn visit_pat(&mut self, p: &'gcx hir::Pat) {
188 hir::PatKind::Binding(..) => {
190 let fcx_tables = self.fcx.tables.borrow();
191 fcx_tables.validate_hir_id(p.hir_id);
192 *fcx_tables.pat_binding_modes.get(&p.hir_id.local_id)
193 .expect("missing binding mode")
195 self.tables.validate_hir_id(p.hir_id);
196 self.tables.pat_binding_modes.insert(p.hir_id.local_id, bm);
201 self.visit_node_id(p.span, p.hir_id);
202 intravisit::walk_pat(self, p);
205 fn visit_local(&mut self, l: &'gcx hir::Local) {
206 intravisit::walk_local(self, l);
207 let var_ty = self.fcx.local_ty(l.span, l.id);
208 let var_ty = self.resolve(&var_ty, &l.span);
209 self.write_ty_to_tables(l.hir_id, var_ty);
213 impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
214 fn visit_upvar_borrow_map(&mut self) {
215 for (upvar_id, upvar_capture) in self.fcx.tables.borrow().upvar_capture_map.iter() {
216 let new_upvar_capture = match *upvar_capture {
217 ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue,
218 ty::UpvarCapture::ByRef(ref upvar_borrow) => {
219 let r = upvar_borrow.region;
220 let r = self.resolve(&r, &upvar_id.var_id);
221 ty::UpvarCapture::ByRef(
222 ty::UpvarBorrow { kind: upvar_borrow.kind, region: r })
225 debug!("Upvar capture for {:?} resolved to {:?}",
228 self.tables.upvar_capture_map.insert(*upvar_id, new_upvar_capture);
232 fn visit_closures(&mut self) {
233 let fcx_tables = self.fcx.tables.borrow();
234 debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
236 for (&id, closure_ty) in fcx_tables.closure_tys.iter() {
237 let hir_id = hir::HirId {
238 owner: fcx_tables.local_id_root.index,
241 let closure_ty = self.resolve(closure_ty, &hir_id);
242 self.tables.closure_tys.insert(id, closure_ty);
245 for (&id, &closure_kind) in fcx_tables.closure_kinds.iter() {
246 self.tables.closure_kinds.insert(id, closure_kind);
250 fn visit_cast_types(&mut self) {
251 self.tables.cast_kinds.extend(
252 self.fcx.tables.borrow().cast_kinds.iter().map(|(&key, &value)| (key, value)));
255 fn visit_free_region_map(&mut self) {
256 let free_region_map = self.tcx().lift_to_global(&self.fcx.tables.borrow().free_region_map);
257 let free_region_map = free_region_map.expect("all regions in free-region-map are global");
258 self.tables.free_region_map = free_region_map;
261 fn visit_anon_types(&mut self) {
262 let gcx = self.tcx().global_tcx();
263 for (&node_id, &concrete_ty) in self.fcx.anon_types.borrow().iter() {
264 let inside_ty = self.resolve(&concrete_ty, &node_id);
266 // Convert the type from the function into a type valid outside
267 // the function, by replacing invalid regions with 'static,
268 // after producing an error for each of them.
269 let outside_ty = gcx.fold_regions(&inside_ty, &mut false, |r, _| {
271 // 'static and early-bound regions are valid.
273 ty::ReEarlyBound(_) |
277 ty::ReLateBound(..) |
279 ty::ReSkolemized(..) => {
280 let span = node_id.to_span(&self.fcx.tcx);
281 span_err!(self.tcx().sess, span, E0564,
282 "only named lifetimes are allowed in `impl Trait`, \
283 but `{}` was found in the type `{}`", r, inside_ty);
289 let span = node_id.to_span(&self.fcx.tcx);
290 span_bug!(span, "invalid region in impl Trait: {:?}", r);
295 let hir_id = self.tcx().hir.node_to_hir_id(node_id);
296 self.tables.validate_hir_id(hir_id);
297 self.tables.node_types.insert(hir_id.local_id, outside_ty);
301 fn visit_node_id(&mut self, span: Span, hir_id: hir::HirId) {
303 let mut fcx_tables = self.fcx.tables.borrow_mut();
304 fcx_tables.validate_hir_id(hir_id);
305 // Export associated path extensions and method resultions.
306 if let Some(def) = fcx_tables.type_dependent_defs.remove(&hir_id.local_id) {
307 self.tables.validate_hir_id(hir_id);
308 self.tables.type_dependent_defs.insert(hir_id.local_id, def);
312 // Resolve any borrowings for the node with id `node_id`
313 self.visit_adjustments(span, hir_id);
315 // Resolve the type of the node with id `node_id`
316 let n_ty = self.fcx.node_ty(hir_id);
317 let n_ty = self.resolve(&n_ty, &span);
318 self.write_ty_to_tables(hir_id, n_ty);
319 debug!("Node {:?} has type {:?}", hir_id, n_ty);
321 // Resolve any substitutions
322 if let Some(&substs) = self.fcx.tables.borrow().node_substs.get(&hir_id.local_id) {
323 let substs = self.resolve(&substs, &span);
324 debug!("write_substs_to_tcx({:?}, {:?})", hir_id, substs);
325 assert!(!substs.needs_infer());
326 self.tables.node_substs.insert(hir_id.local_id, substs);
330 fn visit_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
332 let mut fcx_tables = self.fcx.tables.borrow_mut();
333 fcx_tables.validate_hir_id(hir_id);
334 fcx_tables.adjustments.remove(&hir_id.local_id)
338 debug!("No adjustments for node {:?}", hir_id);
341 Some(adjustment) => {
342 let resolved_adjustment = self.resolve(&adjustment, &span);
343 debug!("Adjustments for node {:?}: {:?}", hir_id, resolved_adjustment);
344 self.tables.validate_hir_id(hir_id);
345 self.tables.adjustments.insert(hir_id.local_id, resolved_adjustment);
350 fn visit_liberated_fn_sigs(&mut self) {
351 let fcx_tables = self.fcx.tables.borrow();
352 debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
354 for (&local_id, fn_sig) in fcx_tables.liberated_fn_sigs.iter() {
355 let hir_id = hir::HirId {
356 owner: fcx_tables.local_id_root.index,
359 let fn_sig = self.resolve(fn_sig, &hir_id);
360 self.tables.liberated_fn_sigs.insert(local_id, fn_sig.clone());
364 fn visit_fru_field_types(&mut self) {
365 let fcx_tables = self.fcx.tables.borrow();
366 debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
368 for (&local_id, ftys) in fcx_tables.fru_field_types.iter() {
369 let hir_id = hir::HirId {
370 owner: fcx_tables.local_id_root.index,
373 let ftys = self.resolve(ftys, &hir_id);
374 self.tables.fru_field_types.insert(local_id, ftys);
378 fn resolve<T>(&self, x: &T, span: &Locatable) -> T::Lifted
379 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
381 let x = x.fold_with(&mut Resolver::new(self.fcx, span, self.body));
382 if let Some(lifted) = self.tcx().lift_to_global(&x) {
385 span_bug!(span.to_span(&self.fcx.tcx),
386 "writeback: `{:?}` missing from the global type context",
393 fn to_span(&self, tcx: &TyCtxt) -> Span;
396 impl Locatable for Span {
397 fn to_span(&self, _: &TyCtxt) -> Span { *self }
400 impl Locatable for ast::NodeId {
401 fn to_span(&self, tcx: &TyCtxt) -> Span { tcx.hir.span(*self) }
404 impl Locatable for hir::HirId {
405 fn to_span(&self, tcx: &TyCtxt) -> Span {
406 let node_id = tcx.hir.definitions().find_node_for_hir_id(*self);
407 tcx.hir.span(node_id)
411 ///////////////////////////////////////////////////////////////////////////
412 // The Resolver. This is the type folding engine that detects
413 // unresolved types and so forth.
415 struct Resolver<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
416 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
417 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
418 span: &'cx Locatable,
419 body: &'gcx hir::Body,
422 impl<'cx, 'gcx, 'tcx> Resolver<'cx, 'gcx, 'tcx> {
423 fn new(fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>, span: &'cx Locatable, body: &'gcx hir::Body)
424 -> Resolver<'cx, 'gcx, 'tcx>
434 fn report_error(&self, t: Ty<'tcx>) {
435 if !self.tcx.sess.has_errors() {
436 self.infcx.need_type_info(Some(self.body.id()), self.span.to_span(&self.tcx), t);
441 impl<'cx, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for Resolver<'cx, 'gcx, 'tcx> {
442 fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx> {
446 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
447 match self.infcx.fully_resolve(&t) {
450 debug!("Resolver::fold_ty: input type `{:?}` not fully resolvable",
452 self.report_error(t);
458 // FIXME This should be carefully checked
459 // We could use `self.report_error` but it doesn't accept a ty::Region, right now.
460 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
461 match self.infcx.fully_resolve(&r) {
464 self.tcx.types.re_static
470 ///////////////////////////////////////////////////////////////////////////
471 // During type check, we store promises with the result of trait
472 // lookup rather than the actual results (because the results are not
473 // necessarily available immediately). These routines unwind the
474 // promises. It is expected that we will have already reported any
475 // errors that may be encountered, so if the promises store an error,
476 // a dummy result is returned.