]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/writeback.rs
Rollup merge of #68033 - ollie27:win_f32, r=dtolnay
[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
7 use rustc::hir::map::Map;
8 use rustc::infer::error_reporting::TypeAnnotationNeeded::E0282;
9 use rustc::infer::InferCtxt;
10 use rustc::ty::adjustment::{Adjust, Adjustment, PointerCast};
11 use rustc::ty::fold::{TypeFoldable, TypeFolder};
12 use rustc::ty::{self, Ty, TyCtxt};
13 use rustc_data_structures::sync::Lrc;
14 use rustc_hir as hir;
15 use rustc_hir::def_id::{DefId, DefIdSet, DefIndex};
16 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
17 use rustc_span::symbol::sym;
18 use rustc_span::Span;
19
20 use std::mem;
21
22 ///////////////////////////////////////////////////////////////////////////
23 // Entry point
24
25 // During type inference, partially inferred types are
26 // represented using Type variables (ty::Infer). These don't appear in
27 // the final TypeckTables since all of the types should have been
28 // inferred once typeck_tables_of is done.
29 // When type inference is running however, having to update the typeck
30 // tables every time a new type is inferred would be unreasonably slow,
31 // so instead all of the replacement happens at the end in
32 // resolve_type_vars_in_body, which creates a new TypeTables which
33 // doesn't contain any inference types.
34 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
35     pub fn resolve_type_vars_in_body(
36         &self,
37         body: &'tcx hir::Body<'tcx>,
38     ) -> &'tcx ty::TypeckTables<'tcx> {
39         let item_id = self.tcx.hir().body_owner(body.id());
40         let item_def_id = self.tcx.hir().local_def_id(item_id);
41
42         // This attribute causes us to dump some writeback information
43         // in the form of errors, which is uSymbolfor unit tests.
44         let rustc_dump_user_substs = self.tcx.has_attr(item_def_id, sym::rustc_dump_user_substs);
45
46         let mut wbcx = WritebackCx::new(self, body, rustc_dump_user_substs);
47         for param in body.params {
48             wbcx.visit_node_id(param.pat.span, param.hir_id);
49         }
50         // Type only exists for constants and statics, not functions.
51         match self.tcx.hir().body_owner_kind(item_id) {
52             hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => {
53                 wbcx.visit_node_id(body.value.span, item_id);
54             }
55             hir::BodyOwnerKind::Closure | hir::BodyOwnerKind::Fn => (),
56         }
57         wbcx.visit_body(body);
58         wbcx.visit_upvar_capture_map();
59         wbcx.visit_closures();
60         wbcx.visit_liberated_fn_sigs();
61         wbcx.visit_fru_field_types();
62         wbcx.visit_opaque_types(body.value.span);
63         wbcx.visit_coercion_casts();
64         wbcx.visit_free_region_map();
65         wbcx.visit_user_provided_tys();
66         wbcx.visit_user_provided_sigs();
67         wbcx.visit_generator_interior_types();
68
69         let used_trait_imports = mem::replace(
70             &mut self.tables.borrow_mut().used_trait_imports,
71             Lrc::new(DefIdSet::default()),
72         );
73         debug!("used_trait_imports({:?}) = {:?}", item_def_id, used_trait_imports);
74         wbcx.tables.used_trait_imports = used_trait_imports;
75
76         wbcx.tables.upvar_list =
77             mem::replace(&mut self.tables.borrow_mut().upvar_list, Default::default());
78
79         wbcx.tables.tainted_by_errors = self.is_tainted_by_errors();
80
81         debug!("writeback: tables for {:?} are {:#?}", item_def_id, wbcx.tables);
82
83         self.tcx.arena.alloc(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, 'tcx> {
96     fcx: &'cx FnCtxt<'cx, 'tcx>,
97
98     tables: ty::TypeckTables<'tcx>,
99
100     body: &'tcx hir::Body<'tcx>,
101
102     rustc_dump_user_substs: bool,
103 }
104
105 impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
106     fn new(
107         fcx: &'cx FnCtxt<'cx, 'tcx>,
108         body: &'tcx hir::Body<'tcx>,
109         rustc_dump_user_substs: bool,
110     ) -> WritebackCx<'cx, '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<'tcx> {
122         self.fcx.tcx
123     }
124
125     fn write_ty_to_tables(&mut self, hir_id: hir::HirId, ty: Ty<'tcx>) {
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.kind {
137             hir::ExprKind::Unary(hir::UnOp::UnNeg, ref inner)
138             | hir::ExprKind::Unary(hir::UnOp::UnNot, ref inner) => {
139                 let inner_ty = self.fcx.node_ty(inner.hir_id);
140                 let inner_ty = self.fcx.resolve_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_vars_if_possible(&lhs_ty);
152
153                 let rhs_ty = self.fcx.node_ty(rhs.hir_id);
154                 let rhs_ty = self.fcx.resolve_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.kind {
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.adjustments_mut().get_mut(lhs.hir_id).map(|a| a.pop());
171                         }
172                         _ => {}
173                     }
174                 }
175             }
176             _ => {}
177         }
178     }
179
180     // Similar to operators, indexing is always assumed to be overloaded
181     // Here, correct cases where an indexing expression can be simplified
182     // to use builtin indexing because the index type is known to be
183     // usize-ish
184     fn fix_index_builtin_expr(&mut self, e: &hir::Expr<'_>) {
185         if let hir::ExprKind::Index(ref base, ref index) = e.kind {
186             let mut tables = self.fcx.tables.borrow_mut();
187
188             // All valid indexing looks like this; might encounter non-valid indexes at this point.
189             let base_ty = tables.expr_ty_adjusted_opt(&base).map(|t| &t.kind);
190             if base_ty.is_none() {
191                 // When encountering `return [0][0]` outside of a `fn` body we can encounter a base
192                 // that isn't in the type table. We assume more relevant errors have already been
193                 // emitted, so we delay an ICE if none have. (#64638)
194                 self.tcx().sess.delay_span_bug(e.span, &format!("bad base: `{:?}`", base));
195             }
196             if let Some(ty::Ref(_, base_ty, _)) = base_ty {
197                 let index_ty = tables.expr_ty_adjusted_opt(&index).unwrap_or_else(|| {
198                     // When encountering `return [0][0]` outside of a `fn` body we would attempt
199                     // to access an unexistend index. We assume that more relevant errors will
200                     // already have been emitted, so we only gate on this with an ICE if no
201                     // error has been emitted. (#64638)
202                     self.tcx().sess.delay_span_bug(
203                         e.span,
204                         &format!("bad index {:?} for base: `{:?}`", index, base),
205                     );
206                     self.fcx.tcx.types.err
207                 });
208                 let index_ty = self.fcx.resolve_vars_if_possible(&index_ty);
209
210                 if base_ty.builtin_index().is_some() && index_ty == self.fcx.tcx.types.usize {
211                     // Remove the method call record
212                     tables.type_dependent_defs_mut().remove(e.hir_id);
213                     tables.node_substs_mut().remove(e.hir_id);
214
215                     tables.adjustments_mut().get_mut(base.hir_id).map(|a| {
216                         // Discard the need for a mutable borrow
217                         match a.pop() {
218                             // Extra adjustment made when indexing causes a drop
219                             // of size information - we need to get rid of it
220                             // Since this is "after" the other adjustment to be
221                             // discarded, we do an extra `pop()`
222                             Some(Adjustment {
223                                 kind: Adjust::Pointer(PointerCast::Unsize), ..
224                             }) => {
225                                 // So the borrow discard actually happens here
226                                 a.pop();
227                             }
228                             _ => {}
229                         }
230                     });
231                 }
232             }
233         }
234     }
235 }
236
237 ///////////////////////////////////////////////////////////////////////////
238 // Impl of Visitor for Resolver
239 //
240 // This is the master code which walks the AST. It delegates most of
241 // the heavy lifting to the generic visit and resolve functions
242 // below. In general, a function is made into a `visitor` if it must
243 // traffic in node-ids or update tables in the type context etc.
244
245 impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> {
246     type Map = Map<'tcx>;
247
248     fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
249         NestedVisitorMap::None
250     }
251
252     fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
253         self.fix_scalar_builtin_expr(e);
254         self.fix_index_builtin_expr(e);
255
256         self.visit_node_id(e.span, e.hir_id);
257
258         match e.kind {
259             hir::ExprKind::Closure(_, _, body, _, _) => {
260                 let body = self.fcx.tcx.hir().body(body);
261                 for param in body.params {
262                     self.visit_node_id(e.span, param.hir_id);
263                 }
264
265                 self.visit_body(body);
266             }
267             hir::ExprKind::Struct(_, fields, _) => {
268                 for field in fields {
269                     self.visit_field_id(field.hir_id);
270                 }
271             }
272             hir::ExprKind::Field(..) => {
273                 self.visit_field_id(e.hir_id);
274             }
275             _ => {}
276         }
277
278         intravisit::walk_expr(self, e);
279     }
280
281     fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) {
282         self.visit_node_id(b.span, b.hir_id);
283         intravisit::walk_block(self, b);
284     }
285
286     fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
287         match p.kind {
288             hir::PatKind::Binding(..) => {
289                 let tables = self.fcx.tables.borrow();
290                 if let Some(bm) = tables.extract_binding_mode(self.tcx().sess, p.hir_id, p.span) {
291                     self.tables.pat_binding_modes_mut().insert(p.hir_id, bm);
292                 }
293             }
294             hir::PatKind::Struct(_, fields, _) => {
295                 for field in fields {
296                     self.visit_field_id(field.hir_id);
297                 }
298             }
299             _ => {}
300         };
301
302         self.visit_pat_adjustments(p.span, p.hir_id);
303
304         self.visit_node_id(p.span, p.hir_id);
305         intravisit::walk_pat(self, p);
306     }
307
308     fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
309         intravisit::walk_local(self, l);
310         let var_ty = self.fcx.local_ty(l.span, l.hir_id).decl_ty;
311         let var_ty = self.resolve(&var_ty, &l.span);
312         self.write_ty_to_tables(l.hir_id, var_ty);
313     }
314
315     fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) {
316         intravisit::walk_ty(self, hir_ty);
317         let ty = self.fcx.node_ty(hir_ty.hir_id);
318         let ty = self.resolve(&ty, &hir_ty.span);
319         self.write_ty_to_tables(hir_ty.hir_id, ty);
320     }
321 }
322
323 impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
324     fn visit_upvar_capture_map(&mut self) {
325         for (upvar_id, upvar_capture) in self.fcx.tables.borrow().upvar_capture_map.iter() {
326             let new_upvar_capture = match *upvar_capture {
327                 ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue,
328                 ty::UpvarCapture::ByRef(ref upvar_borrow) => {
329                     let r = upvar_borrow.region;
330                     let r = self.resolve(&r, &upvar_id.var_path.hir_id);
331                     ty::UpvarCapture::ByRef(ty::UpvarBorrow { kind: upvar_borrow.kind, region: r })
332                 }
333             };
334             debug!("Upvar capture for {:?} resolved to {:?}", upvar_id, new_upvar_capture);
335             self.tables.upvar_capture_map.insert(*upvar_id, new_upvar_capture);
336         }
337     }
338
339     fn visit_closures(&mut self) {
340         let fcx_tables = self.fcx.tables.borrow();
341         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
342         let common_local_id_root = fcx_tables.local_id_root.unwrap();
343
344         for (&id, &origin) in fcx_tables.closure_kind_origins().iter() {
345             let hir_id = hir::HirId { owner: common_local_id_root.index, local_id: id };
346             self.tables.closure_kind_origins_mut().insert(hir_id, origin);
347         }
348     }
349
350     fn visit_coercion_casts(&mut self) {
351         let fcx_tables = self.fcx.tables.borrow();
352         let fcx_coercion_casts = fcx_tables.coercion_casts();
353         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
354
355         for local_id in fcx_coercion_casts {
356             self.tables.set_coercion_cast(*local_id);
357         }
358     }
359
360     fn visit_free_region_map(&mut self) {
361         self.tables.free_region_map = self.fcx.tables.borrow().free_region_map.clone();
362         debug_assert!(!self.tables.free_region_map.elements().any(|r| r.has_local_value()));
363     }
364
365     fn visit_user_provided_tys(&mut self) {
366         let fcx_tables = self.fcx.tables.borrow();
367         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
368         let common_local_id_root = fcx_tables.local_id_root.unwrap();
369
370         let mut errors_buffer = Vec::new();
371         for (&local_id, c_ty) in fcx_tables.user_provided_types().iter() {
372             let hir_id = hir::HirId { owner: common_local_id_root.index, local_id };
373
374             if cfg!(debug_assertions) && c_ty.has_local_value() {
375                 span_bug!(hir_id.to_span(self.fcx.tcx), "writeback: `{:?}` is a local value", c_ty);
376             };
377
378             self.tables.user_provided_types_mut().insert(hir_id, c_ty.clone());
379
380             if let ty::UserType::TypeOf(_, user_substs) = c_ty.value {
381                 if self.rustc_dump_user_substs {
382                     // This is a unit-testing mechanism.
383                     let span = self.tcx().hir().span(hir_id);
384                     // We need to buffer the errors in order to guarantee a consistent
385                     // order when emitting them.
386                     let err = self
387                         .tcx()
388                         .sess
389                         .struct_span_err(span, &format!("user substs: {:?}", user_substs));
390                     err.buffer(&mut errors_buffer);
391                 }
392             }
393         }
394
395         if !errors_buffer.is_empty() {
396             errors_buffer.sort_by_key(|diag| diag.span.primary_span());
397             for diag in errors_buffer.drain(..) {
398                 self.tcx().sess.diagnostic().emit_diagnostic(&diag);
399             }
400         }
401     }
402
403     fn visit_user_provided_sigs(&mut self) {
404         let fcx_tables = self.fcx.tables.borrow();
405         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
406
407         for (&def_id, c_sig) in fcx_tables.user_provided_sigs.iter() {
408             if cfg!(debug_assertions) && c_sig.has_local_value() {
409                 span_bug!(
410                     self.fcx.tcx.hir().span_if_local(def_id).unwrap(),
411                     "writeback: `{:?}` is a local value",
412                     c_sig
413                 );
414             };
415
416             self.tables.user_provided_sigs.insert(def_id, c_sig.clone());
417         }
418     }
419
420     fn visit_generator_interior_types(&mut self) {
421         let fcx_tables = self.fcx.tables.borrow();
422         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
423         self.tables.generator_interior_types = fcx_tables.generator_interior_types.clone();
424     }
425
426     fn visit_opaque_types(&mut self, span: Span) {
427         for (&def_id, opaque_defn) in self.fcx.opaque_types.borrow().iter() {
428             let hir_id = self.tcx().hir().as_local_hir_id(def_id).unwrap();
429             let instantiated_ty = self.resolve(&opaque_defn.concrete_ty, &hir_id);
430
431             debug_assert!(!instantiated_ty.has_escaping_bound_vars());
432
433             // Prevent:
434             // * `fn foo<T>() -> Foo<T>`
435             // * `fn foo<T: Bound + Other>() -> Foo<T>`
436             // from being defining.
437
438             // Also replace all generic params with the ones from the opaque type
439             // definition so that
440             // ```rust
441             // type Foo<T> = impl Baz + 'static;
442             // fn foo<U>() -> Foo<U> { .. }
443             // ```
444             // figures out the concrete type with `U`, but the stored type is with `T`.
445             let definition_ty = self.fcx.infer_opaque_definition_from_instantiation(
446                 def_id,
447                 opaque_defn,
448                 instantiated_ty,
449                 span,
450             );
451
452             let mut skip_add = false;
453
454             if let ty::Opaque(defin_ty_def_id, _substs) = definition_ty.kind {
455                 if let hir::OpaqueTyOrigin::TypeAlias = opaque_defn.origin {
456                     if def_id == defin_ty_def_id {
457                         debug!(
458                             "skipping adding concrete definition for opaque type {:?} {:?}",
459                             opaque_defn, defin_ty_def_id
460                         );
461                         skip_add = true;
462                     }
463                 }
464             }
465
466             if !opaque_defn.substs.has_local_value() {
467                 // We only want to add an entry into `concrete_opaque_types`
468                 // if we actually found a defining usage of this opaque type.
469                 // Otherwise, we do nothing - we'll either find a defining usage
470                 // in some other location, or we'll end up emitting an error due
471                 // to the lack of defining usage
472                 if !skip_add {
473                     let new = ty::ResolvedOpaqueTy {
474                         concrete_type: definition_ty,
475                         substs: opaque_defn.substs,
476                     };
477
478                     let old = self.tables.concrete_opaque_types.insert(def_id, new);
479                     if let Some(old) = old {
480                         if old.concrete_type != definition_ty || old.substs != opaque_defn.substs {
481                             span_bug!(
482                                 span,
483                                 "`visit_opaque_types` tried to write different types for the same \
484                                  opaque type: {:?}, {:?}, {:?}, {:?}",
485                                 def_id,
486                                 definition_ty,
487                                 opaque_defn,
488                                 old,
489                             );
490                         }
491                     }
492                 }
493             } else {
494                 self.tcx().sess.delay_span_bug(span, "`opaque_defn` is a local value");
495             }
496         }
497     }
498
499     fn visit_field_id(&mut self, hir_id: hir::HirId) {
500         if let Some(index) = self.fcx.tables.borrow_mut().field_indices_mut().remove(hir_id) {
501             self.tables.field_indices_mut().insert(hir_id, index);
502         }
503     }
504
505     fn visit_node_id(&mut self, span: Span, hir_id: hir::HirId) {
506         // Export associated path extensions and method resolutions.
507         if let Some(def) = self.fcx.tables.borrow_mut().type_dependent_defs_mut().remove(hir_id) {
508             self.tables.type_dependent_defs_mut().insert(hir_id, def);
509         }
510
511         // Resolve any borrowings for the node with id `node_id`
512         self.visit_adjustments(span, hir_id);
513
514         // Resolve the type of the node with id `node_id`
515         let n_ty = self.fcx.node_ty(hir_id);
516         let n_ty = self.resolve(&n_ty, &span);
517         self.write_ty_to_tables(hir_id, n_ty);
518         debug!("node {:?} has type {:?}", hir_id, n_ty);
519
520         // Resolve any substitutions
521         if let Some(substs) = self.fcx.tables.borrow().node_substs_opt(hir_id) {
522             let substs = self.resolve(&substs, &span);
523             debug!("write_substs_to_tcx({:?}, {:?})", hir_id, substs);
524             assert!(!substs.needs_infer() && !substs.has_placeholders());
525             self.tables.node_substs_mut().insert(hir_id, substs);
526         }
527     }
528
529     fn visit_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
530         let adjustment = self.fcx.tables.borrow_mut().adjustments_mut().remove(hir_id);
531         match adjustment {
532             None => {
533                 debug!("no adjustments for node {:?}", hir_id);
534             }
535
536             Some(adjustment) => {
537                 let resolved_adjustment = self.resolve(&adjustment, &span);
538                 debug!("adjustments for node {:?}: {:?}", hir_id, resolved_adjustment);
539                 self.tables.adjustments_mut().insert(hir_id, resolved_adjustment);
540             }
541         }
542     }
543
544     fn visit_pat_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
545         let adjustment = self.fcx.tables.borrow_mut().pat_adjustments_mut().remove(hir_id);
546         match adjustment {
547             None => {
548                 debug!("no pat_adjustments for node {:?}", hir_id);
549             }
550
551             Some(adjustment) => {
552                 let resolved_adjustment = self.resolve(&adjustment, &span);
553                 debug!("pat_adjustments for node {:?}: {:?}", hir_id, resolved_adjustment);
554                 self.tables.pat_adjustments_mut().insert(hir_id, resolved_adjustment);
555             }
556         }
557     }
558
559     fn visit_liberated_fn_sigs(&mut self) {
560         let fcx_tables = self.fcx.tables.borrow();
561         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
562         let common_local_id_root = fcx_tables.local_id_root.unwrap();
563
564         for (&local_id, fn_sig) in fcx_tables.liberated_fn_sigs().iter() {
565             let hir_id = hir::HirId { owner: common_local_id_root.index, local_id };
566             let fn_sig = self.resolve(fn_sig, &hir_id);
567             self.tables.liberated_fn_sigs_mut().insert(hir_id, fn_sig.clone());
568         }
569     }
570
571     fn visit_fru_field_types(&mut self) {
572         let fcx_tables = self.fcx.tables.borrow();
573         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
574         let common_local_id_root = fcx_tables.local_id_root.unwrap();
575
576         for (&local_id, ftys) in fcx_tables.fru_field_types().iter() {
577             let hir_id = hir::HirId { owner: common_local_id_root.index, local_id };
578             let ftys = self.resolve(ftys, &hir_id);
579             self.tables.fru_field_types_mut().insert(hir_id, ftys);
580         }
581     }
582
583     fn resolve<T>(&self, x: &T, span: &dyn Locatable) -> T
584     where
585         T: TypeFoldable<'tcx>,
586     {
587         let x = x.fold_with(&mut Resolver::new(self.fcx, span, self.body));
588         if cfg!(debug_assertions) && x.has_local_value() {
589             span_bug!(span.to_span(self.fcx.tcx), "writeback: `{:?}` is a local value", x);
590         }
591         x
592     }
593 }
594
595 trait Locatable {
596     fn to_span(&self, tcx: TyCtxt<'_>) -> Span;
597 }
598
599 impl Locatable for Span {
600     fn to_span(&self, _: TyCtxt<'_>) -> Span {
601         *self
602     }
603 }
604
605 impl Locatable for DefIndex {
606     fn to_span(&self, tcx: TyCtxt<'_>) -> Span {
607         let hir_id = tcx.hir().def_index_to_hir_id(*self);
608         tcx.hir().span(hir_id)
609     }
610 }
611
612 impl Locatable for hir::HirId {
613     fn to_span(&self, tcx: TyCtxt<'_>) -> Span {
614         tcx.hir().span(*self)
615     }
616 }
617
618 ///////////////////////////////////////////////////////////////////////////
619 // The Resolver. This is the type folding engine that detects
620 // unresolved types and so forth.
621
622 struct Resolver<'cx, 'tcx> {
623     tcx: TyCtxt<'tcx>,
624     infcx: &'cx InferCtxt<'cx, 'tcx>,
625     span: &'cx dyn Locatable,
626     body: &'tcx hir::Body<'tcx>,
627 }
628
629 impl<'cx, 'tcx> Resolver<'cx, 'tcx> {
630     fn new(
631         fcx: &'cx FnCtxt<'cx, 'tcx>,
632         span: &'cx dyn Locatable,
633         body: &'tcx hir::Body<'tcx>,
634     ) -> Resolver<'cx, 'tcx> {
635         Resolver { tcx: fcx.tcx, infcx: fcx, span, body }
636     }
637
638     fn report_error(&self, t: Ty<'tcx>) {
639         if !self.tcx.sess.has_errors() {
640             self.infcx
641                 .need_type_info_err(Some(self.body.id()), self.span.to_span(self.tcx), t, E0282)
642                 .emit();
643         }
644     }
645 }
646
647 impl<'cx, 'tcx> TypeFolder<'tcx> for Resolver<'cx, 'tcx> {
648     fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
649         self.tcx
650     }
651
652     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
653         match self.infcx.fully_resolve(&t) {
654             Ok(t) => t,
655             Err(_) => {
656                 debug!("Resolver::fold_ty: input type `{:?}` not fully resolvable", t);
657                 self.report_error(t);
658                 self.tcx().types.err
659             }
660         }
661     }
662
663     // FIXME This should be carefully checked
664     // We could use `self.report_error` but it doesn't accept a ty::Region, right now.
665     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
666         self.infcx.fully_resolve(&r).unwrap_or(self.tcx.lifetimes.re_static)
667     }
668
669     fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
670         match self.infcx.fully_resolve(&ct) {
671             Ok(ct) => ct,
672             Err(_) => {
673                 debug!("Resolver::fold_const: input const `{:?}` not fully resolvable", ct);
674                 // FIXME: we'd like to use `self.report_error`, but it doesn't yet
675                 // accept a &'tcx ty::Const.
676                 self.tcx().consts.err
677             }
678         }
679     }
680 }
681
682 ///////////////////////////////////////////////////////////////////////////
683 // During type check, we store promises with the result of trait
684 // lookup rather than the actual results (because the results are not
685 // necessarily available immediately). These routines unwind the
686 // promises. It is expected that we will have already reported any
687 // errors that may be encountered, so if the promises store an error,
688 // a dummy result is returned.