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