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