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