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