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