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;
12use std::ops::ControlFlow;
13
14use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
15use rustc_data_structures::unord::ExtendUnord;
16use rustc_errors::{E0720, ErrorGuaranteed};
17use rustc_hir::def_id::LocalDefId;
18use rustc_hir::intravisit::{self, InferKind, Visitor};
19use rustc_hir::{self as hir, AmbigArg, HirId};
20use rustc_infer::traits::solve::Goal;
21use rustc_middle::traits::ObligationCause;
22use rustc_middle::ty::adjustment::{Adjust, Adjustment, PointerCoercion};
23use rustc_middle::ty::{
24    self, DefiningScopeKind, OpaqueHiddenType, Ty, TyCtxt, TypeFoldable, TypeFolder,
25    TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
26    fold_regions,
27};
28use rustc_span::{Span, sym};
29use rustc_trait_selection::error_reporting::infer::need_type_info::TypeAnnotationNeeded;
30use rustc_trait_selection::opaque_types::opaque_type_has_defining_use_args;
31use rustc_trait_selection::solve;
32use tracing::{debug, instrument};
33
34use crate::FnCtxt;
35
36///////////////////////////////////////////////////////////////////////////
37// Entry point
38
39impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
40    pub(crate) fn resolve_type_vars_in_body(
41        &self,
42        body: &'tcx hir::Body<'tcx>,
43    ) -> &'tcx ty::TypeckResults<'tcx> {
44        let item_def_id = self.tcx.hir_body_owner_def_id(body.id());
45
46        // This attribute causes us to dump some writeback information
47        // in the form of errors, which is used for unit tests.
48        let rustc_dump_user_args =
49            self.has_rustc_attrs && self.tcx.has_attr(item_def_id, sym::rustc_dump_user_args);
50
51        let mut wbcx = WritebackCx::new(self, body, rustc_dump_user_args);
52        for param in body.params {
53            wbcx.visit_node_id(param.pat.span, param.hir_id);
54        }
55        match self.tcx.hir_body_owner_kind(item_def_id) {
56            // Visit the type of a const or static, which is used during THIR building.
57            hir::BodyOwnerKind::Const { .. }
58            | hir::BodyOwnerKind::Static(_)
59            | hir::BodyOwnerKind::GlobalAsm => {
60                let item_hir_id = self.tcx.local_def_id_to_hir_id(item_def_id);
61                wbcx.visit_node_id(body.value.span, item_hir_id);
62            }
63            // For closures and consts, we already plan to visit liberated signatures.
64            hir::BodyOwnerKind::Closure | hir::BodyOwnerKind::Fn => {}
65        }
66        wbcx.visit_body(body);
67        wbcx.visit_min_capture_map();
68        wbcx.eval_closure_size();
69        wbcx.visit_fake_reads_map();
70        wbcx.visit_closures();
71        wbcx.visit_liberated_fn_sigs();
72        wbcx.visit_fru_field_types();
73        wbcx.visit_opaque_types();
74        wbcx.visit_coercion_casts();
75        wbcx.visit_user_provided_tys();
76        wbcx.visit_user_provided_sigs();
77        wbcx.visit_coroutine_interior();
78        wbcx.visit_transmutes();
79        wbcx.visit_offset_of_container_types();
80        wbcx.visit_potentially_region_dependent_goals();
81
82        wbcx.typeck_results.rvalue_scopes =
83            mem::take(&mut self.typeck_results.borrow_mut().rvalue_scopes);
84
85        let used_trait_imports =
86            mem::take(&mut self.typeck_results.borrow_mut().used_trait_imports);
87        debug!("used_trait_imports({:?}) = {:?}", item_def_id, used_trait_imports);
88        wbcx.typeck_results.used_trait_imports = used_trait_imports;
89
90        debug!("writeback: typeck results for {:?} are {:#?}", item_def_id, wbcx.typeck_results);
91
92        self.tcx.arena.alloc(wbcx.typeck_results)
93    }
94}
95
96/// The Writeback context. This visitor walks the HIR, checking the
97/// fn-specific typeck results to find inference variables. It resolves
98/// those inference variables and writes the final result into the
99/// `TypeckResults`. It also applies a few ad-hoc checks that were not
100/// convenient to do elsewhere.
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) => {
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                    if !op.node.is_by_value() {
172                        let mut adjustments = self.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            }
182            hir::ExprKind::AssignOp(_, lhs, rhs) => {
183                let lhs_ty = self.typeck_results.node_type(lhs.hir_id);
184                let rhs_ty = self.typeck_results.node_type(rhs.hir_id);
185
186                if lhs_ty.is_scalar() && rhs_ty.is_scalar() {
187                    self.typeck_results.type_dependent_defs_mut().remove(e.hir_id);
188                    self.typeck_results.node_args_mut().remove(e.hir_id);
189
190                    if let Some(a) = self.typeck_results.adjustments_mut().get_mut(lhs.hir_id) {
191                        a.pop();
192                    }
193                }
194            }
195            _ => {}
196        }
197    }
198
199    // (ouz-a 1005988): Normally `[T] : std::ops::Index<usize>` should be normalized
200    // into [T] but currently `Where` clause stops the normalization process for it,
201    // here we compare types of expr and base in a code without `Where` clause they would be equal
202    // if they are not we don't modify the expr, hence we bypass the ICE
203    fn is_builtin_index(
204        &mut self,
205        e: &hir::Expr<'_>,
206        base_ty: Ty<'tcx>,
207        index_ty: Ty<'tcx>,
208    ) -> bool {
209        if let Some(elem_ty) = base_ty.builtin_index()
210            && let Some(exp_ty) = self.typeck_results.expr_ty_opt(e)
211        {
212            elem_ty == exp_ty && index_ty == self.fcx.tcx.types.usize
213        } else {
214            false
215        }
216    }
217
218    // Similar to operators, indexing is always assumed to be overloaded
219    // Here, correct cases where an indexing expression can be simplified
220    // to use builtin indexing because the index type is known to be
221    // usize-ish
222    fn fix_index_builtin_expr(&mut self, e: &hir::Expr<'_>) {
223        if let hir::ExprKind::Index(base, index, _) = e.kind {
224            // All valid indexing looks like this; might encounter non-valid indexes at this point.
225            let base_ty = self.typeck_results.expr_ty_adjusted(base);
226            if let ty::Ref(_, base_ty_inner, _) = *base_ty.kind() {
227                let index_ty = self.typeck_results.expr_ty_adjusted(index);
228                if self.is_builtin_index(e, base_ty_inner, index_ty) {
229                    // Remove the method call record
230                    self.typeck_results.type_dependent_defs_mut().remove(e.hir_id);
231                    self.typeck_results.node_args_mut().remove(e.hir_id);
232
233                    if let Some(a) = self.typeck_results.adjustments_mut().get_mut(base.hir_id)
234                        // Discard the need for a mutable borrow
235                        // Extra adjustment made when indexing causes a drop
236                        // of size information - we need to get rid of it
237                        // Since this is "after" the other adjustment to be
238                        // discarded, we do an extra `pop()`
239                        && let Some(Adjustment {
240                            kind: Adjust::Pointer(PointerCoercion::Unsize),
241                            ..
242                        }) = a.pop()
243                    {
244                        // So the borrow discard actually happens here
245                        a.pop();
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                (hir_id, *c_ty)
515            }),
516        );
517    }
518
519    fn visit_user_provided_sigs(&mut self) {
520        let fcx_typeck_results = self.fcx.typeck_results.borrow();
521        assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
522
523        self.typeck_results.user_provided_sigs.extend_unord(
524            fcx_typeck_results.user_provided_sigs.items().map(|(def_id, c_sig)| (*def_id, *c_sig)),
525        );
526    }
527
528    fn visit_coroutine_interior(&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        for (predicate, cause) in &fcx_typeck_results.coroutine_stalled_predicates {
532            let (predicate, cause) =
533                self.resolve_coroutine_predicate((*predicate, cause.clone()), &cause.span);
534            self.typeck_results.coroutine_stalled_predicates.insert((predicate, cause));
535        }
536    }
537
538    fn visit_transmutes(&mut self) {
539        let tcx = self.tcx();
540        let fcx_typeck_results = self.fcx.typeck_results.borrow();
541        assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
542        for &(from, to, hir_id) in self.fcx.deferred_transmute_checks.borrow().iter() {
543            let span = tcx.hir_span(hir_id);
544            let from = self.resolve(from, &span);
545            let to = self.resolve(to, &span);
546            self.typeck_results.transmutes_to_check.push((from, to, hir_id));
547        }
548    }
549
550    fn visit_opaque_types_next(&mut self) {
551        let mut fcx_typeck_results = self.fcx.typeck_results.borrow_mut();
552        assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
553        for hidden_ty in fcx_typeck_results.hidden_types.values() {
554            assert!(!hidden_ty.has_infer());
555        }
556
557        assert_eq!(self.typeck_results.hidden_types.len(), 0);
558        self.typeck_results.hidden_types = mem::take(&mut fcx_typeck_results.hidden_types);
559    }
560
561    #[instrument(skip(self), level = "debug")]
562    fn visit_opaque_types(&mut self) {
563        if self.fcx.next_trait_solver() {
564            return self.visit_opaque_types_next();
565        }
566
567        let tcx = self.tcx();
568        // We clone the opaques instead of stealing them here as they are still used for
569        // normalization in the next generation trait solver.
570        let opaque_types = self.fcx.infcx.clone_opaque_types();
571        let num_entries = self.fcx.inner.borrow_mut().opaque_types().num_entries();
572        let prev = self.fcx.checked_opaque_types_storage_entries.replace(Some(num_entries));
573        debug_assert_eq!(prev, None);
574        for (opaque_type_key, hidden_type) in opaque_types {
575            let hidden_type = self.resolve(hidden_type, &hidden_type.span);
576            let opaque_type_key = self.resolve(opaque_type_key, &hidden_type.span);
577            if let ty::Alias(ty::Opaque, alias_ty) = hidden_type.ty.kind()
578                && alias_ty.def_id == opaque_type_key.def_id.to_def_id()
579                && alias_ty.args == opaque_type_key.args
580            {
581                continue;
582            }
583
584            if let Err(err) = opaque_type_has_defining_use_args(
585                self.fcx,
586                opaque_type_key,
587                hidden_type.span,
588                DefiningScopeKind::HirTypeck,
589            ) {
590                self.typeck_results.hidden_types.insert(
591                    opaque_type_key.def_id,
592                    ty::OpaqueHiddenType::new_error(tcx, err.report(self.fcx)),
593                );
594            }
595
596            let hidden_type = hidden_type.remap_generic_params_to_declaration_params(
597                opaque_type_key,
598                tcx,
599                DefiningScopeKind::HirTypeck,
600            );
601
602            if let Some(prev) =
603                self.typeck_results.hidden_types.insert(opaque_type_key.def_id, hidden_type)
604            {
605                let entry =
606                    &mut self.typeck_results.hidden_types.get_mut(&opaque_type_key.def_id).unwrap();
607                if prev.ty != hidden_type.ty {
608                    if let Some(guar) = self.typeck_results.tainted_by_errors {
609                        entry.ty = Ty::new_error(tcx, guar);
610                    } else {
611                        let (Ok(guar) | Err(guar)) =
612                            prev.build_mismatch_error(&hidden_type, tcx).map(|d| d.emit());
613                        entry.ty = Ty::new_error(tcx, guar);
614                    }
615                }
616
617                // Pick a better span if there is one.
618                // FIXME(oli-obk): collect multiple spans for better diagnostics down the road.
619                entry.span = prev.span.substitute_dummy(hidden_type.span);
620            }
621        }
622
623        let recursive_opaques: Vec<_> = self
624            .typeck_results
625            .hidden_types
626            .iter()
627            .filter(|&(&def_id, hidden_ty)| {
628                hidden_ty
629                    .ty
630                    .visit_with(&mut HasRecursiveOpaque {
631                        def_id,
632                        seen: Default::default(),
633                        opaques: &self.typeck_results.hidden_types,
634                        tcx,
635                    })
636                    .is_break()
637            })
638            .map(|(def_id, hidden_ty)| (*def_id, hidden_ty.span))
639            .collect();
640        for (def_id, span) in recursive_opaques {
641            let guar = self
642                .fcx
643                .dcx()
644                .struct_span_err(span, "cannot resolve opaque type")
645                .with_code(E0720)
646                .emit();
647            self.typeck_results
648                .hidden_types
649                .insert(def_id, OpaqueHiddenType { span, ty: Ty::new_error(tcx, guar) });
650        }
651    }
652
653    fn visit_field_id(&mut self, hir_id: HirId) {
654        if let Some(index) = self.fcx.typeck_results.borrow_mut().field_indices_mut().remove(hir_id)
655        {
656            self.typeck_results.field_indices_mut().insert(hir_id, index);
657        }
658    }
659
660    #[instrument(skip(self, span), level = "debug")]
661    fn visit_node_id(&mut self, span: Span, hir_id: HirId) {
662        // Export associated path extensions and method resolutions.
663        if let Some(def) =
664            self.fcx.typeck_results.borrow_mut().type_dependent_defs_mut().remove(hir_id)
665        {
666            self.typeck_results.type_dependent_defs_mut().insert(hir_id, def);
667        }
668
669        // Resolve any borrowings for the node with id `node_id`
670        self.visit_adjustments(span, hir_id);
671
672        // Resolve the type of the node with id `node_id`
673        let n_ty = self.fcx.node_ty(hir_id);
674        let n_ty = self.resolve(n_ty, &span);
675        self.write_ty_to_typeck_results(hir_id, n_ty);
676        debug!(?n_ty);
677
678        // Resolve any generic parameters
679        if let Some(args) = self.fcx.typeck_results.borrow().node_args_opt(hir_id) {
680            let args = self.resolve(args, &span);
681            debug!("write_args_to_tcx({:?}, {:?})", hir_id, args);
682            assert!(!args.has_infer() && !args.has_placeholders());
683            self.typeck_results.node_args_mut().insert(hir_id, args);
684        }
685    }
686
687    #[instrument(skip(self, span), level = "debug")]
688    fn visit_adjustments(&mut self, span: Span, hir_id: HirId) {
689        let adjustment = self.fcx.typeck_results.borrow_mut().adjustments_mut().remove(hir_id);
690        match adjustment {
691            None => {
692                debug!("no adjustments for node");
693            }
694
695            Some(adjustment) => {
696                let resolved_adjustment = self.resolve(adjustment, &span);
697                debug!(?resolved_adjustment);
698                self.typeck_results.adjustments_mut().insert(hir_id, resolved_adjustment);
699            }
700        }
701    }
702
703    #[instrument(skip(self), level = "debug")]
704    fn visit_rust_2024_migration_desugared_pats(&mut self, hir_id: hir::HirId) {
705        if let Some(is_hard_error) = self
706            .fcx
707            .typeck_results
708            .borrow_mut()
709            .rust_2024_migration_desugared_pats_mut()
710            .remove(hir_id)
711        {
712            debug!(
713                "node is a pat whose match ergonomics are desugared by the Rust 2024 migration lint"
714            );
715            self.typeck_results
716                .rust_2024_migration_desugared_pats_mut()
717                .insert(hir_id, is_hard_error);
718        }
719    }
720
721    #[instrument(skip(self, span), level = "debug")]
722    fn visit_pat_adjustments(&mut self, span: Span, hir_id: HirId) {
723        let adjustment = self.fcx.typeck_results.borrow_mut().pat_adjustments_mut().remove(hir_id);
724        match adjustment {
725            None => {
726                debug!("no pat_adjustments for node");
727            }
728
729            Some(adjustment) => {
730                let resolved_adjustment = self.resolve(adjustment, &span);
731                debug!(?resolved_adjustment);
732                self.typeck_results.pat_adjustments_mut().insert(hir_id, resolved_adjustment);
733            }
734        }
735    }
736
737    #[instrument(skip(self), level = "debug")]
738    fn visit_skipped_ref_pats(&mut self, hir_id: hir::HirId) {
739        if self.fcx.typeck_results.borrow_mut().skipped_ref_pats_mut().remove(hir_id) {
740            debug!("node is a skipped ref pat");
741            self.typeck_results.skipped_ref_pats_mut().insert(hir_id);
742        }
743    }
744
745    fn visit_liberated_fn_sigs(&mut self) {
746        let fcx_typeck_results = self.fcx.typeck_results.borrow();
747        assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
748        let common_hir_owner = fcx_typeck_results.hir_owner;
749
750        let fcx_liberated_fn_sigs = fcx_typeck_results.liberated_fn_sigs().items_in_stable_order();
751
752        for (local_id, &fn_sig) in fcx_liberated_fn_sigs {
753            let hir_id = HirId { owner: common_hir_owner, local_id };
754            let fn_sig = self.resolve(fn_sig, &hir_id);
755            self.typeck_results.liberated_fn_sigs_mut().insert(hir_id, fn_sig);
756        }
757    }
758
759    fn visit_fru_field_types(&mut self) {
760        let fcx_typeck_results = self.fcx.typeck_results.borrow();
761        assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
762        let common_hir_owner = fcx_typeck_results.hir_owner;
763
764        let fcx_fru_field_types = fcx_typeck_results.fru_field_types().items_in_stable_order();
765
766        for (local_id, ftys) in fcx_fru_field_types {
767            let hir_id = HirId { owner: common_hir_owner, local_id };
768            let ftys = self.resolve(ftys.clone(), &hir_id);
769            self.typeck_results.fru_field_types_mut().insert(hir_id, ftys);
770        }
771    }
772
773    fn visit_offset_of_container_types(&mut self) {
774        let fcx_typeck_results = self.fcx.typeck_results.borrow();
775        assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
776        let common_hir_owner = fcx_typeck_results.hir_owner;
777
778        for (local_id, &(container, ref indices)) in
779            fcx_typeck_results.offset_of_data().items_in_stable_order()
780        {
781            let hir_id = HirId { owner: common_hir_owner, local_id };
782            let container = self.resolve(container, &hir_id);
783            self.typeck_results.offset_of_data_mut().insert(hir_id, (container, indices.clone()));
784        }
785    }
786
787    fn visit_potentially_region_dependent_goals(&mut self) {
788        let obligations = self.fcx.take_hir_typeck_potentially_region_dependent_goals();
789        if self.fcx.tainted_by_errors().is_none() {
790            for obligation in obligations {
791                let (predicate, mut cause) =
792                    self.fcx.resolve_vars_if_possible((obligation.predicate, obligation.cause));
793                if predicate.has_non_region_infer() {
794                    self.fcx.dcx().span_delayed_bug(
795                        cause.span,
796                        format!("unexpected inference variable after writeback: {predicate:?}"),
797                    );
798                } else {
799                    let predicate = self.tcx().erase_and_anonymize_regions(predicate);
800                    if cause.has_infer() || cause.has_placeholders() {
801                        // We can't use the the obligation cause as it references
802                        // information local to this query.
803                        cause = self.fcx.misc(cause.span);
804                    }
805                    self.typeck_results
806                        .potentially_region_dependent_goals
807                        .insert((predicate, cause));
808                }
809            }
810        }
811    }
812
813    fn resolve<T>(&mut self, value: T, span: &dyn Locatable) -> T
814    where
815        T: TypeFoldable<TyCtxt<'tcx>>,
816    {
817        let value = self.fcx.resolve_vars_if_possible(value);
818
819        let mut goals = vec![];
820        let value =
821            value.fold_with(&mut Resolver::new(self.fcx, span, self.body, true, &mut goals));
822
823        // Ensure that we resolve goals we get from normalizing coroutine interiors,
824        // but we shouldn't expect those goals to need normalizing (or else we'd get
825        // into a somewhat awkward fixpoint situation, and we don't need it anyways).
826        let mut unexpected_goals = vec![];
827        self.typeck_results.coroutine_stalled_predicates.extend(
828            goals
829                .into_iter()
830                .map(|pred| {
831                    self.fcx.resolve_vars_if_possible(pred).fold_with(&mut Resolver::new(
832                        self.fcx,
833                        span,
834                        self.body,
835                        false,
836                        &mut unexpected_goals,
837                    ))
838                })
839                // FIXME: throwing away the param-env :(
840                .map(|goal| (goal.predicate, self.fcx.misc(span.to_span(self.fcx.tcx)))),
841        );
842        assert_eq!(unexpected_goals, vec![]);
843
844        assert!(!value.has_infer());
845
846        // We may have introduced e.g. `ty::Error`, if inference failed, make sure
847        // to mark the `TypeckResults` as tainted in that case, so that downstream
848        // users of the typeck results don't produce extra errors, or worse, ICEs.
849        if let Err(guar) = value.error_reported() {
850            self.typeck_results.tainted_by_errors = Some(guar);
851        }
852
853        value
854    }
855
856    fn resolve_coroutine_predicate<T>(&mut self, value: T, span: &dyn Locatable) -> T
857    where
858        T: TypeFoldable<TyCtxt<'tcx>>,
859    {
860        let value = self.fcx.resolve_vars_if_possible(value);
861
862        let mut goals = vec![];
863        let value =
864            value.fold_with(&mut Resolver::new(self.fcx, span, self.body, false, &mut goals));
865        assert_eq!(goals, vec![]);
866
867        assert!(!value.has_infer());
868
869        // We may have introduced e.g. `ty::Error`, if inference failed, make sure
870        // to mark the `TypeckResults` as tainted in that case, so that downstream
871        // users of the typeck results don't produce extra errors, or worse, ICEs.
872        if let Err(guar) = value.error_reported() {
873            self.typeck_results.tainted_by_errors = Some(guar);
874        }
875
876        value
877    }
878}
879
880pub(crate) trait Locatable {
881    fn to_span(&self, tcx: TyCtxt<'_>) -> Span;
882}
883
884impl Locatable for Span {
885    fn to_span(&self, _: TyCtxt<'_>) -> Span {
886        *self
887    }
888}
889
890impl Locatable for HirId {
891    fn to_span(&self, tcx: TyCtxt<'_>) -> Span {
892        tcx.hir_span(*self)
893    }
894}
895
896struct Resolver<'cx, 'tcx> {
897    fcx: &'cx FnCtxt<'cx, 'tcx>,
898    span: &'cx dyn Locatable,
899    body: &'tcx hir::Body<'tcx>,
900    /// Whether we should normalize using the new solver, disabled
901    /// both when using the old solver and when resolving predicates.
902    should_normalize: bool,
903    nested_goals: &'cx mut Vec<Goal<'tcx, ty::Predicate<'tcx>>>,
904}
905
906impl<'cx, 'tcx> Resolver<'cx, 'tcx> {
907    fn new(
908        fcx: &'cx FnCtxt<'cx, 'tcx>,
909        span: &'cx dyn Locatable,
910        body: &'tcx hir::Body<'tcx>,
911        should_normalize: bool,
912        nested_goals: &'cx mut Vec<Goal<'tcx, ty::Predicate<'tcx>>>,
913    ) -> Resolver<'cx, 'tcx> {
914        Resolver { fcx, span, body, nested_goals, should_normalize }
915    }
916
917    fn report_error(&self, p: impl Into<ty::Term<'tcx>>) -> ErrorGuaranteed {
918        if let Some(guar) = self.fcx.tainted_by_errors() {
919            guar
920        } else {
921            self.fcx
922                .err_ctxt()
923                .emit_inference_failure_err(
924                    self.fcx.tcx.hir_body_owner_def_id(self.body.id()),
925                    self.span.to_span(self.fcx.tcx),
926                    p.into(),
927                    TypeAnnotationNeeded::E0282,
928                    false,
929                )
930                .emit()
931        }
932    }
933
934    #[instrument(level = "debug", skip(self, outer_exclusive_binder, new_err))]
935    fn handle_term<T>(
936        &mut self,
937        value: T,
938        outer_exclusive_binder: impl FnOnce(T) -> ty::DebruijnIndex,
939        new_err: impl Fn(TyCtxt<'tcx>, ErrorGuaranteed) -> T,
940    ) -> T
941    where
942        T: Into<ty::Term<'tcx>> + TypeSuperFoldable<TyCtxt<'tcx>> + Copy,
943    {
944        let tcx = self.fcx.tcx;
945        // We must deeply normalize in the new solver, since later lints expect
946        // that types that show up in the typeck are fully normalized.
947        let mut value = if self.should_normalize && self.fcx.next_trait_solver() {
948            let body_id = tcx.hir_body_owner_def_id(self.body.id());
949            let cause = ObligationCause::misc(self.span.to_span(tcx), body_id);
950            let at = self.fcx.at(&cause, self.fcx.param_env);
951            let universes = vec![None; outer_exclusive_binder(value).as_usize()];
952            match solve::deeply_normalize_with_skipped_universes_and_ambiguous_coroutine_goals(
953                at, value, universes,
954            ) {
955                Ok((value, goals)) => {
956                    self.nested_goals.extend(goals);
957                    value
958                }
959                Err(errors) => {
960                    let guar = self.fcx.err_ctxt().report_fulfillment_errors(errors);
961                    new_err(tcx, guar)
962                }
963            }
964        } else {
965            value
966        };
967
968        // Bail if there are any non-region infer.
969        if value.has_non_region_infer() {
970            let guar = self.report_error(value);
971            value = new_err(tcx, guar);
972        }
973
974        // Erase the regions from the ty, since it's not really meaningful what
975        // these region values are; there's not a trivial correspondence between
976        // regions in the HIR and MIR, so when we turn the body into MIR, there's
977        // no reason to keep regions around. They will be repopulated during MIR
978        // borrowck, and specifically region constraints will be populated during
979        // MIR typeck which is run on the new body.
980        //
981        // We're not using `tcx.erase_and_anonymize_regions` as that also
982        // anonymizes bound variables, regressing borrowck diagnostics.
983        value = fold_regions(tcx, value, |_, _| tcx.lifetimes.re_erased);
984
985        // Normalize consts in writeback, because GCE doesn't normalize eagerly.
986        if tcx.features().generic_const_exprs() {
987            value = value.fold_with(&mut EagerlyNormalizeConsts::new(self.fcx));
988        }
989
990        value
991    }
992}
993
994impl<'cx, 'tcx> TypeFolder<TyCtxt<'tcx>> for Resolver<'cx, 'tcx> {
995    fn cx(&self) -> TyCtxt<'tcx> {
996        self.fcx.tcx
997    }
998
999    fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
1000        match r.kind() {
1001            ty::ReBound(..) => r,
1002            _ => self.fcx.tcx.lifetimes.re_erased,
1003        }
1004    }
1005
1006    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1007        self.handle_term(ty, Ty::outer_exclusive_binder, Ty::new_error)
1008    }
1009
1010    fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1011        self.handle_term(ct, ty::Const::outer_exclusive_binder, ty::Const::new_error)
1012    }
1013
1014    fn fold_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
1015        assert!(
1016            !self.should_normalize,
1017            "normalizing predicates in writeback is not generally sound"
1018        );
1019        predicate.super_fold_with(self)
1020    }
1021}
1022
1023struct EagerlyNormalizeConsts<'tcx> {
1024    tcx: TyCtxt<'tcx>,
1025    typing_env: ty::TypingEnv<'tcx>,
1026}
1027impl<'tcx> EagerlyNormalizeConsts<'tcx> {
1028    fn new(fcx: &FnCtxt<'_, 'tcx>) -> Self {
1029        // FIXME(#132279, generic_const_exprs): Using `try_normalize_erasing_regions` here
1030        // means we can't handle opaque types in their defining scope.
1031        EagerlyNormalizeConsts { tcx: fcx.tcx, typing_env: fcx.typing_env(fcx.param_env) }
1032    }
1033}
1034
1035impl<'tcx> TypeFolder<TyCtxt<'tcx>> for EagerlyNormalizeConsts<'tcx> {
1036    fn cx(&self) -> TyCtxt<'tcx> {
1037        self.tcx
1038    }
1039
1040    fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1041        self.tcx.try_normalize_erasing_regions(self.typing_env, ct).unwrap_or(ct)
1042    }
1043}
1044
1045struct HasRecursiveOpaque<'a, 'tcx> {
1046    def_id: LocalDefId,
1047    seen: FxHashSet<LocalDefId>,
1048    opaques: &'a FxIndexMap<LocalDefId, ty::OpaqueHiddenType<'tcx>>,
1049    tcx: TyCtxt<'tcx>,
1050}
1051
1052impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasRecursiveOpaque<'_, 'tcx> {
1053    type Result = ControlFlow<()>;
1054
1055    fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1056        if let ty::Alias(ty::Opaque, alias_ty) = *t.kind()
1057            && let Some(def_id) = alias_ty.def_id.as_local()
1058        {
1059            if self.def_id == def_id {
1060                return ControlFlow::Break(());
1061            }
1062
1063            if self.seen.insert(def_id)
1064                && let Some(hidden_ty) = self.opaques.get(&def_id)
1065            {
1066                ty::EarlyBinder::bind(hidden_ty.ty)
1067                    .instantiate(self.tcx, alias_ty.args)
1068                    .visit_with(self)?;
1069            }
1070        }
1071
1072        t.super_visit_with(self)
1073    }
1074}