]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/writeback.rs
Rollup merge of #67837 - GuillaumeGomez:clean-up-err-codes, r=Dylan-DPC
[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;
8 use rustc::hir::def_id::{DefId, DefIndex};
9 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
10 use rustc::infer::error_reporting::TypeAnnotationNeeded::E0282;
11 use rustc::infer::InferCtxt;
12 use rustc::ty::adjustment::{Adjust, Adjustment, PointerCast};
13 use rustc::ty::fold::{TypeFoldable, TypeFolder};
14 use rustc::ty::{self, Ty, TyCtxt};
15 use rustc::util::nodemap::DefIdSet;
16 use rustc_data_structures::sync::Lrc;
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::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_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     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
247         NestedVisitorMap::None
248     }
249
250     fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
251         self.fix_scalar_builtin_expr(e);
252         self.fix_index_builtin_expr(e);
253
254         self.visit_node_id(e.span, e.hir_id);
255
256         match e.kind {
257             hir::ExprKind::Closure(_, _, body, _, _) => {
258                 let body = self.fcx.tcx.hir().body(body);
259                 for param in body.params {
260                     self.visit_node_id(e.span, param.hir_id);
261                 }
262
263                 self.visit_body(body);
264             }
265             hir::ExprKind::Struct(_, fields, _) => {
266                 for field in fields {
267                     self.visit_field_id(field.hir_id);
268                 }
269             }
270             hir::ExprKind::Field(..) => {
271                 self.visit_field_id(e.hir_id);
272             }
273             _ => {}
274         }
275
276         intravisit::walk_expr(self, e);
277     }
278
279     fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) {
280         self.visit_node_id(b.span, b.hir_id);
281         intravisit::walk_block(self, b);
282     }
283
284     fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
285         match p.kind {
286             hir::PatKind::Binding(..) => {
287                 let tables = self.fcx.tables.borrow();
288                 if let Some(bm) = tables.extract_binding_mode(self.tcx().sess, p.hir_id, p.span) {
289                     self.tables.pat_binding_modes_mut().insert(p.hir_id, bm);
290                 }
291             }
292             hir::PatKind::Struct(_, fields, _) => {
293                 for field in fields {
294                     self.visit_field_id(field.hir_id);
295                 }
296             }
297             _ => {}
298         };
299
300         self.visit_pat_adjustments(p.span, p.hir_id);
301
302         self.visit_node_id(p.span, p.hir_id);
303         intravisit::walk_pat(self, p);
304     }
305
306     fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
307         intravisit::walk_local(self, l);
308         let var_ty = self.fcx.local_ty(l.span, l.hir_id).decl_ty;
309         let var_ty = self.resolve(&var_ty, &l.span);
310         self.write_ty_to_tables(l.hir_id, var_ty);
311     }
312
313     fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) {
314         intravisit::walk_ty(self, hir_ty);
315         let ty = self.fcx.node_ty(hir_ty.hir_id);
316         let ty = self.resolve(&ty, &hir_ty.span);
317         self.write_ty_to_tables(hir_ty.hir_id, ty);
318     }
319 }
320
321 impl<'cx, 'tcx> WritebackCx<'cx, '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 { kind: upvar_borrow.kind, region: r })
330                 }
331             };
332             debug!("Upvar capture for {:?} resolved to {:?}", upvar_id, new_upvar_capture);
333             self.tables.upvar_capture_map.insert(*upvar_id, new_upvar_capture);
334         }
335     }
336
337     fn visit_closures(&mut self) {
338         let fcx_tables = self.fcx.tables.borrow();
339         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
340         let common_local_id_root = fcx_tables.local_id_root.unwrap();
341
342         for (&id, &origin) in fcx_tables.closure_kind_origins().iter() {
343             let hir_id = hir::HirId { owner: common_local_id_root.index, local_id: id };
344             self.tables.closure_kind_origins_mut().insert(hir_id, origin);
345         }
346     }
347
348     fn visit_coercion_casts(&mut self) {
349         let fcx_tables = self.fcx.tables.borrow();
350         let fcx_coercion_casts = fcx_tables.coercion_casts();
351         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
352
353         for local_id in fcx_coercion_casts {
354             self.tables.set_coercion_cast(*local_id);
355         }
356     }
357
358     fn visit_free_region_map(&mut self) {
359         self.tables.free_region_map = self.fcx.tables.borrow().free_region_map.clone();
360         debug_assert!(!self.tables.free_region_map.elements().any(|r| r.has_local_value()));
361     }
362
363     fn visit_user_provided_tys(&mut self) {
364         let fcx_tables = self.fcx.tables.borrow();
365         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
366         let common_local_id_root = fcx_tables.local_id_root.unwrap();
367
368         let mut errors_buffer = Vec::new();
369         for (&local_id, c_ty) in fcx_tables.user_provided_types().iter() {
370             let hir_id = hir::HirId { owner: common_local_id_root.index, local_id };
371
372             if cfg!(debug_assertions) && c_ty.has_local_value() {
373                 span_bug!(hir_id.to_span(self.fcx.tcx), "writeback: `{:?}` is a local value", c_ty);
374             };
375
376             self.tables.user_provided_types_mut().insert(hir_id, c_ty.clone());
377
378             if let ty::UserType::TypeOf(_, user_substs) = c_ty.value {
379                 if self.rustc_dump_user_substs {
380                     // This is a unit-testing mechanism.
381                     let span = self.tcx().hir().span(hir_id);
382                     // We need to buffer the errors in order to guarantee a consistent
383                     // order when emitting them.
384                     let err = self
385                         .tcx()
386                         .sess
387                         .struct_span_err(span, &format!("user substs: {:?}", user_substs));
388                     err.buffer(&mut errors_buffer);
389                 }
390             }
391         }
392
393         if !errors_buffer.is_empty() {
394             errors_buffer.sort_by_key(|diag| diag.span.primary_span());
395             for diag in errors_buffer.drain(..) {
396                 self.tcx().sess.diagnostic().emit_diagnostic(&diag);
397             }
398         }
399     }
400
401     fn visit_user_provided_sigs(&mut self) {
402         let fcx_tables = self.fcx.tables.borrow();
403         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
404
405         for (&def_id, c_sig) in fcx_tables.user_provided_sigs.iter() {
406             if cfg!(debug_assertions) && c_sig.has_local_value() {
407                 span_bug!(
408                     self.fcx.tcx.hir().span_if_local(def_id).unwrap(),
409                     "writeback: `{:?}` is a local value",
410                     c_sig
411                 );
412             };
413
414             self.tables.user_provided_sigs.insert(def_id, c_sig.clone());
415         }
416     }
417
418     fn visit_generator_interior_types(&mut self) {
419         let fcx_tables = self.fcx.tables.borrow();
420         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
421         self.tables.generator_interior_types = fcx_tables.generator_interior_types.clone();
422     }
423
424     fn visit_opaque_types(&mut self, span: Span) {
425         for (&def_id, opaque_defn) in self.fcx.opaque_types.borrow().iter() {
426             let hir_id = self.tcx().hir().as_local_hir_id(def_id).unwrap();
427             let instantiated_ty = self.resolve(&opaque_defn.concrete_ty, &hir_id);
428
429             debug_assert!(!instantiated_ty.has_escaping_bound_vars());
430
431             // Prevent:
432             // * `fn foo<T>() -> Foo<T>`
433             // * `fn foo<T: Bound + Other>() -> Foo<T>`
434             // from being defining.
435
436             // Also replace all generic params with the ones from the opaque type
437             // definition so that
438             // ```rust
439             // type Foo<T> = impl Baz + 'static;
440             // fn foo<U>() -> Foo<U> { .. }
441             // ```
442             // figures out the concrete type with `U`, but the stored type is with `T`.
443             let definition_ty = self.fcx.infer_opaque_definition_from_instantiation(
444                 def_id,
445                 opaque_defn,
446                 instantiated_ty,
447                 span,
448             );
449
450             let mut skip_add = false;
451
452             if let ty::Opaque(defin_ty_def_id, _substs) = definition_ty.kind {
453                 if let hir::OpaqueTyOrigin::TypeAlias = opaque_defn.origin {
454                     if def_id == defin_ty_def_id {
455                         debug!(
456                             "skipping adding concrete definition for opaque type {:?} {:?}",
457                             opaque_defn, defin_ty_def_id
458                         );
459                         skip_add = true;
460                     }
461                 }
462             }
463
464             if !opaque_defn.substs.has_local_value() {
465                 // We only want to add an entry into `concrete_opaque_types`
466                 // if we actually found a defining usage of this opaque type.
467                 // Otherwise, we do nothing - we'll either find a defining usage
468                 // in some other location, or we'll end up emitting an error due
469                 // to the lack of defining usage
470                 if !skip_add {
471                     let new = ty::ResolvedOpaqueTy {
472                         concrete_type: definition_ty,
473                         substs: opaque_defn.substs,
474                     };
475
476                     let old = self.tables.concrete_opaque_types.insert(def_id, new);
477                     if let Some(old) = old {
478                         if old.concrete_type != definition_ty || old.substs != opaque_defn.substs {
479                             span_bug!(
480                                 span,
481                                 "`visit_opaque_types` tried to write different types for the same \
482                                  opaque type: {:?}, {:?}, {:?}, {:?}",
483                                 def_id,
484                                 definition_ty,
485                                 opaque_defn,
486                                 old,
487                             );
488                         }
489                     }
490                 }
491             } else {
492                 self.tcx().sess.delay_span_bug(span, "`opaque_defn` is a local value");
493             }
494         }
495     }
496
497     fn visit_field_id(&mut self, hir_id: hir::HirId) {
498         if let Some(index) = self.fcx.tables.borrow_mut().field_indices_mut().remove(hir_id) {
499             self.tables.field_indices_mut().insert(hir_id, index);
500         }
501     }
502
503     fn visit_node_id(&mut self, span: Span, hir_id: hir::HirId) {
504         // Export associated path extensions and method resolutions.
505         if let Some(def) = self.fcx.tables.borrow_mut().type_dependent_defs_mut().remove(hir_id) {
506             self.tables.type_dependent_defs_mut().insert(hir_id, def);
507         }
508
509         // Resolve any borrowings for the node with id `node_id`
510         self.visit_adjustments(span, hir_id);
511
512         // Resolve the type of the node with id `node_id`
513         let n_ty = self.fcx.node_ty(hir_id);
514         let n_ty = self.resolve(&n_ty, &span);
515         self.write_ty_to_tables(hir_id, n_ty);
516         debug!("node {:?} has type {:?}", hir_id, n_ty);
517
518         // Resolve any substitutions
519         if let Some(substs) = self.fcx.tables.borrow().node_substs_opt(hir_id) {
520             let substs = self.resolve(&substs, &span);
521             debug!("write_substs_to_tcx({:?}, {:?})", hir_id, substs);
522             assert!(!substs.needs_infer() && !substs.has_placeholders());
523             self.tables.node_substs_mut().insert(hir_id, substs);
524         }
525     }
526
527     fn visit_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
528         let adjustment = self.fcx.tables.borrow_mut().adjustments_mut().remove(hir_id);
529         match adjustment {
530             None => {
531                 debug!("no adjustments for node {:?}", hir_id);
532             }
533
534             Some(adjustment) => {
535                 let resolved_adjustment = self.resolve(&adjustment, &span);
536                 debug!("adjustments for node {:?}: {:?}", hir_id, resolved_adjustment);
537                 self.tables.adjustments_mut().insert(hir_id, resolved_adjustment);
538             }
539         }
540     }
541
542     fn visit_pat_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
543         let adjustment = self.fcx.tables.borrow_mut().pat_adjustments_mut().remove(hir_id);
544         match adjustment {
545             None => {
546                 debug!("no pat_adjustments for node {:?}", hir_id);
547             }
548
549             Some(adjustment) => {
550                 let resolved_adjustment = self.resolve(&adjustment, &span);
551                 debug!("pat_adjustments for node {:?}: {:?}", hir_id, resolved_adjustment);
552                 self.tables.pat_adjustments_mut().insert(hir_id, resolved_adjustment);
553             }
554         }
555     }
556
557     fn visit_liberated_fn_sigs(&mut self) {
558         let fcx_tables = self.fcx.tables.borrow();
559         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
560         let common_local_id_root = fcx_tables.local_id_root.unwrap();
561
562         for (&local_id, fn_sig) in fcx_tables.liberated_fn_sigs().iter() {
563             let hir_id = hir::HirId { owner: common_local_id_root.index, local_id };
564             let fn_sig = self.resolve(fn_sig, &hir_id);
565             self.tables.liberated_fn_sigs_mut().insert(hir_id, fn_sig.clone());
566         }
567     }
568
569     fn visit_fru_field_types(&mut self) {
570         let fcx_tables = self.fcx.tables.borrow();
571         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
572         let common_local_id_root = fcx_tables.local_id_root.unwrap();
573
574         for (&local_id, ftys) in fcx_tables.fru_field_types().iter() {
575             let hir_id = hir::HirId { owner: common_local_id_root.index, local_id };
576             let ftys = self.resolve(ftys, &hir_id);
577             self.tables.fru_field_types_mut().insert(hir_id, ftys);
578         }
579     }
580
581     fn resolve<T>(&self, x: &T, span: &dyn Locatable) -> T
582     where
583         T: TypeFoldable<'tcx>,
584     {
585         let x = x.fold_with(&mut Resolver::new(self.fcx, span, self.body));
586         if cfg!(debug_assertions) && x.has_local_value() {
587             span_bug!(span.to_span(self.fcx.tcx), "writeback: `{:?}` is a local value", x);
588         }
589         x
590     }
591 }
592
593 trait Locatable {
594     fn to_span(&self, tcx: TyCtxt<'_>) -> Span;
595 }
596
597 impl Locatable for Span {
598     fn to_span(&self, _: TyCtxt<'_>) -> Span {
599         *self
600     }
601 }
602
603 impl Locatable for DefIndex {
604     fn to_span(&self, tcx: TyCtxt<'_>) -> Span {
605         let hir_id = tcx.hir().def_index_to_hir_id(*self);
606         tcx.hir().span(hir_id)
607     }
608 }
609
610 impl Locatable for hir::HirId {
611     fn to_span(&self, tcx: TyCtxt<'_>) -> Span {
612         tcx.hir().span(*self)
613     }
614 }
615
616 ///////////////////////////////////////////////////////////////////////////
617 // The Resolver. This is the type folding engine that detects
618 // unresolved types and so forth.
619
620 struct Resolver<'cx, 'tcx> {
621     tcx: TyCtxt<'tcx>,
622     infcx: &'cx InferCtxt<'cx, 'tcx>,
623     span: &'cx dyn Locatable,
624     body: &'tcx hir::Body<'tcx>,
625 }
626
627 impl<'cx, 'tcx> Resolver<'cx, 'tcx> {
628     fn new(
629         fcx: &'cx FnCtxt<'cx, 'tcx>,
630         span: &'cx dyn Locatable,
631         body: &'tcx hir::Body<'tcx>,
632     ) -> Resolver<'cx, 'tcx> {
633         Resolver { tcx: fcx.tcx, infcx: fcx, span, body }
634     }
635
636     fn report_error(&self, t: Ty<'tcx>) {
637         if !self.tcx.sess.has_errors() {
638             self.infcx
639                 .need_type_info_err(Some(self.body.id()), self.span.to_span(self.tcx), t, E0282)
640                 .emit();
641         }
642     }
643 }
644
645 impl<'cx, 'tcx> TypeFolder<'tcx> for Resolver<'cx, 'tcx> {
646     fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
647         self.tcx
648     }
649
650     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
651         match self.infcx.fully_resolve(&t) {
652             Ok(t) => t,
653             Err(_) => {
654                 debug!("Resolver::fold_ty: input type `{:?}` not fully resolvable", t);
655                 self.report_error(t);
656                 self.tcx().types.err
657             }
658         }
659     }
660
661     // FIXME This should be carefully checked
662     // We could use `self.report_error` but it doesn't accept a ty::Region, right now.
663     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
664         self.infcx.fully_resolve(&r).unwrap_or(self.tcx.lifetimes.re_static)
665     }
666
667     fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
668         match self.infcx.fully_resolve(&ct) {
669             Ok(ct) => ct,
670             Err(_) => {
671                 debug!("Resolver::fold_const: input const `{:?}` not fully resolvable", ct);
672                 // FIXME: we'd like to use `self.report_error`, but it doesn't yet
673                 // accept a &'tcx ty::Const.
674                 self.tcx().consts.err
675             }
676         }
677     }
678 }
679
680 ///////////////////////////////////////////////////////////////////////////
681 // During type check, we store promises with the result of trait
682 // lookup rather than the actual results (because the results are not
683 // necessarily available immediately). These routines unwind the
684 // promises. It is expected that we will have already reported any
685 // errors that may be encountered, so if the promises store an error,
686 // a dummy result is returned.