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::intravisit::{self, Visitor, NestedVisitorMap};
18 use rustc::infer::{InferCtxt};
19 use rustc::ty::{self, Ty, TyCtxt, MethodCallee};
20 use rustc::ty::adjustment;
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.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();
48 wbcx.visit_free_region_map();
50 let used_trait_imports = mem::replace(&mut self.tables.borrow_mut().used_trait_imports,
52 debug!("used_trait_imports({:?}) = {:?}", item_def_id, used_trait_imports);
53 wbcx.tables.used_trait_imports = used_trait_imports;
55 wbcx.tables.tainted_by_errors = self.is_tainted_by_errors();
57 self.tcx.alloc_tables(wbcx.tables)
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
69 struct WritebackCx<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
70 fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>,
72 tables: ty::TypeckTables<'gcx>,
74 body: &'gcx hir::Body,
77 impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
78 fn new(fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>, body: &'gcx hir::Body)
79 -> WritebackCx<'cx, 'gcx, 'tcx> {
82 tables: ty::TypeckTables::empty(),
87 fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
91 fn write_ty_to_tables(&mut self, node_id: ast::NodeId, ty: Ty<'gcx>) {
92 debug!("write_ty_to_tables({}, {:?})", node_id, ty);
93 assert!(!ty.needs_infer());
94 self.tables.node_types.insert(node_id, ty);
97 // Hacky hack: During type-checking, we treat *all* operators
98 // as potentially overloaded. But then, during writeback, if
99 // we observe that something like `a+b` is (known to be)
100 // operating on scalars, we clear the overload.
101 fn fix_scalar_builtin_expr(&mut self, e: &hir::Expr) {
103 hir::ExprUnary(hir::UnNeg, ref inner) |
104 hir::ExprUnary(hir::UnNot, ref inner) => {
105 let inner_ty = self.fcx.node_ty(inner.id);
106 let inner_ty = self.fcx.resolve_type_vars_if_possible(&inner_ty);
108 if inner_ty.is_scalar() {
109 self.fcx.tables.borrow_mut().method_map.remove(&e.id);
112 hir::ExprBinary(ref op, ref lhs, ref rhs) |
113 hir::ExprAssignOp(ref op, ref lhs, ref rhs) => {
114 let lhs_ty = self.fcx.node_ty(lhs.id);
115 let lhs_ty = self.fcx.resolve_type_vars_if_possible(&lhs_ty);
117 let rhs_ty = self.fcx.node_ty(rhs.id);
118 let rhs_ty = self.fcx.resolve_type_vars_if_possible(&rhs_ty);
120 if lhs_ty.is_scalar() && rhs_ty.is_scalar() {
121 self.fcx.tables.borrow_mut().method_map.remove(&e.id);
123 // weird but true: the by-ref binops put an
124 // adjustment on the lhs but not the rhs; the
125 // adjustment for rhs is kind of baked into the
128 hir::ExprBinary(..) => {
129 if !op.node.is_by_value() {
130 self.fcx.tables.borrow_mut().adjustments.remove(&lhs.id);
133 hir::ExprAssignOp(..) => {
134 self.fcx.tables.borrow_mut().adjustments.remove(&lhs.id);
145 ///////////////////////////////////////////////////////////////////////////
146 // Impl of Visitor for Resolver
148 // This is the master code which walks the AST. It delegates most of
149 // the heavy lifting to the generic visit and resolve functions
150 // below. In general, a function is made into a `visitor` if it must
151 // traffic in node-ids or update tables in the type context etc.
153 impl<'cx, 'gcx, 'tcx> Visitor<'gcx> for WritebackCx<'cx, 'gcx, 'tcx> {
154 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
155 NestedVisitorMap::None
158 fn visit_stmt(&mut self, s: &'gcx hir::Stmt) {
159 self.visit_node_id(s.span, s.node.id());
160 intravisit::walk_stmt(self, s);
163 fn visit_expr(&mut self, e: &'gcx hir::Expr) {
164 self.fix_scalar_builtin_expr(e);
166 self.visit_node_id(e.span, e.id);
167 self.visit_method_map_entry(e.span, e.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.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.id);
183 intravisit::walk_block(self, b);
186 fn visit_pat(&mut self, p: &'gcx hir::Pat) {
187 self.visit_node_id(p.span, p.id);
188 intravisit::walk_pat(self, p);
191 fn visit_local(&mut self, l: &'gcx hir::Local) {
192 intravisit::walk_local(self, l);
193 let var_ty = self.fcx.local_ty(l.span, l.id);
194 let var_ty = self.resolve(&var_ty, &l.span);
195 self.write_ty_to_tables(l.id, var_ty);
199 impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
200 fn visit_upvar_borrow_map(&mut self) {
201 for (upvar_id, upvar_capture) in self.fcx.tables.borrow().upvar_capture_map.iter() {
202 let new_upvar_capture = match *upvar_capture {
203 ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue,
204 ty::UpvarCapture::ByRef(ref upvar_borrow) => {
205 let r = upvar_borrow.region;
206 let r = self.resolve(&r, &upvar_id.var_id);
207 ty::UpvarCapture::ByRef(
208 ty::UpvarBorrow { kind: upvar_borrow.kind, region: r })
211 debug!("Upvar capture for {:?} resolved to {:?}",
214 self.tables.upvar_capture_map.insert(*upvar_id, new_upvar_capture);
218 fn visit_closures(&mut self) {
219 for (&id, closure_ty) in self.fcx.tables.borrow().closure_tys.iter() {
220 let closure_ty = self.resolve(closure_ty, &id);
221 self.tables.closure_tys.insert(id, closure_ty);
224 for (&id, &closure_kind) in self.fcx.tables.borrow().closure_kinds.iter() {
225 self.tables.closure_kinds.insert(id, closure_kind);
229 fn visit_cast_types(&mut self) {
230 self.tables.cast_kinds.extend(
231 self.fcx.tables.borrow().cast_kinds.iter().map(|(&key, &value)| (key, value)));
234 fn visit_lints(&mut self) {
235 self.fcx.tables.borrow_mut().lints.transfer(&mut self.tables.lints);
238 fn visit_free_region_map(&mut self) {
239 let free_region_map = self.tcx().lift_to_global(&self.fcx.tables.borrow().free_region_map);
240 let free_region_map = free_region_map.expect("all regions in free-region-map are global");
241 self.tables.free_region_map = free_region_map;
244 fn visit_anon_types(&mut self) {
245 let gcx = self.tcx().global_tcx();
246 for (&node_id, &concrete_ty) in self.fcx.anon_types.borrow().iter() {
247 let inside_ty = self.resolve(&concrete_ty, &node_id);
249 // Convert the type from the function into a type valid outside
250 // the function, by replacing invalid regions with 'static,
251 // after producing an error for each of them.
252 let outside_ty = gcx.fold_regions(&inside_ty, &mut false, |r, _| {
254 // 'static and early-bound regions are valid.
256 ty::ReEarlyBound(_) |
260 ty::ReLateBound(..) |
262 ty::ReSkolemized(..) => {
263 let span = node_id.to_span(&self.fcx.tcx);
264 span_err!(self.tcx().sess, span, E0564,
265 "only named lifetimes are allowed in `impl Trait`, \
266 but `{}` was found in the type `{}`", r, inside_ty);
272 let span = node_id.to_span(&self.fcx.tcx);
273 span_bug!(span, "invalid region in impl Trait: {:?}", r);
278 self.tables.node_types.insert(node_id, outside_ty);
282 fn visit_node_id(&mut self, span: Span, node_id: ast::NodeId) {
283 // Export associated path extensions.
284 if let Some(def) = self.fcx.tables.borrow_mut().type_relative_path_defs.remove(&node_id) {
285 self.tables.type_relative_path_defs.insert(node_id, def);
288 // Resolve any borrowings for the node with id `node_id`
289 self.visit_adjustments(span, node_id);
291 // Resolve the type of the node with id `node_id`
292 let n_ty = self.fcx.node_ty(node_id);
293 let n_ty = self.resolve(&n_ty, &span);
294 self.write_ty_to_tables(node_id, n_ty);
295 debug!("Node {} has type {:?}", node_id, n_ty);
297 // Resolve any substitutions
298 if let Some(&substs) = self.fcx.tables.borrow().node_substs.get(&node_id) {
299 let substs = self.resolve(&substs, &span);
300 debug!("write_substs_to_tcx({}, {:?})", node_id, substs);
301 assert!(!substs.needs_infer());
302 self.tables.node_substs.insert(node_id, substs);
306 fn visit_adjustments(&mut self, span: Span, node_id: ast::NodeId) {
307 let adjustments = self.fcx.tables.borrow_mut().adjustments.remove(&node_id);
310 debug!("No adjustments for node {}", node_id);
313 Some(adjustment) => {
314 let resolved_adjustment = match adjustment.kind {
315 adjustment::Adjust::NeverToAny => {
316 adjustment::Adjust::NeverToAny
319 adjustment::Adjust::ReifyFnPointer => {
320 adjustment::Adjust::ReifyFnPointer
323 adjustment::Adjust::MutToConstPointer => {
324 adjustment::Adjust::MutToConstPointer
327 adjustment::Adjust::ClosureFnPointer => {
328 adjustment::Adjust::ClosureFnPointer
331 adjustment::Adjust::UnsafeFnPointer => {
332 adjustment::Adjust::UnsafeFnPointer
335 adjustment::Adjust::DerefRef { autoderefs, autoref, unsize } => {
336 adjustment::Adjust::DerefRef {
337 autoderefs: autoderefs.iter().map(|overloaded| {
338 overloaded.map(|method| {
340 def_id: method.def_id,
341 substs: self.resolve(&method.substs, &span),
342 sig: self.resolve(&method.sig, &span),
346 autoref: self.resolve(&autoref, &span),
351 let resolved_adjustment = adjustment::Adjustment {
352 kind: resolved_adjustment,
353 target: self.resolve(&adjustment.target, &span)
355 debug!("Adjustments for node {}: {:?}", node_id, resolved_adjustment);
356 self.tables.adjustments.insert(node_id, resolved_adjustment);
361 fn visit_method_map_entry(&mut self,
363 node_id: ast::NodeId) {
364 // Resolve any method map entry
365 let new_method = match self.fcx.tables.borrow_mut().method_map.remove(&node_id) {
368 def_id: method.def_id,
369 substs: self.resolve(&method.substs, &method_span),
370 sig: self.resolve(&method.sig, &method_span),
376 //NB(jroesch): We need to match twice to avoid a double borrow which would cause an ICE
377 if let Some(method) = new_method {
378 self.tables.method_map.insert(node_id, method);
382 fn visit_liberated_fn_sigs(&mut self) {
383 for (&node_id, fn_sig) in self.fcx.tables.borrow().liberated_fn_sigs.iter() {
384 let fn_sig = self.resolve(fn_sig, &node_id);
385 self.tables.liberated_fn_sigs.insert(node_id, fn_sig.clone());
389 fn visit_fru_field_types(&mut self) {
390 for (&node_id, ftys) in self.fcx.tables.borrow().fru_field_types.iter() {
391 let ftys = self.resolve(ftys, &node_id);
392 self.tables.fru_field_types.insert(node_id, ftys);
396 fn resolve<T>(&self, x: &T, span: &Locatable) -> T::Lifted
397 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
399 let x = x.fold_with(&mut Resolver::new(self.fcx, span, self.body));
400 if let Some(lifted) = self.tcx().lift_to_global(&x) {
403 span_bug!(span.to_span(&self.fcx.tcx),
404 "writeback: `{:?}` missing from the global type context",
411 fn to_span(&self, tcx: &TyCtxt) -> Span;
414 impl Locatable for Span {
415 fn to_span(&self, _: &TyCtxt) -> Span { *self }
418 impl Locatable for ast::NodeId {
419 fn to_span(&self, tcx: &TyCtxt) -> Span { tcx.hir.span(*self) }
422 ///////////////////////////////////////////////////////////////////////////
423 // The Resolver. This is the type folding engine that detects
424 // unresolved types and so forth.
426 struct Resolver<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
427 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
428 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
429 span: &'cx Locatable,
430 body: &'gcx hir::Body,
433 impl<'cx, 'gcx, 'tcx> Resolver<'cx, 'gcx, 'tcx> {
434 fn new(fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>, span: &'cx Locatable, body: &'gcx hir::Body)
435 -> Resolver<'cx, 'gcx, 'tcx>
445 fn report_error(&self, t: Ty<'tcx>) {
446 if !self.tcx.sess.has_errors() {
447 self.infcx.need_type_info(self.body.id(), self.span.to_span(&self.tcx), t);
452 impl<'cx, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for Resolver<'cx, 'gcx, 'tcx> {
453 fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx> {
457 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
458 match self.infcx.fully_resolve(&t) {
461 debug!("Resolver::fold_ty: input type `{:?}` not fully resolvable",
463 self.report_error(t);
469 // FIXME This should be carefully checked
470 // We could use `self.report_error` but it doesn't accept a ty::Region, right now.
471 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
472 match self.infcx.fully_resolve(&r) {
475 self.tcx.types.re_static
481 ///////////////////////////////////////////////////////////////////////////
482 // During type check, we store promises with the result of trait
483 // lookup rather than the actual results (because the results are not
484 // necessarily available immediately). These routines unwind the
485 // promises. It is expected that we will have already reported any
486 // errors that may be encountered, so if the promises store an error,
487 // a dummy result is returned.