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