rustc_hir_typeck/
writeback.rs

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