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