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