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, DefIndex};
18 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
19 use rustc::infer::InferCtxt;
20 use rustc::ty::{self, Ty, TyCtxt};
21 use rustc::ty::adjustment::{Adjust, Adjustment};
22 use rustc::ty::fold::{TypeFoldable, TypeFolder};
23 use rustc::util::nodemap::DefIdSet;
27 use rustc_data_structures::sync::Lrc;
29 ///////////////////////////////////////////////////////////////////////////
32 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
33 pub fn resolve_type_vars_in_body(&self, body: &'gcx hir::Body) -> &'gcx ty::TypeckTables<'gcx> {
34 let item_id = self.tcx.hir.body_owner(body.id());
35 let item_def_id = self.tcx.hir.local_def_id(item_id);
37 let mut wbcx = WritebackCx::new(self, body);
38 for arg in &body.arguments {
39 wbcx.visit_node_id(arg.pat.span, arg.hir_id);
41 wbcx.visit_body(body);
42 wbcx.visit_upvar_borrow_map();
43 wbcx.visit_closures();
44 wbcx.visit_liberated_fn_sigs();
45 wbcx.visit_fru_field_types();
46 wbcx.visit_anon_types(body.value.span);
47 wbcx.visit_cast_types();
48 wbcx.visit_free_region_map();
49 wbcx.visit_user_provided_tys();
51 let used_trait_imports = mem::replace(
52 &mut self.tables.borrow_mut().used_trait_imports,
56 "used_trait_imports({:?}) = {:?}",
60 wbcx.tables.used_trait_imports = used_trait_imports;
62 wbcx.tables.tainted_by_errors = self.is_tainted_by_errors();
65 "writeback: tables for {:?} are {:#?}",
70 self.tcx.alloc_tables(wbcx.tables)
74 ///////////////////////////////////////////////////////////////////////////
75 // The Writerback context. This visitor walks the AST, checking the
76 // fn-specific tables to find references to types or regions. It
77 // resolves those regions to remove inference variables and writes the
78 // final result back into the master tables in the tcx. Here and
79 // there, it applies a few ad-hoc checks that were not convenient to
82 struct WritebackCx<'cx, 'gcx: 'cx + 'tcx, 'tcx: 'cx> {
83 fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>,
85 tables: ty::TypeckTables<'gcx>,
87 body: &'gcx hir::Body,
90 impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
92 fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>,
93 body: &'gcx hir::Body,
94 ) -> WritebackCx<'cx, 'gcx, 'tcx> {
95 let owner = fcx.tcx.hir.definitions().node_to_hir_id(body.id().node_id);
99 tables: ty::TypeckTables::empty(Some(DefId::local(owner.owner))),
104 fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
108 fn write_ty_to_tables(&mut self, hir_id: hir::HirId, ty: Ty<'gcx>) {
109 debug!("write_ty_to_tables({:?}, {:?})", hir_id, ty);
110 assert!(!ty.needs_infer() && !ty.has_skol());
111 self.tables.node_types_mut().insert(hir_id, ty);
114 // Hacky hack: During type-checking, we treat *all* operators
115 // as potentially overloaded. But then, during writeback, if
116 // we observe that something like `a+b` is (known to be)
117 // operating on scalars, we clear the overload.
118 fn fix_scalar_builtin_expr(&mut self, e: &hir::Expr) {
120 hir::ExprKind::Unary(hir::UnNeg, ref inner) |
121 hir::ExprKind::Unary(hir::UnNot, ref inner) => {
122 let inner_ty = self.fcx.node_ty(inner.hir_id);
123 let inner_ty = self.fcx.resolve_type_vars_if_possible(&inner_ty);
125 if inner_ty.is_scalar() {
126 let mut tables = self.fcx.tables.borrow_mut();
127 tables.type_dependent_defs_mut().remove(e.hir_id);
128 tables.node_substs_mut().remove(e.hir_id);
131 hir::ExprKind::Binary(ref op, ref lhs, ref rhs)
132 | hir::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
133 let lhs_ty = self.fcx.node_ty(lhs.hir_id);
134 let lhs_ty = self.fcx.resolve_type_vars_if_possible(&lhs_ty);
136 let rhs_ty = self.fcx.node_ty(rhs.hir_id);
137 let rhs_ty = self.fcx.resolve_type_vars_if_possible(&rhs_ty);
139 if lhs_ty.is_scalar() && rhs_ty.is_scalar() {
140 let mut tables = self.fcx.tables.borrow_mut();
141 tables.type_dependent_defs_mut().remove(e.hir_id);
142 tables.node_substs_mut().remove(e.hir_id);
145 hir::ExprKind::Binary(..) => {
146 if !op.node.is_by_value() {
147 let mut adjustments = tables.adjustments_mut();
148 adjustments.get_mut(lhs.hir_id).map(|a| a.pop());
149 adjustments.get_mut(rhs.hir_id).map(|a| a.pop());
152 hir::ExprKind::AssignOp(..) => {
166 // Similar to operators, indexing is always assumed to be overloaded
167 // Here, correct cases where an indexing expression can be simplified
168 // to use builtin indexing because the index type is known to be
170 fn fix_index_builtin_expr(&mut self, e: &hir::Expr) {
171 if let hir::ExprKind::Index(ref base, ref index) = e.node {
172 let mut tables = self.fcx.tables.borrow_mut();
174 match tables.expr_ty_adjusted(&base).sty {
175 // All valid indexing looks like this
176 ty::TyRef(_, base_ty, _) => {
177 let index_ty = tables.expr_ty_adjusted(&index);
178 let index_ty = self.fcx.resolve_type_vars_if_possible(&index_ty);
180 if base_ty.builtin_index().is_some()
181 && index_ty == self.fcx.tcx.types.usize {
182 // Remove the method call record
183 tables.type_dependent_defs_mut().remove(e.hir_id);
184 tables.node_substs_mut().remove(e.hir_id);
186 tables.adjustments_mut().get_mut(base.hir_id).map(|a| {
187 // Discard the need for a mutable borrow
189 // Extra adjustment made when indexing causes a drop
190 // of size information - we need to get rid of it
191 // Since this is "after" the other adjustment to be
192 // discarded, we do an extra `pop()`
193 Some(Adjustment { kind: Adjust::Unsize, .. }) => {
194 // So the borrow discard actually happens here
202 // Might encounter non-valid indexes at this point, so there
203 // has to be a fall-through
211 ///////////////////////////////////////////////////////////////////////////
212 // Impl of Visitor for Resolver
214 // This is the master code which walks the AST. It delegates most of
215 // the heavy lifting to the generic visit and resolve functions
216 // below. In general, a function is made into a `visitor` if it must
217 // traffic in node-ids or update tables in the type context etc.
219 impl<'cx, 'gcx, 'tcx> Visitor<'gcx> for WritebackCx<'cx, 'gcx, 'tcx> {
220 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
221 NestedVisitorMap::None
224 fn visit_expr(&mut self, e: &'gcx hir::Expr) {
225 self.fix_scalar_builtin_expr(e);
226 self.fix_index_builtin_expr(e);
228 self.visit_node_id(e.span, e.hir_id);
231 hir::ExprKind::Closure(_, _, body, _, _) => {
232 let body = self.fcx.tcx.hir.body(body);
233 for arg in &body.arguments {
234 self.visit_node_id(e.span, arg.hir_id);
237 self.visit_body(body);
239 hir::ExprKind::Struct(_, ref fields, _) => {
240 for field in fields {
241 self.visit_field_id(field.id);
244 hir::ExprKind::Field(..) => {
245 self.visit_field_id(e.id);
250 intravisit::walk_expr(self, e);
253 fn visit_block(&mut self, b: &'gcx hir::Block) {
254 self.visit_node_id(b.span, b.hir_id);
255 intravisit::walk_block(self, b);
258 fn visit_pat(&mut self, p: &'gcx hir::Pat) {
260 hir::PatKind::Binding(..) => {
261 if let Some(&bm) = self.fcx.tables.borrow().pat_binding_modes().get(p.hir_id) {
262 self.tables.pat_binding_modes_mut().insert(p.hir_id, bm);
264 self.tcx().sess.delay_span_bug(p.span, "missing binding mode");
267 hir::PatKind::Struct(_, ref fields, _) => {
268 for field in fields {
269 self.visit_field_id(field.node.id);
275 self.visit_pat_adjustments(p.span, p.hir_id);
277 self.visit_node_id(p.span, p.hir_id);
278 intravisit::walk_pat(self, p);
281 fn visit_local(&mut self, l: &'gcx hir::Local) {
282 intravisit::walk_local(self, l);
283 let var_ty = self.fcx.local_ty(l.span, l.id);
284 let var_ty = self.resolve(&var_ty, &l.span);
285 self.write_ty_to_tables(l.hir_id, var_ty);
288 fn visit_ty(&mut self, hir_ty: &'gcx hir::Ty) {
289 intravisit::walk_ty(self, hir_ty);
290 let ty = self.fcx.node_ty(hir_ty.hir_id);
291 let ty = self.resolve(&ty, &hir_ty.span);
292 self.write_ty_to_tables(hir_ty.hir_id, ty);
296 impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
297 fn visit_upvar_borrow_map(&mut self) {
298 for (upvar_id, upvar_capture) in self.fcx.tables.borrow().upvar_capture_map.iter() {
299 let new_upvar_capture = match *upvar_capture {
300 ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue,
301 ty::UpvarCapture::ByRef(ref upvar_borrow) => {
302 let r = upvar_borrow.region;
303 let r = self.resolve(&r, &upvar_id.var_id);
304 ty::UpvarCapture::ByRef(ty::UpvarBorrow {
305 kind: upvar_borrow.kind,
311 "Upvar capture for {:?} resolved to {:?}",
317 .insert(*upvar_id, new_upvar_capture);
321 fn visit_closures(&mut self) {
322 let fcx_tables = self.fcx.tables.borrow();
323 debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
324 let common_local_id_root = fcx_tables.local_id_root.unwrap();
326 for (&id, &origin) in fcx_tables.closure_kind_origins().iter() {
327 let hir_id = hir::HirId {
328 owner: common_local_id_root.index,
332 .closure_kind_origins_mut()
333 .insert(hir_id, origin);
337 fn visit_cast_types(&mut self) {
338 let fcx_tables = self.fcx.tables.borrow();
339 let fcx_cast_kinds = fcx_tables.cast_kinds();
340 debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
341 let mut self_cast_kinds = self.tables.cast_kinds_mut();
342 let common_local_id_root = fcx_tables.local_id_root.unwrap();
344 for (&local_id, &cast_kind) in fcx_cast_kinds.iter() {
345 let hir_id = hir::HirId {
346 owner: common_local_id_root.index,
349 self_cast_kinds.insert(hir_id, cast_kind);
353 fn visit_free_region_map(&mut self) {
354 let free_region_map = self.tcx()
355 .lift_to_global(&self.fcx.tables.borrow().free_region_map);
356 let free_region_map = free_region_map.expect("all regions in free-region-map are global");
357 self.tables.free_region_map = free_region_map;
360 fn visit_user_provided_tys(&mut self) {
361 let fcx_tables = self.fcx.tables.borrow();
362 debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
363 let common_local_id_root = fcx_tables.local_id_root.unwrap();
365 for (&local_id, c_ty) in fcx_tables.user_provided_tys().iter() {
366 let hir_id = hir::HirId {
367 owner: common_local_id_root.index,
371 let c_ty = if let Some(c_ty) = self.tcx().lift_to_global(c_ty) {
375 hir_id.to_span(&self.fcx.tcx),
376 "writeback: `{:?}` missing from the global type context",
382 .user_provided_tys_mut()
383 .insert(hir_id, c_ty.clone());
387 fn visit_anon_types(&mut self, span: Span) {
388 for (&def_id, anon_defn) in self.fcx.anon_types.borrow().iter() {
389 let node_id = self.tcx().hir.as_local_node_id(def_id).unwrap();
390 let instantiated_ty = self.resolve(&anon_defn.concrete_ty, &node_id);
391 let definition_ty = self.fcx.infer_anon_definition_from_instantiation(
396 let old = self.tables.concrete_existential_types.insert(def_id, definition_ty);
397 if let Some(old) = old {
398 if old != definition_ty {
401 "visit_anon_types tried to write \
402 different types for the same existential type: {:?}, {:?}, {:?}",
412 fn visit_field_id(&mut self, node_id: ast::NodeId) {
413 let hir_id = self.tcx().hir.node_to_hir_id(node_id);
414 if let Some(index) = self.fcx.tables.borrow_mut().field_indices_mut().remove(hir_id) {
415 self.tables.field_indices_mut().insert(hir_id, index);
419 fn visit_node_id(&mut self, span: Span, hir_id: hir::HirId) {
420 // Export associated path extensions and method resultions.
421 if let Some(def) = self.fcx
424 .type_dependent_defs_mut()
427 self.tables.type_dependent_defs_mut().insert(hir_id, def);
430 // Resolve any borrowings for the node with id `node_id`
431 self.visit_adjustments(span, hir_id);
433 // Resolve the type of the node with id `node_id`
434 let n_ty = self.fcx.node_ty(hir_id);
435 let n_ty = self.resolve(&n_ty, &span);
436 self.write_ty_to_tables(hir_id, n_ty);
437 debug!("Node {:?} has type {:?}", hir_id, n_ty);
439 // Resolve any substitutions
440 if let Some(substs) = self.fcx.tables.borrow().node_substs_opt(hir_id) {
441 let substs = self.resolve(&substs, &span);
442 debug!("write_substs_to_tcx({:?}, {:?})", hir_id, substs);
443 assert!(!substs.needs_infer() && !substs.has_skol());
444 self.tables.node_substs_mut().insert(hir_id, substs);
448 fn visit_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
449 let adjustment = self.fcx
456 debug!("No adjustments for node {:?}", hir_id);
459 Some(adjustment) => {
460 let resolved_adjustment = self.resolve(&adjustment, &span);
462 "Adjustments for node {:?}: {:?}",
468 .insert(hir_id, resolved_adjustment);
473 fn visit_pat_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
474 let adjustment = self.fcx
477 .pat_adjustments_mut()
481 debug!("No pat_adjustments for node {:?}", hir_id);
484 Some(adjustment) => {
485 let resolved_adjustment = self.resolve(&adjustment, &span);
487 "pat_adjustments for node {:?}: {:?}",
492 .pat_adjustments_mut()
493 .insert(hir_id, resolved_adjustment);
498 fn visit_liberated_fn_sigs(&mut self) {
499 let fcx_tables = self.fcx.tables.borrow();
500 debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
501 let common_local_id_root = fcx_tables.local_id_root.unwrap();
503 for (&local_id, fn_sig) in fcx_tables.liberated_fn_sigs().iter() {
504 let hir_id = hir::HirId {
505 owner: common_local_id_root.index,
508 let fn_sig = self.resolve(fn_sig, &hir_id);
510 .liberated_fn_sigs_mut()
511 .insert(hir_id, fn_sig.clone());
515 fn visit_fru_field_types(&mut self) {
516 let fcx_tables = self.fcx.tables.borrow();
517 debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
518 let common_local_id_root = fcx_tables.local_id_root.unwrap();
520 for (&local_id, ftys) in fcx_tables.fru_field_types().iter() {
521 let hir_id = hir::HirId {
522 owner: common_local_id_root.index,
525 let ftys = self.resolve(ftys, &hir_id);
526 self.tables.fru_field_types_mut().insert(hir_id, ftys);
530 fn resolve<T>(&self, x: &T, span: &dyn Locatable) -> T::Lifted
532 T: TypeFoldable<'tcx> + ty::Lift<'gcx>,
534 let x = x.fold_with(&mut Resolver::new(self.fcx, span, self.body));
535 if let Some(lifted) = self.tcx().lift_to_global(&x) {
539 span.to_span(&self.fcx.tcx),
540 "writeback: `{:?}` missing from the global type context",
548 fn to_span(&self, tcx: &TyCtxt) -> Span;
551 impl Locatable for Span {
552 fn to_span(&self, _: &TyCtxt) -> Span {
557 impl Locatable for ast::NodeId {
558 fn to_span(&self, tcx: &TyCtxt) -> Span {
563 impl Locatable for DefIndex {
564 fn to_span(&self, tcx: &TyCtxt) -> Span {
565 let node_id = tcx.hir.def_index_to_node_id(*self);
566 tcx.hir.span(node_id)
570 impl Locatable for hir::HirId {
571 fn to_span(&self, tcx: &TyCtxt) -> Span {
572 let node_id = tcx.hir.hir_to_node_id(*self);
573 tcx.hir.span(node_id)
577 ///////////////////////////////////////////////////////////////////////////
578 // The Resolver. This is the type folding engine that detects
579 // unresolved types and so forth.
581 struct Resolver<'cx, 'gcx: 'cx + 'tcx, 'tcx: 'cx> {
582 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
583 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
584 span: &'cx dyn Locatable,
585 body: &'gcx hir::Body,
588 impl<'cx, 'gcx, 'tcx> Resolver<'cx, 'gcx, 'tcx> {
590 fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>,
591 span: &'cx dyn Locatable,
592 body: &'gcx hir::Body,
593 ) -> Resolver<'cx, 'gcx, 'tcx> {
602 fn report_error(&self, t: Ty<'tcx>) {
603 if !self.tcx.sess.has_errors() {
605 .need_type_info_err(Some(self.body.id()), self.span.to_span(&self.tcx), t).emit();
610 impl<'cx, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for Resolver<'cx, 'gcx, 'tcx> {
611 fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx> {
615 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
616 match self.infcx.fully_resolve(&t) {
620 "Resolver::fold_ty: input type `{:?}` not fully resolvable",
623 self.report_error(t);
629 // FIXME This should be carefully checked
630 // We could use `self.report_error` but it doesn't accept a ty::Region, right now.
631 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
632 match self.infcx.fully_resolve(&r) {
634 Err(_) => self.tcx.types.re_static,
639 ///////////////////////////////////////////////////////////////////////////
640 // During type check, we store promises with the result of trait
641 // lookup rather than the actual results (because the results are not
642 // necessarily available immediately). These routines unwind the
643 // promises. It is expected that we will have already reported any
644 // errors that may be encountered, so if the promises store an error,
645 // a dummy result is returned.