rustc_hir_typeck/
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// generic parameters.
4
5use std::mem;
6
7use rustc_data_structures::unord::ExtendUnord;
8use rustc_errors::ErrorGuaranteed;
9use rustc_hir::intravisit::{self, InferKind, Visitor};
10use rustc_hir::{self as hir, AmbigArg, HirId};
11use rustc_middle::span_bug;
12use rustc_middle::traits::ObligationCause;
13use rustc_middle::ty::adjustment::{Adjust, Adjustment, PointerCoercion};
14use rustc_middle::ty::{
15    self, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, fold_regions,
16};
17use rustc_span::{Span, sym};
18use rustc_trait_selection::error_reporting::infer::need_type_info::TypeAnnotationNeeded;
19use rustc_trait_selection::solve;
20use tracing::{debug, instrument};
21
22use crate::FnCtxt;
23
24///////////////////////////////////////////////////////////////////////////
25// Entry point
26
27// During type inference, partially inferred types are
28// represented using Type variables (ty::Infer). These don't appear in
29// the final TypeckResults since all of the types should have been
30// inferred once typeck is done.
31// When type inference is running however, having to update the typeck
32// typeck results every time a new type is inferred would be unreasonably slow,
33// so instead all of the replacement happens at the end in
34// resolve_type_vars_in_body, which creates a new TypeTables which
35// doesn't contain any inference types.
36impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
37    pub(crate) fn resolve_type_vars_in_body(
38        &self,
39        body: &'tcx hir::Body<'tcx>,
40    ) -> &'tcx ty::TypeckResults<'tcx> {
41        let item_def_id = self.tcx.hir_body_owner_def_id(body.id());
42
43        // This attribute causes us to dump some writeback information
44        // in the form of errors, which is used for unit tests.
45        let rustc_dump_user_args = self.tcx.has_attr(item_def_id, sym::rustc_dump_user_args);
46
47        let mut wbcx = WritebackCx::new(self, body, rustc_dump_user_args);
48        for param in body.params {
49            wbcx.visit_node_id(param.pat.span, param.hir_id);
50        }
51        match self.tcx.hir_body_owner_kind(item_def_id) {
52            // Visit the type of a const or static, which is used during THIR building.
53            hir::BodyOwnerKind::Const { .. }
54            | hir::BodyOwnerKind::Static(_)
55            | hir::BodyOwnerKind::GlobalAsm => {
56                let item_hir_id = self.tcx.local_def_id_to_hir_id(item_def_id);
57                wbcx.visit_node_id(body.value.span, item_hir_id);
58            }
59            // For closures and consts, we already plan to visit liberated signatures.
60            hir::BodyOwnerKind::Closure | hir::BodyOwnerKind::Fn => {}
61        }
62        wbcx.visit_body(body);
63        wbcx.visit_min_capture_map();
64        wbcx.eval_closure_size();
65        wbcx.visit_fake_reads_map();
66        wbcx.visit_closures();
67        wbcx.visit_liberated_fn_sigs();
68        wbcx.visit_fru_field_types();
69        wbcx.visit_opaque_types();
70        wbcx.visit_coercion_casts();
71        wbcx.visit_user_provided_tys();
72        wbcx.visit_user_provided_sigs();
73        wbcx.visit_coroutine_interior();
74        wbcx.visit_offset_of_container_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        debug!("writeback: typeck results for {:?} are {:#?}", item_def_id, wbcx.typeck_results);
88
89        self.tcx.arena.alloc(wbcx.typeck_results)
90    }
91}
92
93///////////////////////////////////////////////////////////////////////////
94// The Writeback context. This visitor walks the HIR, checking the
95// fn-specific typeck results to find references to types or regions. It
96// resolves those regions to remove inference variables and writes the
97// final result back into the master typeck results in the tcx. Here and
98// there, it applies a few ad-hoc checks that were not convenient to
99// do elsewhere.
100
101struct WritebackCx<'cx, 'tcx> {
102    fcx: &'cx FnCtxt<'cx, 'tcx>,
103
104    typeck_results: ty::TypeckResults<'tcx>,
105
106    body: &'tcx hir::Body<'tcx>,
107
108    rustc_dump_user_args: bool,
109}
110
111impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
112    fn new(
113        fcx: &'cx FnCtxt<'cx, 'tcx>,
114        body: &'tcx hir::Body<'tcx>,
115        rustc_dump_user_args: bool,
116    ) -> WritebackCx<'cx, 'tcx> {
117        let owner = body.id().hir_id.owner;
118
119        let mut wbcx = WritebackCx {
120            fcx,
121            typeck_results: ty::TypeckResults::new(owner),
122            body,
123            rustc_dump_user_args,
124        };
125
126        // HACK: We specifically don't want the (opaque) error from tainting our
127        // inference context. That'll prevent us from doing opaque type inference
128        // later on in borrowck, which affects diagnostic spans pretty negatively.
129        if let Some(e) = fcx.tainted_by_errors() {
130            wbcx.typeck_results.tainted_by_errors = Some(e);
131        }
132
133        wbcx
134    }
135
136    fn tcx(&self) -> TyCtxt<'tcx> {
137        self.fcx.tcx
138    }
139
140    fn write_ty_to_typeck_results(&mut self, hir_id: HirId, ty: Ty<'tcx>) {
141        debug!("write_ty_to_typeck_results({:?}, {:?})", hir_id, ty);
142        assert!(
143            !ty.has_infer() && !ty.has_placeholders() && !ty.has_free_regions(),
144            "{ty} can't be put into typeck results"
145        );
146        self.typeck_results.node_types_mut().insert(hir_id, ty);
147    }
148
149    // Hacky hack: During type-checking, we treat *all* operators
150    // as potentially overloaded. But then, during writeback, if
151    // we observe that something like `a+b` is (known to be)
152    // operating on scalars, we clear the overload.
153    fn fix_scalar_builtin_expr(&mut self, e: &hir::Expr<'_>) {
154        match e.kind {
155            hir::ExprKind::Unary(hir::UnOp::Neg | hir::UnOp::Not, inner) => {
156                let inner_ty = self.typeck_results.node_type(inner.hir_id);
157
158                if inner_ty.is_scalar() {
159                    self.typeck_results.type_dependent_defs_mut().remove(e.hir_id);
160                    self.typeck_results.node_args_mut().remove(e.hir_id);
161                }
162            }
163            hir::ExprKind::Binary(ref op, lhs, rhs) | hir::ExprKind::AssignOp(ref op, lhs, rhs) => {
164                let lhs_ty = self.typeck_results.node_type(lhs.hir_id);
165                let rhs_ty = self.typeck_results.node_type(rhs.hir_id);
166
167                if lhs_ty.is_scalar() && rhs_ty.is_scalar() {
168                    self.typeck_results.type_dependent_defs_mut().remove(e.hir_id);
169                    self.typeck_results.node_args_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 = self.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) =
185                                self.typeck_results.adjustments_mut().get_mut(lhs.hir_id) =>
186                        {
187                            a.pop();
188                        }
189                        _ => {}
190                    }
191                }
192            }
193            _ => {}
194        }
195    }
196
197    // (ouz-a 1005988): Normally `[T] : std::ops::Index<usize>` should be normalized
198    // into [T] but currently `Where` clause stops the normalization process for it,
199    // here we compare types of expr and base in a code without `Where` clause they would be equal
200    // if they are not we don't modify the expr, hence we bypass the ICE
201    fn is_builtin_index(
202        &mut self,
203        e: &hir::Expr<'_>,
204        base_ty: Ty<'tcx>,
205        index_ty: Ty<'tcx>,
206    ) -> bool {
207        if let Some(elem_ty) = base_ty.builtin_index()
208            && let Some(exp_ty) = self.typeck_results.expr_ty_opt(e)
209        {
210            elem_ty == exp_ty && index_ty == self.fcx.tcx.types.usize
211        } else {
212            false
213        }
214    }
215
216    // Similar to operators, indexing is always assumed to be overloaded
217    // Here, correct cases where an indexing expression can be simplified
218    // to use builtin indexing because the index type is known to be
219    // usize-ish
220    fn fix_index_builtin_expr(&mut self, e: &hir::Expr<'_>) {
221        if let hir::ExprKind::Index(ref base, ref index, _) = e.kind {
222            // All valid indexing looks like this; might encounter non-valid indexes at this point.
223            let base_ty = self.typeck_results.expr_ty_adjusted(base);
224            if let ty::Ref(_, base_ty_inner, _) = *base_ty.kind() {
225                let index_ty = self.typeck_results.expr_ty_adjusted(index);
226                if self.is_builtin_index(e, base_ty_inner, index_ty) {
227                    // Remove the method call record
228                    self.typeck_results.type_dependent_defs_mut().remove(e.hir_id);
229                    self.typeck_results.node_args_mut().remove(e.hir_id);
230
231                    if let Some(a) = self.typeck_results.adjustments_mut().get_mut(base.hir_id) {
232                        // Discard the need for a mutable borrow
233
234                        // Extra adjustment made when indexing causes a drop
235                        // of size information - we need to get rid of it
236                        // Since this is "after" the other adjustment to be
237                        // discarded, we do an extra `pop()`
238                        if let Some(Adjustment {
239                            kind: Adjust::Pointer(PointerCoercion::Unsize),
240                            ..
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
261impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> {
262    fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
263        match e.kind {
264            hir::ExprKind::Closure(&hir::Closure { body, .. }) => {
265                let body = self.fcx.tcx.hir_body(body);
266                for param in body.params {
267                    self.visit_node_id(e.span, param.hir_id);
268                }
269
270                self.visit_body(body);
271            }
272            hir::ExprKind::Struct(_, fields, _) => {
273                for field in fields {
274                    self.visit_field_id(field.hir_id);
275                }
276            }
277            hir::ExprKind::Field(..) | hir::ExprKind::OffsetOf(..) => {
278                self.visit_field_id(e.hir_id);
279            }
280            _ => {}
281        }
282
283        self.visit_node_id(e.span, e.hir_id);
284        intravisit::walk_expr(self, e);
285
286        self.fix_scalar_builtin_expr(e);
287        self.fix_index_builtin_expr(e);
288    }
289
290    fn visit_inline_const(&mut self, anon_const: &hir::ConstBlock) {
291        let span = self.tcx().def_span(anon_const.def_id);
292        self.visit_node_id(span, anon_const.hir_id);
293
294        let body = self.tcx().hir_body(anon_const.body);
295        self.visit_body(body);
296    }
297
298    fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
299        match &p.kind {
300            hir::GenericParamKind::Lifetime { .. } => {
301                // Nothing to write back here
302            }
303            hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => {
304                self.tcx()
305                    .dcx()
306                    .span_delayed_bug(p.span, format!("unexpected generic param: {p:?}"));
307            }
308        }
309    }
310
311    fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) {
312        self.visit_node_id(b.span, b.hir_id);
313        intravisit::walk_block(self, b);
314    }
315
316    fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
317        match p.kind {
318            hir::PatKind::Binding(..) => {
319                let typeck_results = self.fcx.typeck_results.borrow();
320                let bm = typeck_results.extract_binding_mode(self.tcx().sess, p.hir_id, p.span);
321                self.typeck_results.pat_binding_modes_mut().insert(p.hir_id, bm);
322            }
323            hir::PatKind::Struct(_, fields, _) => {
324                for field in fields {
325                    self.visit_field_id(field.hir_id);
326                }
327            }
328            _ => {}
329        };
330
331        self.visit_rust_2024_migration_desugared_pats(p.hir_id);
332        self.visit_skipped_ref_pats(p.hir_id);
333        self.visit_pat_adjustments(p.span, p.hir_id);
334
335        self.visit_node_id(p.span, p.hir_id);
336        intravisit::walk_pat(self, p);
337    }
338
339    fn visit_pat_expr(&mut self, expr: &'tcx hir::PatExpr<'tcx>) {
340        self.visit_node_id(expr.span, expr.hir_id);
341        intravisit::walk_pat_expr(self, expr);
342    }
343
344    fn visit_local(&mut self, l: &'tcx hir::LetStmt<'tcx>) {
345        intravisit::walk_local(self, l);
346        let var_ty = self.fcx.local_ty(l.span, l.hir_id);
347        let var_ty = self.resolve(var_ty, &l.span);
348        self.write_ty_to_typeck_results(l.hir_id, var_ty);
349    }
350
351    fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx, AmbigArg>) {
352        intravisit::walk_ty(self, hir_ty);
353        // If there are type checking errors, Type privacy pass will stop,
354        // so we may not get the type from hid_id, see #104513
355        if let Some(ty) = self.fcx.node_ty_opt(hir_ty.hir_id) {
356            let ty = self.resolve(ty, &hir_ty.span);
357            self.write_ty_to_typeck_results(hir_ty.hir_id, ty);
358        }
359    }
360
361    fn visit_infer(
362        &mut self,
363        inf_id: HirId,
364        inf_span: Span,
365        _kind: InferKind<'cx>,
366    ) -> Self::Result {
367        self.visit_id(inf_id);
368
369        // We don't currently write inference results of const infer vars to
370        // the typeck results as there is not yet any part of the compiler that
371        // needs this information.
372        if let Some(ty) = self.fcx.node_ty_opt(inf_id) {
373            let ty = self.resolve(ty, &inf_span);
374            self.write_ty_to_typeck_results(inf_id, ty);
375        }
376    }
377}
378
379impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
380    fn eval_closure_size(&mut self) {
381        self.tcx().with_stable_hashing_context(|ref hcx| {
382            let fcx_typeck_results = self.fcx.typeck_results.borrow();
383
384            self.typeck_results.closure_size_eval = fcx_typeck_results
385                .closure_size_eval
386                .to_sorted(hcx, false)
387                .into_iter()
388                .map(|(&closure_def_id, data)| {
389                    let closure_hir_id = self.tcx().local_def_id_to_hir_id(closure_def_id);
390                    let data = self.resolve(*data, &closure_hir_id);
391                    (closure_def_id, data)
392                })
393                .collect();
394        })
395    }
396
397    fn visit_min_capture_map(&mut self) {
398        self.tcx().with_stable_hashing_context(|ref hcx| {
399            let fcx_typeck_results = self.fcx.typeck_results.borrow();
400
401            self.typeck_results.closure_min_captures = fcx_typeck_results
402                .closure_min_captures
403                .to_sorted(hcx, false)
404                .into_iter()
405                .map(|(&closure_def_id, root_min_captures)| {
406                    let root_var_map_wb = root_min_captures
407                        .iter()
408                        .map(|(var_hir_id, min_list)| {
409                            let min_list_wb = min_list
410                                .iter()
411                                .map(|captured_place| {
412                                    let locatable =
413                                        captured_place.info.path_expr_id.unwrap_or_else(|| {
414                                            self.tcx().local_def_id_to_hir_id(closure_def_id)
415                                        });
416                                    self.resolve(captured_place.clone(), &locatable)
417                                })
418                                .collect();
419                            (*var_hir_id, min_list_wb)
420                        })
421                        .collect();
422                    (closure_def_id, root_var_map_wb)
423                })
424                .collect();
425        })
426    }
427
428    fn visit_fake_reads_map(&mut self) {
429        self.tcx().with_stable_hashing_context(move |ref hcx| {
430            let fcx_typeck_results = self.fcx.typeck_results.borrow();
431
432            self.typeck_results.closure_fake_reads = fcx_typeck_results
433                .closure_fake_reads
434                .to_sorted(hcx, true)
435                .into_iter()
436                .map(|(&closure_def_id, fake_reads)| {
437                    let resolved_fake_reads = fake_reads
438                        .iter()
439                        .map(|(place, cause, hir_id)| {
440                            let locatable = self.tcx().local_def_id_to_hir_id(closure_def_id);
441                            let resolved_fake_read = self.resolve(place.clone(), &locatable);
442                            (resolved_fake_read, *cause, *hir_id)
443                        })
444                        .collect();
445
446                    (closure_def_id, resolved_fake_reads)
447                })
448                .collect();
449        });
450    }
451
452    fn visit_closures(&mut self) {
453        let fcx_typeck_results = self.fcx.typeck_results.borrow();
454        assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
455        let common_hir_owner = fcx_typeck_results.hir_owner;
456
457        let fcx_closure_kind_origins =
458            fcx_typeck_results.closure_kind_origins().items_in_stable_order();
459
460        for (local_id, origin) in fcx_closure_kind_origins {
461            let hir_id = HirId { owner: common_hir_owner, local_id };
462            let place_span = origin.0;
463            let place = self.resolve(origin.1.clone(), &place_span);
464            self.typeck_results.closure_kind_origins_mut().insert(hir_id, (place_span, place));
465        }
466    }
467
468    fn visit_coercion_casts(&mut self) {
469        let fcx_typeck_results = self.fcx.typeck_results.borrow();
470
471        assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
472
473        let fcx_coercion_casts = fcx_typeck_results.coercion_casts().to_sorted_stable_ord();
474        for &local_id in fcx_coercion_casts {
475            self.typeck_results.set_coercion_cast(local_id);
476        }
477    }
478
479    fn visit_user_provided_tys(&mut self) {
480        let fcx_typeck_results = self.fcx.typeck_results.borrow();
481        assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
482        let common_hir_owner = fcx_typeck_results.hir_owner;
483
484        if self.rustc_dump_user_args {
485            let sorted_user_provided_types =
486                fcx_typeck_results.user_provided_types().items_in_stable_order();
487
488            let mut errors_buffer = Vec::new();
489            for (local_id, c_ty) in sorted_user_provided_types {
490                let hir_id = HirId { owner: common_hir_owner, local_id };
491
492                if let ty::UserTypeKind::TypeOf(_, user_args) = c_ty.value.kind {
493                    // This is a unit-testing mechanism.
494                    let span = self.tcx().hir().span(hir_id);
495                    // We need to buffer the errors in order to guarantee a consistent
496                    // order when emitting them.
497                    let err =
498                        self.tcx().dcx().struct_span_err(span, format!("user args: {user_args:?}"));
499                    errors_buffer.push(err);
500                }
501            }
502
503            if !errors_buffer.is_empty() {
504                errors_buffer.sort_by_key(|diag| diag.span.primary_span());
505                for err in errors_buffer {
506                    err.emit();
507                }
508            }
509        }
510
511        self.typeck_results.user_provided_types_mut().extend(
512            fcx_typeck_results.user_provided_types().items().map(|(local_id, c_ty)| {
513                let hir_id = HirId { owner: common_hir_owner, local_id };
514
515                if cfg!(debug_assertions) && c_ty.has_infer() {
516                    span_bug!(
517                        hir_id.to_span(self.fcx.tcx),
518                        "writeback: `{:?}` has inference variables",
519                        c_ty
520                    );
521                };
522
523                (hir_id, *c_ty)
524            }),
525        );
526    }
527
528    fn visit_user_provided_sigs(&mut self) {
529        let fcx_typeck_results = self.fcx.typeck_results.borrow();
530        assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
531
532        self.typeck_results.user_provided_sigs.extend_unord(
533            fcx_typeck_results.user_provided_sigs.items().map(|(&def_id, c_sig)| {
534                if cfg!(debug_assertions) && c_sig.has_infer() {
535                    span_bug!(
536                        self.fcx.tcx.def_span(def_id),
537                        "writeback: `{:?}` has inference variables",
538                        c_sig
539                    );
540                };
541
542                (def_id, *c_sig)
543            }),
544        );
545    }
546
547    fn visit_coroutine_interior(&mut self) {
548        let fcx_typeck_results = self.fcx.typeck_results.borrow();
549        assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
550        for (predicate, cause) in &fcx_typeck_results.coroutine_stalled_predicates {
551            let (predicate, cause) = self.resolve((*predicate, cause.clone()), &cause.span);
552            self.typeck_results.coroutine_stalled_predicates.insert((predicate, cause));
553        }
554    }
555
556    #[instrument(skip(self), level = "debug")]
557    fn visit_opaque_types(&mut self) {
558        // We clone the opaques instead of stealing them here as they are still used for
559        // normalization in the next generation trait solver.
560        //
561        // FIXME(-Znext-solver): Opaque types defined after this would simply get dropped
562        // at the end of typeck. While this seems unlikely to happen in practice this
563        // should still get fixed. Either by preventing writeback from defining new opaque
564        // types or by using this function at the end of writeback and running it as a
565        // fixpoint.
566        let opaque_types = self.fcx.infcx.clone_opaque_types();
567        for (opaque_type_key, hidden_type) in opaque_types {
568            let hidden_type = self.resolve(hidden_type, &hidden_type.span);
569            let opaque_type_key = self.resolve(opaque_type_key, &hidden_type.span);
570
571            if !self.fcx.next_trait_solver() {
572                if let ty::Alias(ty::Opaque, alias_ty) = hidden_type.ty.kind()
573                    && alias_ty.def_id == opaque_type_key.def_id.to_def_id()
574                    && alias_ty.args == opaque_type_key.args
575                {
576                    continue;
577                }
578            }
579
580            // Here we only detect impl trait definition conflicts when they
581            // are equal modulo regions.
582            if let Some(last_opaque_ty) =
583                self.typeck_results.concrete_opaque_types.insert(opaque_type_key, hidden_type)
584                && last_opaque_ty.ty != hidden_type.ty
585            {
586                assert!(!self.fcx.next_trait_solver());
587                if let Ok(d) = hidden_type.build_mismatch_error(&last_opaque_ty, self.tcx()) {
588                    d.emit();
589                }
590            }
591        }
592    }
593
594    fn visit_field_id(&mut self, hir_id: HirId) {
595        if let Some(index) = self.fcx.typeck_results.borrow_mut().field_indices_mut().remove(hir_id)
596        {
597            self.typeck_results.field_indices_mut().insert(hir_id, index);
598        }
599    }
600
601    #[instrument(skip(self, span), level = "debug")]
602    fn visit_node_id(&mut self, span: Span, hir_id: HirId) {
603        // Export associated path extensions and method resolutions.
604        if let Some(def) =
605            self.fcx.typeck_results.borrow_mut().type_dependent_defs_mut().remove(hir_id)
606        {
607            self.typeck_results.type_dependent_defs_mut().insert(hir_id, def);
608        }
609
610        // Resolve any borrowings for the node with id `node_id`
611        self.visit_adjustments(span, hir_id);
612
613        // Resolve the type of the node with id `node_id`
614        let n_ty = self.fcx.node_ty(hir_id);
615        let n_ty = self.resolve(n_ty, &span);
616        self.write_ty_to_typeck_results(hir_id, n_ty);
617        debug!(?n_ty);
618
619        // Resolve any generic parameters
620        if let Some(args) = self.fcx.typeck_results.borrow().node_args_opt(hir_id) {
621            let args = self.resolve(args, &span);
622            debug!("write_args_to_tcx({:?}, {:?})", hir_id, args);
623            assert!(!args.has_infer() && !args.has_placeholders());
624            self.typeck_results.node_args_mut().insert(hir_id, args);
625        }
626    }
627
628    #[instrument(skip(self, span), level = "debug")]
629    fn visit_adjustments(&mut self, span: Span, hir_id: HirId) {
630        let adjustment = self.fcx.typeck_results.borrow_mut().adjustments_mut().remove(hir_id);
631        match adjustment {
632            None => {
633                debug!("no adjustments for node");
634            }
635
636            Some(adjustment) => {
637                let resolved_adjustment = self.resolve(adjustment, &span);
638                debug!(?resolved_adjustment);
639                self.typeck_results.adjustments_mut().insert(hir_id, resolved_adjustment);
640            }
641        }
642    }
643
644    #[instrument(skip(self), level = "debug")]
645    fn visit_rust_2024_migration_desugared_pats(&mut self, hir_id: hir::HirId) {
646        if let Some(is_hard_error) = self
647            .fcx
648            .typeck_results
649            .borrow_mut()
650            .rust_2024_migration_desugared_pats_mut()
651            .remove(hir_id)
652        {
653            debug!(
654                "node is a pat whose match ergonomics are desugared by the Rust 2024 migration lint"
655            );
656            self.typeck_results
657                .rust_2024_migration_desugared_pats_mut()
658                .insert(hir_id, is_hard_error);
659        }
660    }
661
662    #[instrument(skip(self, span), level = "debug")]
663    fn visit_pat_adjustments(&mut self, span: Span, hir_id: HirId) {
664        let adjustment = self.fcx.typeck_results.borrow_mut().pat_adjustments_mut().remove(hir_id);
665        match adjustment {
666            None => {
667                debug!("no pat_adjustments for node");
668            }
669
670            Some(adjustment) => {
671                let resolved_adjustment = self.resolve(adjustment, &span);
672                debug!(?resolved_adjustment);
673                self.typeck_results.pat_adjustments_mut().insert(hir_id, resolved_adjustment);
674            }
675        }
676    }
677
678    #[instrument(skip(self), level = "debug")]
679    fn visit_skipped_ref_pats(&mut self, hir_id: hir::HirId) {
680        if self.fcx.typeck_results.borrow_mut().skipped_ref_pats_mut().remove(hir_id) {
681            debug!("node is a skipped ref pat");
682            self.typeck_results.skipped_ref_pats_mut().insert(hir_id);
683        }
684    }
685
686    fn visit_liberated_fn_sigs(&mut self) {
687        let fcx_typeck_results = self.fcx.typeck_results.borrow();
688        assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
689        let common_hir_owner = fcx_typeck_results.hir_owner;
690
691        let fcx_liberated_fn_sigs = fcx_typeck_results.liberated_fn_sigs().items_in_stable_order();
692
693        for (local_id, &fn_sig) in fcx_liberated_fn_sigs {
694            let hir_id = HirId { owner: common_hir_owner, local_id };
695            let fn_sig = self.resolve(fn_sig, &hir_id);
696            self.typeck_results.liberated_fn_sigs_mut().insert(hir_id, fn_sig);
697        }
698    }
699
700    fn visit_fru_field_types(&mut self) {
701        let fcx_typeck_results = self.fcx.typeck_results.borrow();
702        assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
703        let common_hir_owner = fcx_typeck_results.hir_owner;
704
705        let fcx_fru_field_types = fcx_typeck_results.fru_field_types().items_in_stable_order();
706
707        for (local_id, ftys) in fcx_fru_field_types {
708            let hir_id = HirId { owner: common_hir_owner, local_id };
709            let ftys = self.resolve(ftys.clone(), &hir_id);
710            self.typeck_results.fru_field_types_mut().insert(hir_id, ftys);
711        }
712    }
713
714    fn visit_offset_of_container_types(&mut self) {
715        let fcx_typeck_results = self.fcx.typeck_results.borrow();
716        assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
717        let common_hir_owner = fcx_typeck_results.hir_owner;
718
719        for (local_id, &(container, ref indices)) in
720            fcx_typeck_results.offset_of_data().items_in_stable_order()
721        {
722            let hir_id = HirId { owner: common_hir_owner, local_id };
723            let container = self.resolve(container, &hir_id);
724            self.typeck_results.offset_of_data_mut().insert(hir_id, (container, indices.clone()));
725        }
726    }
727
728    fn resolve<T>(&mut self, value: T, span: &dyn Locatable) -> T
729    where
730        T: TypeFoldable<TyCtxt<'tcx>>,
731    {
732        let value = self.fcx.resolve_vars_if_possible(value);
733        let value = value.fold_with(&mut Resolver::new(self.fcx, span, self.body));
734        assert!(!value.has_infer());
735
736        // We may have introduced e.g. `ty::Error`, if inference failed, make sure
737        // to mark the `TypeckResults` as tainted in that case, so that downstream
738        // users of the typeck results don't produce extra errors, or worse, ICEs.
739        if let Err(guar) = value.error_reported() {
740            self.typeck_results.tainted_by_errors = Some(guar);
741        }
742
743        value
744    }
745}
746
747pub(crate) trait Locatable {
748    fn to_span(&self, tcx: TyCtxt<'_>) -> Span;
749}
750
751impl Locatable for Span {
752    fn to_span(&self, _: TyCtxt<'_>) -> Span {
753        *self
754    }
755}
756
757impl Locatable for HirId {
758    fn to_span(&self, tcx: TyCtxt<'_>) -> Span {
759        tcx.hir().span(*self)
760    }
761}
762
763struct Resolver<'cx, 'tcx> {
764    fcx: &'cx FnCtxt<'cx, 'tcx>,
765    span: &'cx dyn Locatable,
766    body: &'tcx hir::Body<'tcx>,
767    /// Whether we should normalize using the new solver, disabled
768    /// both when using the old solver and when resolving predicates.
769    should_normalize: bool,
770}
771
772impl<'cx, 'tcx> Resolver<'cx, 'tcx> {
773    fn new(
774        fcx: &'cx FnCtxt<'cx, 'tcx>,
775        span: &'cx dyn Locatable,
776        body: &'tcx hir::Body<'tcx>,
777    ) -> Resolver<'cx, 'tcx> {
778        Resolver { fcx, span, body, should_normalize: fcx.next_trait_solver() }
779    }
780
781    fn report_error(&self, p: impl Into<ty::GenericArg<'tcx>>) -> ErrorGuaranteed {
782        if let Some(guar) = self.fcx.tainted_by_errors() {
783            guar
784        } else {
785            self.fcx
786                .err_ctxt()
787                .emit_inference_failure_err(
788                    self.fcx.tcx.hir_body_owner_def_id(self.body.id()),
789                    self.span.to_span(self.fcx.tcx),
790                    p.into(),
791                    TypeAnnotationNeeded::E0282,
792                    false,
793                )
794                .emit()
795        }
796    }
797
798    fn handle_term<T>(
799        &mut self,
800        value: T,
801        outer_exclusive_binder: impl FnOnce(T) -> ty::DebruijnIndex,
802        new_err: impl Fn(TyCtxt<'tcx>, ErrorGuaranteed) -> T,
803    ) -> T
804    where
805        T: Into<ty::GenericArg<'tcx>> + TypeSuperFoldable<TyCtxt<'tcx>> + Copy,
806    {
807        let tcx = self.fcx.tcx;
808        // We must deeply normalize in the new solver, since later lints
809        // expect that types that show up in the typeck are fully
810        // normalized.
811        let mut value = if self.should_normalize {
812            let body_id = tcx.hir_body_owner_def_id(self.body.id());
813            let cause = ObligationCause::misc(self.span.to_span(tcx), body_id);
814            let at = self.fcx.at(&cause, self.fcx.param_env);
815            let universes = vec![None; outer_exclusive_binder(value).as_usize()];
816            solve::deeply_normalize_with_skipped_universes(at, value, universes).unwrap_or_else(
817                |errors| {
818                    let guar = self.fcx.err_ctxt().report_fulfillment_errors(errors);
819                    new_err(tcx, guar)
820                },
821            )
822        } else {
823            value
824        };
825
826        // Bail if there are any non-region infer.
827        if value.has_non_region_infer() {
828            let guar = self.report_error(value);
829            value = new_err(tcx, guar);
830        }
831
832        // Erase the regions from the ty, since it's not really meaningful what
833        // these region values are; there's not a trivial correspondence between
834        // regions in the HIR and MIR, so when we turn the body into MIR, there's
835        // no reason to keep regions around. They will be repopulated during MIR
836        // borrowck, and specifically region constraints will be populated during
837        // MIR typeck which is run on the new body.
838        //
839        // We're not using `tcx.erase_regions` as that also anonymizes bound variables,
840        // regressing borrowck diagnostics.
841        value = fold_regions(tcx, value, |_, _| tcx.lifetimes.re_erased);
842
843        // Normalize consts in writeback, because GCE doesn't normalize eagerly.
844        if tcx.features().generic_const_exprs() {
845            value = value.fold_with(&mut EagerlyNormalizeConsts::new(self.fcx));
846        }
847
848        value
849    }
850}
851
852impl<'cx, 'tcx> TypeFolder<TyCtxt<'tcx>> for Resolver<'cx, 'tcx> {
853    fn cx(&self) -> TyCtxt<'tcx> {
854        self.fcx.tcx
855    }
856
857    fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
858        debug_assert!(!r.is_bound(), "Should not be resolving bound region.");
859        self.fcx.tcx.lifetimes.re_erased
860    }
861
862    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
863        self.handle_term(ty, Ty::outer_exclusive_binder, Ty::new_error)
864    }
865
866    fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
867        self.handle_term(ct, ty::Const::outer_exclusive_binder, |tcx, guar| {
868            ty::Const::new_error(tcx, guar)
869        })
870        .super_fold_with(self)
871    }
872
873    fn fold_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
874        // Do not normalize predicates in the new solver. The new solver is
875        // supposed to handle unnormalized predicates and incorrectly normalizing
876        // them can be unsound, e.g. for `WellFormed` predicates.
877        let prev = mem::replace(&mut self.should_normalize, false);
878        let predicate = predicate.super_fold_with(self);
879        self.should_normalize = prev;
880        predicate
881    }
882}
883
884struct EagerlyNormalizeConsts<'tcx> {
885    tcx: TyCtxt<'tcx>,
886    typing_env: ty::TypingEnv<'tcx>,
887}
888impl<'tcx> EagerlyNormalizeConsts<'tcx> {
889    fn new(fcx: &FnCtxt<'_, 'tcx>) -> Self {
890        // FIXME(#132279, generic_const_exprs): Using `try_normalize_erasing_regions` here
891        // means we can't handle opaque types in their defining scope.
892        EagerlyNormalizeConsts { tcx: fcx.tcx, typing_env: fcx.typing_env(fcx.param_env) }
893    }
894}
895
896impl<'tcx> TypeFolder<TyCtxt<'tcx>> for EagerlyNormalizeConsts<'tcx> {
897    fn cx(&self) -> TyCtxt<'tcx> {
898        self.tcx
899    }
900
901    fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
902        self.tcx.try_normalize_erasing_regions(self.typing_env, ct).unwrap_or(ct)
903    }
904}