]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/writeback.rs
Rollup merge of #99423 - GuillaumeGomez:group-css-font-rule, r=notriddle
[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 hir::def_id::LocalDefId;
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_errors::ErrorGuaranteed;
10 use rustc_hir as hir;
11 use rustc_hir::def_id::DefId;
12 use rustc_hir::intravisit::{self, Visitor};
13 use rustc_infer::infer::error_reporting::TypeAnnotationNeeded::E0282;
14 use rustc_infer::infer::InferCtxt;
15 use rustc_middle::hir::place::Place as HirPlace;
16 use rustc_middle::mir::FakeReadCause;
17 use rustc_middle::ty::adjustment::{Adjust, Adjustment, PointerCast};
18 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable};
19 use rustc_middle::ty::visit::{TypeSuperVisitable, TypeVisitable};
20 use rustc_middle::ty::{self, ClosureSizeProfileData, Ty, TyCtxt};
21 use rustc_span::symbol::sym;
22 use rustc_span::Span;
23
24 use std::mem;
25 use std::ops::ControlFlow;
26
27 ///////////////////////////////////////////////////////////////////////////
28 // Entry point
29
30 // During type inference, partially inferred types are
31 // represented using Type variables (ty::Infer). These don't appear in
32 // the final TypeckResults since all of the types should have been
33 // inferred once typeck is done.
34 // When type inference is running however, having to update the typeck
35 // typeck results every time a new type is inferred would be unreasonably slow,
36 // so instead all of the replacement happens at the end in
37 // resolve_type_vars_in_body, which creates a new TypeTables which
38 // doesn't contain any inference types.
39 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
40     pub fn resolve_type_vars_in_body(
41         &self,
42         body: &'tcx hir::Body<'tcx>,
43     ) -> &'tcx ty::TypeckResults<'tcx> {
44         let item_id = self.tcx.hir().body_owner(body.id());
45         let item_def_id = self.tcx.hir().local_def_id(item_id);
46
47         // This attribute causes us to dump some writeback information
48         // in the form of errors, which is used for unit tests.
49         let rustc_dump_user_substs =
50             self.tcx.has_attr(item_def_id.to_def_id(), sym::rustc_dump_user_substs);
51
52         let mut wbcx = WritebackCx::new(self, body, rustc_dump_user_substs);
53         for param in body.params {
54             wbcx.visit_node_id(param.pat.span, param.hir_id);
55         }
56         // Type only exists for constants and statics, not functions.
57         match self.tcx.hir().body_owner_kind(item_def_id) {
58             hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => {
59                 wbcx.visit_node_id(body.value.span, item_id);
60             }
61             hir::BodyOwnerKind::Closure | hir::BodyOwnerKind::Fn => (),
62         }
63         wbcx.visit_body(body);
64         wbcx.visit_min_capture_map();
65         wbcx.eval_closure_size();
66         wbcx.visit_fake_reads_map();
67         wbcx.visit_closures();
68         wbcx.visit_liberated_fn_sigs();
69         wbcx.visit_fru_field_types();
70         wbcx.visit_opaque_types();
71         wbcx.visit_coercion_casts();
72         wbcx.visit_user_provided_tys();
73         wbcx.visit_user_provided_sigs();
74         wbcx.visit_generator_interior_types();
75
76         wbcx.typeck_results.rvalue_scopes =
77             mem::take(&mut self.typeck_results.borrow_mut().rvalue_scopes);
78
79         let used_trait_imports =
80             mem::take(&mut self.typeck_results.borrow_mut().used_trait_imports);
81         debug!("used_trait_imports({:?}) = {:?}", item_def_id, used_trait_imports);
82         wbcx.typeck_results.used_trait_imports = used_trait_imports;
83
84         wbcx.typeck_results.treat_byte_string_as_slice =
85             mem::take(&mut self.typeck_results.borrow_mut().treat_byte_string_as_slice);
86
87         if self.is_tainted_by_errors() {
88             // FIXME(eddyb) keep track of `ErrorGuaranteed` from where the error was emitted.
89             wbcx.typeck_results.tainted_by_errors =
90                 Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
91         }
92
93         debug!("writeback: typeck results for {:?} are {:#?}", item_def_id, wbcx.typeck_results);
94
95         self.tcx.arena.alloc(wbcx.typeck_results)
96     }
97 }
98
99 ///////////////////////////////////////////////////////////////////////////
100 // The Writeback context. This visitor walks the HIR, checking the
101 // fn-specific typeck results to find references to types or regions. It
102 // resolves those regions to remove inference variables and writes the
103 // final result back into the master typeck results in the tcx. Here and
104 // there, it applies a few ad-hoc checks that were not convenient to
105 // do elsewhere.
106
107 struct WritebackCx<'cx, 'tcx> {
108     fcx: &'cx FnCtxt<'cx, 'tcx>,
109
110     typeck_results: ty::TypeckResults<'tcx>,
111
112     body: &'tcx hir::Body<'tcx>,
113
114     rustc_dump_user_substs: bool,
115 }
116
117 impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
118     fn new(
119         fcx: &'cx FnCtxt<'cx, 'tcx>,
120         body: &'tcx hir::Body<'tcx>,
121         rustc_dump_user_substs: bool,
122     ) -> WritebackCx<'cx, 'tcx> {
123         let owner = body.id().hir_id.owner;
124
125         WritebackCx {
126             fcx,
127             typeck_results: ty::TypeckResults::new(owner),
128             body,
129             rustc_dump_user_substs,
130         }
131     }
132
133     fn tcx(&self) -> TyCtxt<'tcx> {
134         self.fcx.tcx
135     }
136
137     fn write_ty_to_typeck_results(&mut self, hir_id: hir::HirId, ty: Ty<'tcx>) {
138         debug!("write_ty_to_typeck_results({:?}, {:?})", hir_id, ty);
139         assert!(!ty.needs_infer() && !ty.has_placeholders() && !ty.has_free_regions());
140         self.typeck_results.node_types_mut().insert(hir_id, ty);
141     }
142
143     // Hacky hack: During type-checking, we treat *all* operators
144     // as potentially overloaded. But then, during writeback, if
145     // we observe that something like `a+b` is (known to be)
146     // operating on scalars, we clear the overload.
147     fn fix_scalar_builtin_expr(&mut self, e: &hir::Expr<'_>) {
148         match e.kind {
149             hir::ExprKind::Unary(hir::UnOp::Neg | hir::UnOp::Not, inner) => {
150                 let inner_ty = self.fcx.node_ty(inner.hir_id);
151                 let inner_ty = self.fcx.resolve_vars_if_possible(inner_ty);
152
153                 if inner_ty.is_scalar() {
154                     let mut typeck_results = self.fcx.typeck_results.borrow_mut();
155                     typeck_results.type_dependent_defs_mut().remove(e.hir_id);
156                     typeck_results.node_substs_mut().remove(e.hir_id);
157                 }
158             }
159             hir::ExprKind::Binary(ref op, lhs, rhs) | hir::ExprKind::AssignOp(ref op, lhs, rhs) => {
160                 let lhs_ty = self.fcx.node_ty(lhs.hir_id);
161                 let lhs_ty = self.fcx.resolve_vars_if_possible(lhs_ty);
162
163                 let rhs_ty = self.fcx.node_ty(rhs.hir_id);
164                 let rhs_ty = self.fcx.resolve_vars_if_possible(rhs_ty);
165
166                 if lhs_ty.is_scalar() && rhs_ty.is_scalar() {
167                     let mut typeck_results = self.fcx.typeck_results.borrow_mut();
168                     typeck_results.type_dependent_defs_mut().remove(e.hir_id);
169                     typeck_results.node_substs_mut().remove(e.hir_id);
170
171                     match e.kind {
172                         hir::ExprKind::Binary(..) => {
173                             if !op.node.is_by_value() {
174                                 let mut adjustments = typeck_results.adjustments_mut();
175                                 if let Some(a) = adjustments.get_mut(lhs.hir_id) {
176                                     a.pop();
177                                 }
178                                 if let Some(a) = adjustments.get_mut(rhs.hir_id) {
179                                     a.pop();
180                                 }
181                             }
182                         }
183                         hir::ExprKind::AssignOp(..)
184                             if let Some(a) = typeck_results.adjustments_mut().get_mut(lhs.hir_id) =>
185                         {
186                             a.pop();
187                         }
188                         _ => {}
189                     }
190                 }
191             }
192             _ => {}
193         }
194     }
195
196     // Similar to operators, indexing is always assumed to be overloaded
197     // Here, correct cases where an indexing expression can be simplified
198     // to use builtin indexing because the index type is known to be
199     // usize-ish
200     fn fix_index_builtin_expr(&mut self, e: &hir::Expr<'_>) {
201         if let hir::ExprKind::Index(ref base, ref index) = e.kind {
202             let mut typeck_results = self.fcx.typeck_results.borrow_mut();
203
204             // All valid indexing looks like this; might encounter non-valid indexes at this point.
205             let base_ty = typeck_results
206                 .expr_ty_adjusted_opt(base)
207                 .map(|t| self.fcx.resolve_vars_if_possible(t).kind());
208             if base_ty.is_none() {
209                 // When encountering `return [0][0]` outside of a `fn` body we can encounter a base
210                 // that isn't in the type table. We assume more relevant errors have already been
211                 // emitted, so we delay an ICE if none have. (#64638)
212                 self.tcx().sess.delay_span_bug(e.span, &format!("bad base: `{:?}`", base));
213             }
214             if let Some(ty::Ref(_, base_ty, _)) = base_ty {
215                 let index_ty = typeck_results.expr_ty_adjusted_opt(index).unwrap_or_else(|| {
216                     // When encountering `return [0][0]` outside of a `fn` body we would attempt
217                     // to access an nonexistent index. We assume that more relevant errors will
218                     // already have been emitted, so we only gate on this with an ICE if no
219                     // error has been emitted. (#64638)
220                     self.fcx.tcx.ty_error_with_message(
221                         e.span,
222                         &format!("bad index {:?} for base: `{:?}`", index, base),
223                     )
224                 });
225                 let index_ty = self.fcx.resolve_vars_if_possible(index_ty);
226
227                 if base_ty.builtin_index().is_some() && index_ty == self.fcx.tcx.types.usize {
228                     // Remove the method call record
229                     typeck_results.type_dependent_defs_mut().remove(e.hir_id);
230                     typeck_results.node_substs_mut().remove(e.hir_id);
231
232                     if let Some(a) = typeck_results.adjustments_mut().get_mut(base.hir_id) {
233                         // Discard the need for a mutable borrow
234
235                         // Extra adjustment made when indexing causes a drop
236                         // of size information - we need to get rid of it
237                         // Since this is "after" the other adjustment to be
238                         // discarded, we do an extra `pop()`
239                         if let Some(Adjustment {
240                             kind: Adjust::Pointer(PointerCast::Unsize), ..
241                         }) = a.pop()
242                         {
243                             // So the borrow discard actually happens here
244                             a.pop();
245                         }
246                     }
247                 }
248             }
249         }
250     }
251 }
252
253 ///////////////////////////////////////////////////////////////////////////
254 // Impl of Visitor for Resolver
255 //
256 // This is the master code which walks the AST. It delegates most of
257 // the heavy lifting to the generic visit and resolve functions
258 // below. In general, a function is made into a `visitor` if it must
259 // traffic in node-ids or update typeck results in the type context etc.
260
261 impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> {
262     fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
263         self.fix_scalar_builtin_expr(e);
264         self.fix_index_builtin_expr(e);
265
266         match e.kind {
267             hir::ExprKind::Closure(&hir::Closure { body, .. }) => {
268                 let body = self.fcx.tcx.hir().body(body);
269                 for param in body.params {
270                     self.visit_node_id(e.span, param.hir_id);
271                 }
272
273                 self.visit_body(body);
274             }
275             hir::ExprKind::Struct(_, fields, _) => {
276                 for field in fields {
277                     self.visit_field_id(field.hir_id);
278                 }
279             }
280             hir::ExprKind::Field(..) => {
281                 self.visit_field_id(e.hir_id);
282             }
283             hir::ExprKind::ConstBlock(anon_const) => {
284                 self.visit_node_id(e.span, anon_const.hir_id);
285
286                 let body = self.tcx().hir().body(anon_const.body);
287                 self.visit_body(body);
288             }
289             _ => {}
290         }
291
292         self.visit_node_id(e.span, e.hir_id);
293         intravisit::walk_expr(self, e);
294     }
295
296     fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) {
297         self.visit_node_id(b.span, b.hir_id);
298         intravisit::walk_block(self, b);
299     }
300
301     fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
302         match p.kind {
303             hir::PatKind::Binding(..) => {
304                 let typeck_results = self.fcx.typeck_results.borrow();
305                 if let Some(bm) =
306                     typeck_results.extract_binding_mode(self.tcx().sess, p.hir_id, p.span)
307                 {
308                     self.typeck_results.pat_binding_modes_mut().insert(p.hir_id, bm);
309                 }
310             }
311             hir::PatKind::Struct(_, fields, _) => {
312                 for field in fields {
313                     self.visit_field_id(field.hir_id);
314                 }
315             }
316             _ => {}
317         };
318
319         self.visit_pat_adjustments(p.span, p.hir_id);
320
321         self.visit_node_id(p.span, p.hir_id);
322         intravisit::walk_pat(self, p);
323     }
324
325     fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
326         intravisit::walk_local(self, l);
327         let var_ty = self.fcx.local_ty(l.span, l.hir_id).decl_ty;
328         let var_ty = self.resolve(var_ty, &l.span);
329         self.write_ty_to_typeck_results(l.hir_id, var_ty);
330     }
331
332     fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) {
333         intravisit::walk_ty(self, hir_ty);
334         let ty = self.fcx.node_ty(hir_ty.hir_id);
335         let ty = self.resolve(ty, &hir_ty.span);
336         self.write_ty_to_typeck_results(hir_ty.hir_id, ty);
337     }
338
339     fn visit_infer(&mut self, inf: &'tcx hir::InferArg) {
340         intravisit::walk_inf(self, inf);
341         // Ignore cases where the inference is a const.
342         if let Some(ty) = self.fcx.node_ty_opt(inf.hir_id) {
343             let ty = self.resolve(ty, &inf.span);
344             self.write_ty_to_typeck_results(inf.hir_id, ty);
345         }
346     }
347 }
348
349 impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
350     fn eval_closure_size(&mut self) {
351         let mut res: FxHashMap<DefId, ClosureSizeProfileData<'tcx>> = Default::default();
352         for (closure_def_id, data) in self.fcx.typeck_results.borrow().closure_size_eval.iter() {
353             let closure_hir_id =
354                 self.tcx().hir().local_def_id_to_hir_id(closure_def_id.expect_local());
355
356             let data = self.resolve(*data, &closure_hir_id);
357
358             res.insert(*closure_def_id, data);
359         }
360
361         self.typeck_results.closure_size_eval = res;
362     }
363     fn visit_min_capture_map(&mut self) {
364         let mut min_captures_wb = ty::MinCaptureInformationMap::with_capacity_and_hasher(
365             self.fcx.typeck_results.borrow().closure_min_captures.len(),
366             Default::default(),
367         );
368         for (closure_def_id, root_min_captures) in
369             self.fcx.typeck_results.borrow().closure_min_captures.iter()
370         {
371             let mut root_var_map_wb = ty::RootVariableMinCaptureList::with_capacity_and_hasher(
372                 root_min_captures.len(),
373                 Default::default(),
374             );
375             for (var_hir_id, min_list) in root_min_captures.iter() {
376                 let min_list_wb = min_list
377                     .iter()
378                     .map(|captured_place| {
379                         let locatable = captured_place.info.path_expr_id.unwrap_or_else(|| {
380                             self.tcx().hir().local_def_id_to_hir_id(closure_def_id.expect_local())
381                         });
382
383                         self.resolve(captured_place.clone(), &locatable)
384                     })
385                     .collect();
386                 root_var_map_wb.insert(*var_hir_id, min_list_wb);
387             }
388             min_captures_wb.insert(*closure_def_id, root_var_map_wb);
389         }
390
391         self.typeck_results.closure_min_captures = min_captures_wb;
392     }
393
394     fn visit_fake_reads_map(&mut self) {
395         let mut resolved_closure_fake_reads: FxHashMap<
396             DefId,
397             Vec<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>,
398         > = Default::default();
399         for (closure_def_id, fake_reads) in
400             self.fcx.typeck_results.borrow().closure_fake_reads.iter()
401         {
402             let mut resolved_fake_reads = Vec::<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>::new();
403             for (place, cause, hir_id) in fake_reads.iter() {
404                 let locatable =
405                     self.tcx().hir().local_def_id_to_hir_id(closure_def_id.expect_local());
406
407                 let resolved_fake_read = self.resolve(place.clone(), &locatable);
408                 resolved_fake_reads.push((resolved_fake_read, *cause, *hir_id));
409             }
410             resolved_closure_fake_reads.insert(*closure_def_id, resolved_fake_reads);
411         }
412         self.typeck_results.closure_fake_reads = resolved_closure_fake_reads;
413     }
414
415     fn visit_closures(&mut self) {
416         let fcx_typeck_results = self.fcx.typeck_results.borrow();
417         assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
418         let common_hir_owner = fcx_typeck_results.hir_owner;
419
420         for (id, origin) in fcx_typeck_results.closure_kind_origins().iter() {
421             let hir_id = hir::HirId { owner: common_hir_owner, local_id: *id };
422             let place_span = origin.0;
423             let place = self.resolve(origin.1.clone(), &place_span);
424             self.typeck_results.closure_kind_origins_mut().insert(hir_id, (place_span, place));
425         }
426     }
427
428     fn visit_coercion_casts(&mut self) {
429         let fcx_typeck_results = self.fcx.typeck_results.borrow();
430         let fcx_coercion_casts = fcx_typeck_results.coercion_casts();
431         assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
432
433         for local_id in fcx_coercion_casts {
434             self.typeck_results.set_coercion_cast(*local_id);
435         }
436     }
437
438     fn visit_user_provided_tys(&mut self) {
439         let fcx_typeck_results = self.fcx.typeck_results.borrow();
440         assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
441         let common_hir_owner = fcx_typeck_results.hir_owner;
442
443         let mut errors_buffer = Vec::new();
444         for (&local_id, c_ty) in fcx_typeck_results.user_provided_types().iter() {
445             let hir_id = hir::HirId { owner: common_hir_owner, local_id };
446
447             if cfg!(debug_assertions) && c_ty.needs_infer() {
448                 span_bug!(
449                     hir_id.to_span(self.fcx.tcx),
450                     "writeback: `{:?}` has inference variables",
451                     c_ty
452                 );
453             };
454
455             self.typeck_results.user_provided_types_mut().insert(hir_id, *c_ty);
456
457             if let ty::UserType::TypeOf(_, user_substs) = c_ty.value {
458                 if self.rustc_dump_user_substs {
459                     // This is a unit-testing mechanism.
460                     let span = self.tcx().hir().span(hir_id);
461                     // We need to buffer the errors in order to guarantee a consistent
462                     // order when emitting them.
463                     let err = self
464                         .tcx()
465                         .sess
466                         .struct_span_err(span, &format!("user substs: {:?}", user_substs));
467                     err.buffer(&mut errors_buffer);
468                 }
469             }
470         }
471
472         if !errors_buffer.is_empty() {
473             errors_buffer.sort_by_key(|diag| diag.span.primary_span());
474             for mut diag in errors_buffer.drain(..) {
475                 self.tcx().sess.diagnostic().emit_diagnostic(&mut diag);
476             }
477         }
478     }
479
480     fn visit_user_provided_sigs(&mut self) {
481         let fcx_typeck_results = self.fcx.typeck_results.borrow();
482         assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
483
484         for (&def_id, c_sig) in fcx_typeck_results.user_provided_sigs.iter() {
485             if cfg!(debug_assertions) && c_sig.needs_infer() {
486                 span_bug!(
487                     self.fcx.tcx.hir().span_if_local(def_id).unwrap(),
488                     "writeback: `{:?}` has inference variables",
489                     c_sig
490                 );
491             };
492
493             self.typeck_results.user_provided_sigs.insert(def_id, *c_sig);
494         }
495     }
496
497     fn visit_generator_interior_types(&mut self) {
498         let fcx_typeck_results = self.fcx.typeck_results.borrow();
499         assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
500         self.typeck_results.generator_interior_types =
501             fcx_typeck_results.generator_interior_types.clone();
502     }
503
504     #[instrument(skip(self), level = "debug")]
505     fn visit_opaque_types(&mut self) {
506         let opaque_types =
507             self.fcx.infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
508         for (opaque_type_key, decl) in opaque_types {
509             let hidden_type = match decl.origin {
510                 hir::OpaqueTyOrigin::FnReturn(_) | hir::OpaqueTyOrigin::AsyncFn(_) => {
511                     let ty = self.resolve(decl.hidden_type.ty, &decl.hidden_type.span);
512                     struct RecursionChecker {
513                         def_id: LocalDefId,
514                     }
515                     impl<'tcx> ty::TypeVisitor<'tcx> for RecursionChecker {
516                         type BreakTy = ();
517                         fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
518                             if let ty::Opaque(def_id, _) = *t.kind() {
519                                 if def_id == self.def_id.to_def_id() {
520                                     return ControlFlow::Break(());
521                                 }
522                             }
523                             t.super_visit_with(self)
524                         }
525                     }
526                     if ty
527                         .visit_with(&mut RecursionChecker { def_id: opaque_type_key.def_id })
528                         .is_break()
529                     {
530                         return;
531                     }
532                     Some(ty)
533                 }
534                 hir::OpaqueTyOrigin::TyAlias => None,
535             };
536             self.typeck_results.concrete_opaque_types.insert(opaque_type_key.def_id, hidden_type);
537         }
538     }
539
540     fn visit_field_id(&mut self, hir_id: hir::HirId) {
541         if let Some(index) = self.fcx.typeck_results.borrow_mut().field_indices_mut().remove(hir_id)
542         {
543             self.typeck_results.field_indices_mut().insert(hir_id, index);
544         }
545     }
546
547     #[instrument(skip(self, span), level = "debug")]
548     fn visit_node_id(&mut self, span: Span, hir_id: hir::HirId) {
549         // Export associated path extensions and method resolutions.
550         if let Some(def) =
551             self.fcx.typeck_results.borrow_mut().type_dependent_defs_mut().remove(hir_id)
552         {
553             self.typeck_results.type_dependent_defs_mut().insert(hir_id, def);
554         }
555
556         // Resolve any borrowings for the node with id `node_id`
557         self.visit_adjustments(span, hir_id);
558
559         // Resolve the type of the node with id `node_id`
560         let n_ty = self.fcx.node_ty(hir_id);
561         let n_ty = self.resolve(n_ty, &span);
562         self.write_ty_to_typeck_results(hir_id, n_ty);
563         debug!(?n_ty);
564
565         // Resolve any substitutions
566         if let Some(substs) = self.fcx.typeck_results.borrow().node_substs_opt(hir_id) {
567             let substs = self.resolve(substs, &span);
568             debug!("write_substs_to_tcx({:?}, {:?})", hir_id, substs);
569             assert!(!substs.needs_infer() && !substs.has_placeholders());
570             self.typeck_results.node_substs_mut().insert(hir_id, substs);
571         }
572     }
573
574     #[instrument(skip(self, span), level = "debug")]
575     fn visit_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
576         let adjustment = self.fcx.typeck_results.borrow_mut().adjustments_mut().remove(hir_id);
577         match adjustment {
578             None => {
579                 debug!("no adjustments for node");
580             }
581
582             Some(adjustment) => {
583                 let resolved_adjustment = self.resolve(adjustment, &span);
584                 debug!(?resolved_adjustment);
585                 self.typeck_results.adjustments_mut().insert(hir_id, resolved_adjustment);
586             }
587         }
588     }
589
590     #[instrument(skip(self, span), level = "debug")]
591     fn visit_pat_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
592         let adjustment = self.fcx.typeck_results.borrow_mut().pat_adjustments_mut().remove(hir_id);
593         match adjustment {
594             None => {
595                 debug!("no pat_adjustments for node");
596             }
597
598             Some(adjustment) => {
599                 let resolved_adjustment = self.resolve(adjustment, &span);
600                 debug!(?resolved_adjustment);
601                 self.typeck_results.pat_adjustments_mut().insert(hir_id, resolved_adjustment);
602             }
603         }
604     }
605
606     fn visit_liberated_fn_sigs(&mut self) {
607         let fcx_typeck_results = self.fcx.typeck_results.borrow();
608         assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
609         let common_hir_owner = fcx_typeck_results.hir_owner;
610
611         for (&local_id, &fn_sig) in fcx_typeck_results.liberated_fn_sigs().iter() {
612             let hir_id = hir::HirId { owner: common_hir_owner, local_id };
613             let fn_sig = self.resolve(fn_sig, &hir_id);
614             self.typeck_results.liberated_fn_sigs_mut().insert(hir_id, fn_sig);
615         }
616     }
617
618     fn visit_fru_field_types(&mut self) {
619         let fcx_typeck_results = self.fcx.typeck_results.borrow();
620         assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
621         let common_hir_owner = fcx_typeck_results.hir_owner;
622
623         for (&local_id, ftys) in fcx_typeck_results.fru_field_types().iter() {
624             let hir_id = hir::HirId { owner: common_hir_owner, local_id };
625             let ftys = self.resolve(ftys.clone(), &hir_id);
626             self.typeck_results.fru_field_types_mut().insert(hir_id, ftys);
627         }
628     }
629
630     fn resolve<T>(&mut self, x: T, span: &dyn Locatable) -> T
631     where
632         T: TypeFoldable<'tcx>,
633     {
634         let mut resolver = Resolver::new(self.fcx, span, self.body);
635         let x = x.fold_with(&mut resolver);
636         if cfg!(debug_assertions) && x.needs_infer() {
637             span_bug!(span.to_span(self.fcx.tcx), "writeback: `{:?}` has inference variables", x);
638         }
639
640         // We may have introduced e.g. `ty::Error`, if inference failed, make sure
641         // to mark the `TypeckResults` as tainted in that case, so that downstream
642         // users of the typeck results don't produce extra errors, or worse, ICEs.
643         if resolver.replaced_with_error {
644             // FIXME(eddyb) keep track of `ErrorGuaranteed` from where the error was emitted.
645             self.typeck_results.tainted_by_errors =
646                 Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
647         }
648
649         x
650     }
651 }
652
653 pub(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 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     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().is_some() {
692             self.infcx
693                 .emit_inference_failure_err(
694                     Some(self.body.id()),
695                     self.span.to_span(self.tcx),
696                     t.into(),
697                     E0282,
698                     false,
699                 )
700                 .emit();
701         }
702     }
703
704     fn report_const_error(&self, c: ty::Const<'tcx>) {
705         if self.tcx.sess.has_errors().is_none() {
706             self.infcx
707                 .emit_inference_failure_err(
708                     Some(self.body.id()),
709                     self.span.to_span(self.tcx),
710                     c.into(),
711                     E0282,
712                     false,
713                 )
714                 .emit();
715         }
716     }
717 }
718
719 struct EraseEarlyRegions<'tcx> {
720     tcx: TyCtxt<'tcx>,
721 }
722
723 impl<'tcx> TypeFolder<'tcx> for EraseEarlyRegions<'tcx> {
724     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
725         self.tcx
726     }
727     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
728         if ty.has_type_flags(ty::TypeFlags::HAS_FREE_REGIONS) {
729             ty.super_fold_with(self)
730         } else {
731             ty
732         }
733     }
734     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
735         if r.is_late_bound() { r } else { self.tcx.lifetimes.re_erased }
736     }
737 }
738
739 impl<'cx, 'tcx> TypeFolder<'tcx> for Resolver<'cx, 'tcx> {
740     fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
741         self.tcx
742     }
743
744     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
745         match self.infcx.fully_resolve(t) {
746             Ok(t) => {
747                 // Do not anonymize late-bound regions
748                 // (e.g. keep `for<'a>` named `for<'a>`).
749                 // This allows NLL to generate error messages that
750                 // refer to the higher-ranked lifetime names written by the user.
751                 EraseEarlyRegions { tcx: self.infcx.tcx }.fold_ty(t)
752             }
753             Err(_) => {
754                 debug!("Resolver::fold_ty: input type `{:?}` not fully resolvable", t);
755                 self.report_type_error(t);
756                 self.replaced_with_error = true;
757                 self.tcx().ty_error()
758             }
759         }
760     }
761
762     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
763         debug_assert!(!r.is_late_bound(), "Should not be resolving bound region.");
764         self.tcx.lifetimes.re_erased
765     }
766
767     fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
768         match self.infcx.fully_resolve(ct) {
769             Ok(ct) => self.infcx.tcx.erase_regions(ct),
770             Err(_) => {
771                 debug!("Resolver::fold_const: input const `{:?}` not fully resolvable", ct);
772                 self.report_const_error(ct);
773                 self.replaced_with_error = true;
774                 self.tcx().const_error(ct.ty())
775             }
776         }
777     }
778 }
779
780 ///////////////////////////////////////////////////////////////////////////
781 // During type check, we store promises with the result of trait
782 // lookup rather than the actual results (because the results are not
783 // necessarily available immediately). These routines unwind the
784 // promises. It is expected that we will have already reported any
785 // errors that may be encountered, so if the promises store an error,
786 // a dummy result is returned.