]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/writeback.rs
hir: remove NodeId from Expr
[rust.git] / src / librustc_typeck / check / writeback.rs
1 // Type resolution: the phase that finds all the types in the AST with
2 // unresolved type variables and replaces "ty_var" types with their
3 // substitutions.
4
5 use crate::check::FnCtxt;
6 use errors::DiagnosticBuilder;
7 use rustc::hir;
8 use rustc::hir::def_id::{DefId, DefIndex};
9 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
10 use rustc::infer::InferCtxt;
11 use rustc::ty::adjustment::{Adjust, Adjustment};
12 use rustc::ty::fold::{BottomUpFolder, TypeFoldable, TypeFolder};
13 use rustc::ty::subst::UnpackedKind;
14 use rustc::ty::{self, Ty, TyCtxt};
15 use rustc::util::nodemap::DefIdSet;
16 use rustc_data_structures::sync::Lrc;
17 use std::mem;
18 use syntax::ast;
19 use syntax_pos::Span;
20
21 ///////////////////////////////////////////////////////////////////////////
22 // Entry point
23
24 // During type inference, partially inferred types are
25 // represented using Type variables (ty::Infer). These don't appear in
26 // the final TypeckTables since all of the types should have been
27 // inferred once typeck_tables_of is done.
28 // When type inference is running however, having to update the typeck
29 // tables every time a new type is inferred would be unreasonably slow,
30 // so instead all of the replacement happens at the end in
31 // resolve_type_vars_in_body, which creates a new TypeTables which
32 // doesn't contain any inference types.
33 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
34     pub fn resolve_type_vars_in_body(&self, body: &'gcx hir::Body) -> &'gcx ty::TypeckTables<'gcx> {
35         let item_id = self.tcx.hir().body_owner(body.id());
36         let item_def_id = self.tcx.hir().local_def_id(item_id);
37
38         // This attribute causes us to dump some writeback information
39         // in the form of errors, which is used for unit tests.
40         let rustc_dump_user_substs = self.tcx.has_attr(item_def_id, "rustc_dump_user_substs");
41
42         let mut wbcx = WritebackCx::new(self, body, rustc_dump_user_substs);
43         for arg in &body.arguments {
44             wbcx.visit_node_id(arg.pat.span, arg.hir_id);
45         }
46         wbcx.visit_body(body);
47         wbcx.visit_upvar_capture_map();
48         wbcx.visit_upvar_list_map();
49         wbcx.visit_closures();
50         wbcx.visit_liberated_fn_sigs();
51         wbcx.visit_fru_field_types();
52         wbcx.visit_opaque_types(body.value.span);
53         wbcx.visit_cast_types();
54         wbcx.visit_free_region_map();
55         wbcx.visit_user_provided_tys();
56         wbcx.visit_user_provided_sigs();
57
58         let used_trait_imports = mem::replace(
59             &mut self.tables.borrow_mut().used_trait_imports,
60             Lrc::new(DefIdSet::default()),
61         );
62         debug!(
63             "used_trait_imports({:?}) = {:?}",
64             item_def_id, used_trait_imports
65         );
66         wbcx.tables.used_trait_imports = used_trait_imports;
67
68         wbcx.tables.tainted_by_errors = self.is_tainted_by_errors();
69
70         debug!(
71             "writeback: tables for {:?} are {:#?}",
72             item_def_id, wbcx.tables
73         );
74
75         self.tcx.alloc_tables(wbcx.tables)
76     }
77 }
78
79 ///////////////////////////////////////////////////////////////////////////
80 // The Writeback context. This visitor walks the AST, checking the
81 // fn-specific tables to find references to types or regions. It
82 // resolves those regions to remove inference variables and writes the
83 // final result back into the master tables in the tcx. Here and
84 // there, it applies a few ad-hoc checks that were not convenient to
85 // do elsewhere.
86
87 struct WritebackCx<'cx, 'gcx: 'cx + 'tcx, 'tcx: 'cx> {
88     fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>,
89
90     tables: ty::TypeckTables<'gcx>,
91
92     body: &'gcx hir::Body,
93
94     rustc_dump_user_substs: bool,
95 }
96
97 impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
98     fn new(
99         fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>,
100         body: &'gcx hir::Body,
101         rustc_dump_user_substs: bool,
102     ) -> WritebackCx<'cx, 'gcx, 'tcx> {
103         let owner = body.id().hir_id;
104
105         WritebackCx {
106             fcx,
107             tables: ty::TypeckTables::empty(Some(DefId::local(owner.owner))),
108             body,
109             rustc_dump_user_substs,
110         }
111     }
112
113     fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
114         self.fcx.tcx
115     }
116
117     fn write_ty_to_tables(&mut self, hir_id: hir::HirId, ty: Ty<'gcx>) {
118         debug!("write_ty_to_tables({:?}, {:?})", hir_id, ty);
119         assert!(!ty.needs_infer() && !ty.has_placeholders());
120         self.tables.node_types_mut().insert(hir_id, ty);
121     }
122
123     // Hacky hack: During type-checking, we treat *all* operators
124     // as potentially overloaded. But then, during writeback, if
125     // we observe that something like `a+b` is (known to be)
126     // operating on scalars, we clear the overload.
127     fn fix_scalar_builtin_expr(&mut self, e: &hir::Expr) {
128         match e.node {
129             hir::ExprKind::Unary(hir::UnNeg, ref inner)
130             | hir::ExprKind::Unary(hir::UnNot, ref inner) => {
131                 let inner_ty = self.fcx.node_ty(inner.hir_id);
132                 let inner_ty = self.fcx.resolve_type_vars_if_possible(&inner_ty);
133
134                 if inner_ty.is_scalar() {
135                     let mut tables = self.fcx.tables.borrow_mut();
136                     tables.type_dependent_defs_mut().remove(e.hir_id);
137                     tables.node_substs_mut().remove(e.hir_id);
138                 }
139             }
140             hir::ExprKind::Binary(ref op, ref lhs, ref rhs)
141             | hir::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
142                 let lhs_ty = self.fcx.node_ty(lhs.hir_id);
143                 let lhs_ty = self.fcx.resolve_type_vars_if_possible(&lhs_ty);
144
145                 let rhs_ty = self.fcx.node_ty(rhs.hir_id);
146                 let rhs_ty = self.fcx.resolve_type_vars_if_possible(&rhs_ty);
147
148                 if lhs_ty.is_scalar() && rhs_ty.is_scalar() {
149                     let mut tables = self.fcx.tables.borrow_mut();
150                     tables.type_dependent_defs_mut().remove(e.hir_id);
151                     tables.node_substs_mut().remove(e.hir_id);
152
153                     match e.node {
154                         hir::ExprKind::Binary(..) => {
155                             if !op.node.is_by_value() {
156                                 let mut adjustments = tables.adjustments_mut();
157                                 adjustments.get_mut(lhs.hir_id).map(|a| a.pop());
158                                 adjustments.get_mut(rhs.hir_id).map(|a| a.pop());
159                             }
160                         }
161                         hir::ExprKind::AssignOp(..) => {
162                             tables
163                                 .adjustments_mut()
164                                 .get_mut(lhs.hir_id)
165                                 .map(|a| a.pop());
166                         }
167                         _ => {}
168                     }
169                 }
170             }
171             _ => {}
172         }
173     }
174
175     // Similar to operators, indexing is always assumed to be overloaded
176     // Here, correct cases where an indexing expression can be simplified
177     // to use builtin indexing because the index type is known to be
178     // usize-ish
179     fn fix_index_builtin_expr(&mut self, e: &hir::Expr) {
180         if let hir::ExprKind::Index(ref base, ref index) = e.node {
181             let mut tables = self.fcx.tables.borrow_mut();
182
183             // All valid indexing looks like this; might encounter non-valid indexes at this point
184             if let ty::Ref(_, base_ty, _) = tables.expr_ty_adjusted(&base).sty {
185                 let index_ty = tables.expr_ty_adjusted(&index);
186                 let index_ty = self.fcx.resolve_type_vars_if_possible(&index_ty);
187
188                 if base_ty.builtin_index().is_some() && index_ty == self.fcx.tcx.types.usize {
189                     // Remove the method call record
190                     tables.type_dependent_defs_mut().remove(e.hir_id);
191                     tables.node_substs_mut().remove(e.hir_id);
192
193                     tables.adjustments_mut().get_mut(base.hir_id).map(|a| {
194                         // Discard the need for a mutable borrow
195                         match a.pop() {
196                             // Extra adjustment made when indexing causes a drop
197                             // of size information - we need to get rid of it
198                             // Since this is "after" the other adjustment to be
199                             // discarded, we do an extra `pop()`
200                             Some(Adjustment {
201                                 kind: Adjust::Unsize,
202                                 ..
203                             }) => {
204                                 // So the borrow discard actually happens here
205                                 a.pop();
206                             }
207                             _ => {}
208                         }
209                     });
210                 }
211             }
212         }
213     }
214 }
215
216 ///////////////////////////////////////////////////////////////////////////
217 // Impl of Visitor for Resolver
218 //
219 // This is the master code which walks the AST. It delegates most of
220 // the heavy lifting to the generic visit and resolve functions
221 // below. In general, a function is made into a `visitor` if it must
222 // traffic in node-ids or update tables in the type context etc.
223
224 impl<'cx, 'gcx, 'tcx> Visitor<'gcx> for WritebackCx<'cx, 'gcx, 'tcx> {
225     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
226         NestedVisitorMap::None
227     }
228
229     fn visit_expr(&mut self, e: &'gcx hir::Expr) {
230         self.fix_scalar_builtin_expr(e);
231         self.fix_index_builtin_expr(e);
232
233         self.visit_node_id(e.span, e.hir_id);
234
235         match e.node {
236             hir::ExprKind::Closure(_, _, body, _, _) => {
237                 let body = self.fcx.tcx.hir().body(body);
238                 for arg in &body.arguments {
239                     self.visit_node_id(e.span, arg.hir_id);
240                 }
241
242                 self.visit_body(body);
243             }
244             hir::ExprKind::Struct(_, ref fields, _) => {
245                 for field in fields {
246                     self.visit_field_id(field.hir_id);
247                 }
248             }
249             hir::ExprKind::Field(..) => {
250                 self.visit_field_id(e.hir_id);
251             }
252             _ => {}
253         }
254
255         intravisit::walk_expr(self, e);
256     }
257
258     fn visit_block(&mut self, b: &'gcx hir::Block) {
259         self.visit_node_id(b.span, b.hir_id);
260         intravisit::walk_block(self, b);
261     }
262
263     fn visit_pat(&mut self, p: &'gcx hir::Pat) {
264         match p.node {
265             hir::PatKind::Binding(..) => {
266                 if let Some(&bm) = self.fcx.tables.borrow().pat_binding_modes().get(p.hir_id) {
267                     self.tables.pat_binding_modes_mut().insert(p.hir_id, bm);
268                 } else {
269                     self.tcx()
270                         .sess
271                         .delay_span_bug(p.span, "missing binding mode");
272                 }
273             }
274             hir::PatKind::Struct(_, ref fields, _) => {
275                 for field in fields {
276                     self.visit_field_id(field.node.hir_id);
277                 }
278             }
279             _ => {}
280         };
281
282         self.visit_pat_adjustments(p.span, p.hir_id);
283
284         self.visit_node_id(p.span, p.hir_id);
285         intravisit::walk_pat(self, p);
286     }
287
288     fn visit_local(&mut self, l: &'gcx hir::Local) {
289         intravisit::walk_local(self, l);
290         let var_ty = self.fcx.local_ty(l.span, l.id).decl_ty;
291         let var_ty = self.resolve(&var_ty, &l.span);
292         self.write_ty_to_tables(l.hir_id, var_ty);
293     }
294
295     fn visit_ty(&mut self, hir_ty: &'gcx hir::Ty) {
296         intravisit::walk_ty(self, hir_ty);
297         let ty = self.fcx.node_ty(hir_ty.hir_id);
298         let ty = self.resolve(&ty, &hir_ty.span);
299         self.write_ty_to_tables(hir_ty.hir_id, ty);
300     }
301 }
302
303 impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
304     fn visit_upvar_capture_map(&mut self) {
305         for (upvar_id, upvar_capture) in self.fcx.tables.borrow().upvar_capture_map.iter() {
306             let new_upvar_capture = match *upvar_capture {
307                 ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue,
308                 ty::UpvarCapture::ByRef(ref upvar_borrow) => {
309                     let r = upvar_borrow.region;
310                     let r = self.resolve(&r, &upvar_id.var_path.hir_id);
311                     ty::UpvarCapture::ByRef(ty::UpvarBorrow {
312                         kind: upvar_borrow.kind,
313                         region: r,
314                     })
315                 }
316             };
317             debug!(
318                 "Upvar capture for {:?} resolved to {:?}",
319                 upvar_id, new_upvar_capture
320             );
321             self.tables
322                 .upvar_capture_map
323                 .insert(*upvar_id, new_upvar_capture);
324         }
325     }
326
327     /// Runs through the function context's upvar list map and adds the same to
328     /// the TypeckTables. upvarlist is a hashmap of the list of upvars referred
329     /// to in a closure..
330     fn visit_upvar_list_map(&mut self) {
331         for (closure_def_id, upvar_list) in self.fcx.tables.borrow().upvar_list.iter() {
332             debug!(
333                 "UpvarIDs captured by closure {:?} are: {:?}",
334                 closure_def_id, upvar_list
335             );
336             self.tables
337                 .upvar_list
338                 .insert(*closure_def_id, upvar_list.to_vec());
339         }
340     }
341
342     fn visit_closures(&mut self) {
343         let fcx_tables = self.fcx.tables.borrow();
344         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
345         let common_local_id_root = fcx_tables.local_id_root.unwrap();
346
347         for (&id, &origin) in fcx_tables.closure_kind_origins().iter() {
348             let hir_id = hir::HirId {
349                 owner: common_local_id_root.index,
350                 local_id: id,
351             };
352             self.tables
353                 .closure_kind_origins_mut()
354                 .insert(hir_id, origin);
355         }
356     }
357
358     fn visit_cast_types(&mut self) {
359         let fcx_tables = self.fcx.tables.borrow();
360         let fcx_cast_kinds = fcx_tables.cast_kinds();
361         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
362         let mut self_cast_kinds = self.tables.cast_kinds_mut();
363         let common_local_id_root = fcx_tables.local_id_root.unwrap();
364
365         for (&local_id, &cast_kind) in fcx_cast_kinds.iter() {
366             let hir_id = hir::HirId {
367                 owner: common_local_id_root.index,
368                 local_id,
369             };
370             self_cast_kinds.insert(hir_id, cast_kind);
371         }
372     }
373
374     fn visit_free_region_map(&mut self) {
375         let free_region_map = self.tcx()
376             .lift_to_global(&self.fcx.tables.borrow().free_region_map);
377         let free_region_map = free_region_map.expect("all regions in free-region-map are global");
378         self.tables.free_region_map = free_region_map;
379     }
380
381     fn visit_user_provided_tys(&mut self) {
382         let fcx_tables = self.fcx.tables.borrow();
383         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
384         let common_local_id_root = fcx_tables.local_id_root.unwrap();
385
386         let mut errors_buffer = Vec::new();
387         for (&local_id, c_ty) in fcx_tables.user_provided_types().iter() {
388             let hir_id = hir::HirId {
389                 owner: common_local_id_root.index,
390                 local_id,
391             };
392
393             let c_ty = if let Some(c_ty) = self.tcx().lift_to_global(c_ty) {
394                 c_ty
395             } else {
396                 span_bug!(
397                     hir_id.to_span(&self.fcx.tcx),
398                     "writeback: `{:?}` missing from the global type context",
399                     c_ty
400                 );
401             };
402
403             self.tables
404                 .user_provided_types_mut()
405                 .insert(hir_id, c_ty.clone());
406
407             if let ty::UserType::TypeOf(_, user_substs) = c_ty.value {
408                 if self.rustc_dump_user_substs {
409                     // This is a unit-testing mechanism.
410                     let span = self.tcx().hir().span_by_hir_id(hir_id);
411                     // We need to buffer the errors in order to guarantee a consistent
412                     // order when emitting them.
413                     let err = self.tcx().sess.struct_span_err(
414                         span,
415                         &format!("user substs: {:?}", user_substs)
416                     );
417                     err.buffer(&mut errors_buffer);
418                 }
419             }
420         }
421
422         if !errors_buffer.is_empty() {
423             errors_buffer.sort_by_key(|diag| diag.span.primary_span());
424             for diag in errors_buffer.drain(..) {
425                 DiagnosticBuilder::new_diagnostic(self.tcx().sess.diagnostic(), diag).emit();
426             }
427         }
428     }
429
430     fn visit_user_provided_sigs(&mut self) {
431         let fcx_tables = self.fcx.tables.borrow();
432         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
433
434         for (&def_id, c_sig) in fcx_tables.user_provided_sigs.iter() {
435             let c_sig = if let Some(c_sig) = self.tcx().lift_to_global(c_sig) {
436                 c_sig
437             } else {
438                 span_bug!(
439                     self.fcx.tcx.hir().span_if_local(def_id).unwrap(),
440                     "writeback: `{:?}` missing from the global type context",
441                     c_sig
442                 );
443             };
444
445             self.tables
446                 .user_provided_sigs
447                 .insert(def_id, c_sig.clone());
448         }
449     }
450
451     fn visit_opaque_types(&mut self, span: Span) {
452         for (&def_id, opaque_defn) in self.fcx.opaque_types.borrow().iter() {
453             let node_id = self.tcx().hir().as_local_node_id(def_id).unwrap();
454             let instantiated_ty = self.resolve(&opaque_defn.concrete_ty, &node_id);
455
456             let generics = self.tcx().generics_of(def_id);
457
458             let definition_ty = if generics.parent.is_some() {
459                 // impl trait
460                 self.fcx.infer_opaque_definition_from_instantiation(
461                     def_id,
462                     opaque_defn,
463                     instantiated_ty,
464                 )
465             } else {
466                 // prevent
467                 // * `fn foo<T>() -> Foo<T>`
468                 // * `fn foo<T: Bound + Other>() -> Foo<T>`
469                 // from being defining
470
471                 // Also replace all generic params with the ones from the existential type
472                 // definition so
473                 // ```rust
474                 // existential type Foo<T>: 'static;
475                 // fn foo<U>() -> Foo<U> { .. }
476                 // ```
477                 // figures out the concrete type with `U`, but the stored type is with `T`
478                 instantiated_ty.fold_with(&mut BottomUpFolder {
479                     tcx: self.tcx().global_tcx(),
480                     fldop: |ty| {
481                         trace!("checking type {:?}: {:#?}", ty, ty.sty);
482                         // find a type parameter
483                         if let ty::Param(..) = ty.sty {
484                             // look it up in the substitution list
485                             assert_eq!(opaque_defn.substs.len(), generics.params.len());
486                             for (subst, param) in opaque_defn.substs.iter().zip(&generics.params) {
487                                 if let UnpackedKind::Type(subst) = subst.unpack() {
488                                     if subst == ty {
489                                         // found it in the substitution list, replace with the
490                                         // parameter from the existential type
491                                         return self.tcx()
492                                             .global_tcx()
493                                             .mk_ty_param(param.index, param.name);
494                                     }
495                                 }
496                             }
497                             self.tcx()
498                                 .sess
499                                 .struct_span_err(
500                                     span,
501                                     &format!(
502                                         "type parameter `{}` is part of concrete type but not used \
503                                          in parameter list for existential type",
504                                         ty,
505                                     ),
506                                 )
507                                 .emit();
508                             return self.tcx().types.err;
509                         }
510                         ty
511                     },
512                     reg_op: |region| {
513                         match region {
514                             // ignore static regions
515                             ty::ReStatic => region,
516                             _ => {
517                                 trace!("checking {:?}", region);
518                                 for (subst, p) in opaque_defn.substs.iter().zip(&generics.params) {
519                                     if let UnpackedKind::Lifetime(subst) = subst.unpack() {
520                                         if subst == region {
521                                             // found it in the substitution list, replace with the
522                                             // parameter from the existential type
523                                             let reg = ty::EarlyBoundRegion {
524                                                 def_id: p.def_id,
525                                                 index: p.index,
526                                                 name: p.name,
527                                             };
528                                             trace!("replace {:?} with {:?}", region, reg);
529                                             return self.tcx()
530                                                 .global_tcx()
531                                                 .mk_region(ty::ReEarlyBound(reg));
532                                         }
533                                     }
534                                 }
535                                 trace!("opaque_defn: {:#?}", opaque_defn);
536                                 trace!("generics: {:#?}", generics);
537                                 self.tcx()
538                                     .sess
539                                     .struct_span_err(
540                                         span,
541                                         "non-defining existential type use in defining scope",
542                                     )
543                                     .span_label(
544                                         span,
545                                         format!(
546                                             "lifetime `{}` is part of concrete type but not used \
547                                              in parameter list of existential type",
548                                             region,
549                                         ),
550                                     )
551                                     .emit();
552                                 self.tcx().global_tcx().mk_region(ty::ReStatic)
553                             }
554                         }
555                     },
556                 })
557             };
558
559             if let ty::Opaque(defin_ty_def_id, _substs) = definition_ty.sty {
560                 if def_id == defin_ty_def_id {
561                     // Concrete type resolved to the existential type itself
562                     // Force a cycle error
563                     // FIXME(oli-obk): we could just not insert it into `concrete_existential_types`
564                     // which simply would make this use not a defining use.
565                     self.tcx().at(span).type_of(defin_ty_def_id);
566                 }
567             }
568
569             let new = ty::ResolvedOpaqueTy {
570                 concrete_type: definition_ty,
571                 substs: self.tcx().lift_to_global(&opaque_defn.substs).unwrap(),
572             };
573
574             let old = self.tables
575                 .concrete_existential_types
576                 .insert(def_id, new);
577             if let Some(old) = old {
578                 if old.concrete_type != definition_ty || old.substs != opaque_defn.substs {
579                     span_bug!(
580                         span,
581                         "visit_opaque_types tried to write \
582                         different types for the same existential type: {:?}, {:?}, {:?}, {:?}",
583                         def_id,
584                         definition_ty,
585                         opaque_defn,
586                         old,
587                     );
588                 }
589             }
590         }
591     }
592
593     fn visit_field_id(&mut self, hir_id: hir::HirId) {
594         if let Some(index) = self.fcx
595             .tables
596             .borrow_mut()
597             .field_indices_mut()
598             .remove(hir_id)
599         {
600             self.tables.field_indices_mut().insert(hir_id, index);
601         }
602     }
603
604     fn visit_node_id(&mut self, span: Span, hir_id: hir::HirId) {
605         // Export associated path extensions and method resolutions.
606         if let Some(def) = self.fcx
607             .tables
608             .borrow_mut()
609             .type_dependent_defs_mut()
610             .remove(hir_id)
611         {
612             self.tables.type_dependent_defs_mut().insert(hir_id, def);
613         }
614
615         // Resolve any borrowings for the node with id `node_id`
616         self.visit_adjustments(span, hir_id);
617
618         // Resolve the type of the node with id `node_id`
619         let n_ty = self.fcx.node_ty(hir_id);
620         let n_ty = self.resolve(&n_ty, &span);
621         self.write_ty_to_tables(hir_id, n_ty);
622         debug!("Node {:?} has type {:?}", hir_id, n_ty);
623
624         // Resolve any substitutions
625         if let Some(substs) = self.fcx.tables.borrow().node_substs_opt(hir_id) {
626             let substs = self.resolve(&substs, &span);
627             debug!("write_substs_to_tcx({:?}, {:?})", hir_id, substs);
628             assert!(!substs.needs_infer() && !substs.has_placeholders());
629             self.tables.node_substs_mut().insert(hir_id, substs);
630         }
631     }
632
633     fn visit_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
634         let adjustment = self.fcx
635             .tables
636             .borrow_mut()
637             .adjustments_mut()
638             .remove(hir_id);
639         match adjustment {
640             None => {
641                 debug!("No adjustments for node {:?}", hir_id);
642             }
643
644             Some(adjustment) => {
645                 let resolved_adjustment = self.resolve(&adjustment, &span);
646                 debug!(
647                     "Adjustments for node {:?}: {:?}",
648                     hir_id, resolved_adjustment
649                 );
650                 self.tables
651                     .adjustments_mut()
652                     .insert(hir_id, resolved_adjustment);
653             }
654         }
655     }
656
657     fn visit_pat_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
658         let adjustment = self.fcx
659             .tables
660             .borrow_mut()
661             .pat_adjustments_mut()
662             .remove(hir_id);
663         match adjustment {
664             None => {
665                 debug!("No pat_adjustments for node {:?}", hir_id);
666             }
667
668             Some(adjustment) => {
669                 let resolved_adjustment = self.resolve(&adjustment, &span);
670                 debug!(
671                     "pat_adjustments for node {:?}: {:?}",
672                     hir_id, resolved_adjustment
673                 );
674                 self.tables
675                     .pat_adjustments_mut()
676                     .insert(hir_id, resolved_adjustment);
677             }
678         }
679     }
680
681     fn visit_liberated_fn_sigs(&mut self) {
682         let fcx_tables = self.fcx.tables.borrow();
683         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
684         let common_local_id_root = fcx_tables.local_id_root.unwrap();
685
686         for (&local_id, fn_sig) in fcx_tables.liberated_fn_sigs().iter() {
687             let hir_id = hir::HirId {
688                 owner: common_local_id_root.index,
689                 local_id,
690             };
691             let fn_sig = self.resolve(fn_sig, &hir_id);
692             self.tables
693                 .liberated_fn_sigs_mut()
694                 .insert(hir_id, fn_sig.clone());
695         }
696     }
697
698     fn visit_fru_field_types(&mut self) {
699         let fcx_tables = self.fcx.tables.borrow();
700         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
701         let common_local_id_root = fcx_tables.local_id_root.unwrap();
702
703         for (&local_id, ftys) in fcx_tables.fru_field_types().iter() {
704             let hir_id = hir::HirId {
705                 owner: common_local_id_root.index,
706                 local_id,
707             };
708             let ftys = self.resolve(ftys, &hir_id);
709             self.tables.fru_field_types_mut().insert(hir_id, ftys);
710         }
711     }
712
713     fn resolve<T>(&self, x: &T, span: &dyn Locatable) -> T::Lifted
714     where
715         T: TypeFoldable<'tcx> + ty::Lift<'gcx>,
716     {
717         let x = x.fold_with(&mut Resolver::new(self.fcx, span, self.body));
718         if let Some(lifted) = self.tcx().lift_to_global(&x) {
719             lifted
720         } else {
721             span_bug!(
722                 span.to_span(&self.fcx.tcx),
723                 "writeback: `{:?}` missing from the global type context",
724                 x
725             );
726         }
727     }
728 }
729
730 trait Locatable {
731     fn to_span(&self, tcx: &TyCtxt) -> Span;
732 }
733
734 impl Locatable for Span {
735     fn to_span(&self, _: &TyCtxt) -> Span {
736         *self
737     }
738 }
739
740 impl Locatable for ast::NodeId {
741     fn to_span(&self, tcx: &TyCtxt) -> Span {
742         tcx.hir().span(*self)
743     }
744 }
745
746 impl Locatable for DefIndex {
747     fn to_span(&self, tcx: &TyCtxt) -> Span {
748         let hir_id = tcx.hir().def_index_to_hir_id(*self);
749         tcx.hir().span_by_hir_id(hir_id)
750     }
751 }
752
753 impl Locatable for hir::HirId {
754     fn to_span(&self, tcx: &TyCtxt) -> Span {
755         tcx.hir().span_by_hir_id(*self)
756     }
757 }
758
759 ///////////////////////////////////////////////////////////////////////////
760 // The Resolver. This is the type folding engine that detects
761 // unresolved types and so forth.
762
763 struct Resolver<'cx, 'gcx: 'cx + 'tcx, 'tcx: 'cx> {
764     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
765     infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
766     span: &'cx dyn Locatable,
767     body: &'gcx hir::Body,
768 }
769
770 impl<'cx, 'gcx, 'tcx> Resolver<'cx, 'gcx, 'tcx> {
771     fn new(
772         fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>,
773         span: &'cx dyn Locatable,
774         body: &'gcx hir::Body,
775     ) -> Resolver<'cx, 'gcx, 'tcx> {
776         Resolver {
777             tcx: fcx.tcx,
778             infcx: fcx,
779             span,
780             body,
781         }
782     }
783
784     fn report_error(&self, t: Ty<'tcx>) {
785         if !self.tcx.sess.has_errors() {
786             self.infcx
787                 .need_type_info_err(Some(self.body.id()), self.span.to_span(&self.tcx), t)
788                 .emit();
789         }
790     }
791 }
792
793 impl<'cx, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for Resolver<'cx, 'gcx, 'tcx> {
794     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx> {
795         self.tcx
796     }
797
798     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
799         match self.infcx.fully_resolve(&t) {
800             Ok(t) => t,
801             Err(_) => {
802                 debug!(
803                     "Resolver::fold_ty: input type `{:?}` not fully resolvable",
804                     t
805                 );
806                 self.report_error(t);
807                 self.tcx().types.err
808             }
809         }
810     }
811
812     // FIXME This should be carefully checked
813     // We could use `self.report_error` but it doesn't accept a ty::Region, right now.
814     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
815         self.infcx.fully_resolve(&r).unwrap_or(self.tcx.types.re_static)
816     }
817 }
818
819 ///////////////////////////////////////////////////////////////////////////
820 // During type check, we store promises with the result of trait
821 // lookup rather than the actual results (because the results are not
822 // necessarily available immediately). These routines unwind the
823 // promises. It is expected that we will have already reported any
824 // errors that may be encountered, so if the promises store an error,
825 // a dummy result is returned.