1use 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::check_opaque_type_parameter_valid;
31use rustc_trait_selection::solve;
32use tracing::{debug, instrument};
33
34use crate::FnCtxt;
35
36impl<'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 let rustc_dump_user_args = self.tcx.has_attr(item_def_id, sym::rustc_dump_user_args);
49
50 let mut wbcx = WritebackCx::new(self, body, rustc_dump_user_args);
51 for param in body.params {
52 wbcx.visit_node_id(param.pat.span, param.hir_id);
53 }
54 match self.tcx.hir_body_owner_kind(item_def_id) {
55 hir::BodyOwnerKind::Const { .. }
57 | hir::BodyOwnerKind::Static(_)
58 | hir::BodyOwnerKind::GlobalAsm => {
59 let item_hir_id = self.tcx.local_def_id_to_hir_id(item_def_id);
60 wbcx.visit_node_id(body.value.span, item_hir_id);
61 }
62 hir::BodyOwnerKind::Closure | hir::BodyOwnerKind::Fn => {}
64 }
65 wbcx.visit_body(body);
66 wbcx.visit_min_capture_map();
67 wbcx.eval_closure_size();
68 wbcx.visit_fake_reads_map();
69 wbcx.visit_closures();
70 wbcx.visit_liberated_fn_sigs();
71 wbcx.visit_fru_field_types();
72 wbcx.visit_opaque_types();
73 wbcx.visit_coercion_casts();
74 wbcx.visit_user_provided_tys();
75 wbcx.visit_user_provided_sigs();
76 wbcx.visit_coroutine_interior();
77 wbcx.visit_transmutes();
78 wbcx.visit_offset_of_container_types();
79 wbcx.visit_potentially_region_dependent_goals();
80
81 wbcx.typeck_results.rvalue_scopes =
82 mem::take(&mut self.typeck_results.borrow_mut().rvalue_scopes);
83
84 let used_trait_imports =
85 mem::take(&mut self.typeck_results.borrow_mut().used_trait_imports);
86 debug!("used_trait_imports({:?}) = {:?}", item_def_id, used_trait_imports);
87 wbcx.typeck_results.used_trait_imports = used_trait_imports;
88
89 debug!("writeback: typeck results for {:?} are {:#?}", item_def_id, wbcx.typeck_results);
90
91 self.tcx.arena.alloc(wbcx.typeck_results)
92 }
93}
94
95struct WritebackCx<'cx, 'tcx> {
101 fcx: &'cx FnCtxt<'cx, 'tcx>,
102
103 typeck_results: ty::TypeckResults<'tcx>,
104
105 body: &'tcx hir::Body<'tcx>,
106
107 rustc_dump_user_args: bool,
108}
109
110impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
111 fn new(
112 fcx: &'cx FnCtxt<'cx, 'tcx>,
113 body: &'tcx hir::Body<'tcx>,
114 rustc_dump_user_args: bool,
115 ) -> WritebackCx<'cx, 'tcx> {
116 let owner = body.id().hir_id.owner;
117
118 let mut wbcx = WritebackCx {
119 fcx,
120 typeck_results: ty::TypeckResults::new(owner),
121 body,
122 rustc_dump_user_args,
123 };
124
125 if let Some(e) = fcx.tainted_by_errors() {
129 wbcx.typeck_results.tainted_by_errors = Some(e);
130 }
131
132 wbcx
133 }
134
135 fn tcx(&self) -> TyCtxt<'tcx> {
136 self.fcx.tcx
137 }
138
139 fn write_ty_to_typeck_results(&mut self, hir_id: HirId, ty: Ty<'tcx>) {
140 debug!("write_ty_to_typeck_results({:?}, {:?})", hir_id, ty);
141 assert!(
142 !ty.has_infer() && !ty.has_placeholders() && !ty.has_free_regions(),
143 "{ty} can't be put into typeck results"
144 );
145 self.typeck_results.node_types_mut().insert(hir_id, ty);
146 }
147
148 fn fix_scalar_builtin_expr(&mut self, e: &hir::Expr<'_>) {
153 match e.kind {
154 hir::ExprKind::Unary(hir::UnOp::Neg | hir::UnOp::Not, inner) => {
155 let inner_ty = self.typeck_results.node_type(inner.hir_id);
156
157 if inner_ty.is_scalar() {
158 self.typeck_results.type_dependent_defs_mut().remove(e.hir_id);
159 self.typeck_results.node_args_mut().remove(e.hir_id);
160 }
161 }
162 hir::ExprKind::Binary(ref op, lhs, rhs) => {
163 let lhs_ty = self.typeck_results.node_type(lhs.hir_id);
164 let rhs_ty = self.typeck_results.node_type(rhs.hir_id);
165
166 if lhs_ty.is_scalar() && rhs_ty.is_scalar() {
167 self.typeck_results.type_dependent_defs_mut().remove(e.hir_id);
168 self.typeck_results.node_args_mut().remove(e.hir_id);
169
170 if !op.node.is_by_value() {
171 let mut adjustments = self.typeck_results.adjustments_mut();
172 if let Some(a) = adjustments.get_mut(lhs.hir_id) {
173 a.pop();
174 }
175 if let Some(a) = adjustments.get_mut(rhs.hir_id) {
176 a.pop();
177 }
178 }
179 }
180 }
181 hir::ExprKind::AssignOp(_, lhs, rhs) => {
182 let lhs_ty = self.typeck_results.node_type(lhs.hir_id);
183 let rhs_ty = self.typeck_results.node_type(rhs.hir_id);
184
185 if lhs_ty.is_scalar() && rhs_ty.is_scalar() {
186 self.typeck_results.type_dependent_defs_mut().remove(e.hir_id);
187 self.typeck_results.node_args_mut().remove(e.hir_id);
188
189 if let Some(a) = self.typeck_results.adjustments_mut().get_mut(lhs.hir_id) {
190 a.pop();
191 }
192 }
193 }
194 _ => {}
195 }
196 }
197
198 fn is_builtin_index(
203 &mut self,
204 e: &hir::Expr<'_>,
205 base_ty: Ty<'tcx>,
206 index_ty: Ty<'tcx>,
207 ) -> bool {
208 if let Some(elem_ty) = base_ty.builtin_index()
209 && let Some(exp_ty) = self.typeck_results.expr_ty_opt(e)
210 {
211 elem_ty == exp_ty && index_ty == self.fcx.tcx.types.usize
212 } else {
213 false
214 }
215 }
216
217 fn fix_index_builtin_expr(&mut self, e: &hir::Expr<'_>) {
222 if let hir::ExprKind::Index(ref base, ref index, _) = e.kind {
223 let base_ty = self.typeck_results.expr_ty_adjusted(base);
225 if let ty::Ref(_, base_ty_inner, _) = *base_ty.kind() {
226 let index_ty = self.typeck_results.expr_ty_adjusted(index);
227 if self.is_builtin_index(e, base_ty_inner, index_ty) {
228 self.typeck_results.type_dependent_defs_mut().remove(e.hir_id);
230 self.typeck_results.node_args_mut().remove(e.hir_id);
231
232 if let Some(a) = self.typeck_results.adjustments_mut().get_mut(base.hir_id)
233 && let Some(Adjustment {
239 kind: Adjust::Pointer(PointerCoercion::Unsize),
240 ..
241 }) = a.pop()
242 {
243 a.pop();
245 }
246 }
247 }
248 }
249 }
250}
251
252impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> {
261 fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
262 match e.kind {
263 hir::ExprKind::Closure(&hir::Closure { body, .. }) => {
264 let body = self.fcx.tcx.hir_body(body);
265 for param in body.params {
266 self.visit_node_id(e.span, param.hir_id);
267 }
268
269 self.visit_body(body);
270 }
271 hir::ExprKind::Struct(_, fields, _) => {
272 for field in fields {
273 self.visit_field_id(field.hir_id);
274 }
275 }
276 hir::ExprKind::Field(..) | hir::ExprKind::OffsetOf(..) => {
277 self.visit_field_id(e.hir_id);
278 }
279 _ => {}
280 }
281
282 self.visit_node_id(e.span, e.hir_id);
283 intravisit::walk_expr(self, e);
284
285 self.fix_scalar_builtin_expr(e);
286 self.fix_index_builtin_expr(e);
287 }
288
289 fn visit_inline_const(&mut self, anon_const: &hir::ConstBlock) {
290 let span = self.tcx().def_span(anon_const.def_id);
291 self.visit_node_id(span, anon_const.hir_id);
292
293 let body = self.tcx().hir_body(anon_const.body);
294 self.visit_body(body);
295 }
296
297 fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
298 match &p.kind {
299 hir::GenericParamKind::Lifetime { .. } => {
300 }
302 hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => {
303 self.tcx()
304 .dcx()
305 .span_delayed_bug(p.span, format!("unexpected generic param: {p:?}"));
306 }
307 }
308 }
309
310 fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) {
311 self.visit_node_id(b.span, b.hir_id);
312 intravisit::walk_block(self, b);
313 }
314
315 fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
316 match p.kind {
317 hir::PatKind::Binding(..) => {
318 let typeck_results = self.fcx.typeck_results.borrow();
319 let bm = typeck_results.extract_binding_mode(self.tcx().sess, p.hir_id, p.span);
320 self.typeck_results.pat_binding_modes_mut().insert(p.hir_id, bm);
321 }
322 hir::PatKind::Struct(_, fields, _) => {
323 for field in fields {
324 self.visit_field_id(field.hir_id);
325 }
326 }
327 _ => {}
328 };
329
330 self.visit_rust_2024_migration_desugared_pats(p.hir_id);
331 self.visit_skipped_ref_pats(p.hir_id);
332 self.visit_pat_adjustments(p.span, p.hir_id);
333
334 self.visit_node_id(p.span, p.hir_id);
335 intravisit::walk_pat(self, p);
336 }
337
338 fn visit_pat_expr(&mut self, expr: &'tcx hir::PatExpr<'tcx>) {
339 self.visit_node_id(expr.span, expr.hir_id);
340 intravisit::walk_pat_expr(self, expr);
341 }
342
343 fn visit_local(&mut self, l: &'tcx hir::LetStmt<'tcx>) {
344 intravisit::walk_local(self, l);
345 let var_ty = self.fcx.local_ty(l.span, l.hir_id);
346 let var_ty = self.resolve(var_ty, &l.span);
347 self.write_ty_to_typeck_results(l.hir_id, var_ty);
348 }
349
350 fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx, AmbigArg>) {
351 intravisit::walk_ty(self, hir_ty);
352 if let Some(ty) = self.fcx.node_ty_opt(hir_ty.hir_id) {
355 let ty = self.resolve(ty, &hir_ty.span);
356 self.write_ty_to_typeck_results(hir_ty.hir_id, ty);
357 }
358 }
359
360 fn visit_infer(
361 &mut self,
362 inf_id: HirId,
363 inf_span: Span,
364 _kind: InferKind<'cx>,
365 ) -> Self::Result {
366 self.visit_id(inf_id);
367
368 if let Some(ty) = self.fcx.node_ty_opt(inf_id) {
372 let ty = self.resolve(ty, &inf_span);
373 self.write_ty_to_typeck_results(inf_id, ty);
374 }
375 }
376}
377
378impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
379 fn eval_closure_size(&mut self) {
380 self.tcx().with_stable_hashing_context(|ref hcx| {
381 let fcx_typeck_results = self.fcx.typeck_results.borrow();
382
383 self.typeck_results.closure_size_eval = fcx_typeck_results
384 .closure_size_eval
385 .to_sorted(hcx, false)
386 .into_iter()
387 .map(|(&closure_def_id, data)| {
388 let closure_hir_id = self.tcx().local_def_id_to_hir_id(closure_def_id);
389 let data = self.resolve(*data, &closure_hir_id);
390 (closure_def_id, data)
391 })
392 .collect();
393 })
394 }
395
396 fn visit_min_capture_map(&mut self) {
397 self.tcx().with_stable_hashing_context(|ref hcx| {
398 let fcx_typeck_results = self.fcx.typeck_results.borrow();
399
400 self.typeck_results.closure_min_captures = fcx_typeck_results
401 .closure_min_captures
402 .to_sorted(hcx, false)
403 .into_iter()
404 .map(|(&closure_def_id, root_min_captures)| {
405 let root_var_map_wb = root_min_captures
406 .iter()
407 .map(|(var_hir_id, min_list)| {
408 let min_list_wb = min_list
409 .iter()
410 .map(|captured_place| {
411 let locatable =
412 captured_place.info.path_expr_id.unwrap_or_else(|| {
413 self.tcx().local_def_id_to_hir_id(closure_def_id)
414 });
415 self.resolve(captured_place.clone(), &locatable)
416 })
417 .collect();
418 (*var_hir_id, min_list_wb)
419 })
420 .collect();
421 (closure_def_id, root_var_map_wb)
422 })
423 .collect();
424 })
425 }
426
427 fn visit_fake_reads_map(&mut self) {
428 self.tcx().with_stable_hashing_context(move |ref hcx| {
429 let fcx_typeck_results = self.fcx.typeck_results.borrow();
430
431 self.typeck_results.closure_fake_reads = fcx_typeck_results
432 .closure_fake_reads
433 .to_sorted(hcx, true)
434 .into_iter()
435 .map(|(&closure_def_id, fake_reads)| {
436 let resolved_fake_reads = fake_reads
437 .iter()
438 .map(|(place, cause, hir_id)| {
439 let locatable = self.tcx().local_def_id_to_hir_id(closure_def_id);
440 let resolved_fake_read = self.resolve(place.clone(), &locatable);
441 (resolved_fake_read, *cause, *hir_id)
442 })
443 .collect();
444
445 (closure_def_id, resolved_fake_reads)
446 })
447 .collect();
448 });
449 }
450
451 fn visit_closures(&mut self) {
452 let fcx_typeck_results = self.fcx.typeck_results.borrow();
453 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
454 let common_hir_owner = fcx_typeck_results.hir_owner;
455
456 let fcx_closure_kind_origins =
457 fcx_typeck_results.closure_kind_origins().items_in_stable_order();
458
459 for (local_id, origin) in fcx_closure_kind_origins {
460 let hir_id = HirId { owner: common_hir_owner, local_id };
461 let place_span = origin.0;
462 let place = self.resolve(origin.1.clone(), &place_span);
463 self.typeck_results.closure_kind_origins_mut().insert(hir_id, (place_span, place));
464 }
465 }
466
467 fn visit_coercion_casts(&mut self) {
468 let fcx_typeck_results = self.fcx.typeck_results.borrow();
469
470 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
471
472 let fcx_coercion_casts = fcx_typeck_results.coercion_casts().to_sorted_stable_ord();
473 for &local_id in fcx_coercion_casts {
474 self.typeck_results.set_coercion_cast(local_id);
475 }
476 }
477
478 fn visit_user_provided_tys(&mut self) {
479 let fcx_typeck_results = self.fcx.typeck_results.borrow();
480 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
481 let common_hir_owner = fcx_typeck_results.hir_owner;
482
483 if self.rustc_dump_user_args {
484 let sorted_user_provided_types =
485 fcx_typeck_results.user_provided_types().items_in_stable_order();
486
487 let mut errors_buffer = Vec::new();
488 for (local_id, c_ty) in sorted_user_provided_types {
489 let hir_id = HirId { owner: common_hir_owner, local_id };
490
491 if let ty::UserTypeKind::TypeOf(_, user_args) = c_ty.value.kind {
492 let span = self.tcx().hir_span(hir_id);
494 let err =
497 self.tcx().dcx().struct_span_err(span, format!("user args: {user_args:?}"));
498 errors_buffer.push(err);
499 }
500 }
501
502 if !errors_buffer.is_empty() {
503 errors_buffer.sort_by_key(|diag| diag.span.primary_span());
504 for err in errors_buffer {
505 err.emit();
506 }
507 }
508 }
509
510 self.typeck_results.user_provided_types_mut().extend(
511 fcx_typeck_results.user_provided_types().items().map(|(local_id, c_ty)| {
512 let hir_id = HirId { owner: common_hir_owner, local_id };
513 (hir_id, *c_ty)
514 }),
515 );
516 }
517
518 fn visit_user_provided_sigs(&mut self) {
519 let fcx_typeck_results = self.fcx.typeck_results.borrow();
520 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
521
522 self.typeck_results.user_provided_sigs.extend_unord(
523 fcx_typeck_results.user_provided_sigs.items().map(|(def_id, c_sig)| (*def_id, *c_sig)),
524 );
525 }
526
527 fn visit_coroutine_interior(&mut self) {
528 let fcx_typeck_results = self.fcx.typeck_results.borrow();
529 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
530 for (predicate, cause) in &fcx_typeck_results.coroutine_stalled_predicates {
531 let (predicate, cause) =
532 self.resolve_coroutine_predicate((*predicate, cause.clone()), &cause.span);
533 self.typeck_results.coroutine_stalled_predicates.insert((predicate, cause));
534 }
535 }
536
537 fn visit_transmutes(&mut self) {
538 let tcx = self.tcx();
539 let fcx_typeck_results = self.fcx.typeck_results.borrow();
540 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
541 for &(from, to, hir_id) in self.fcx.deferred_transmute_checks.borrow().iter() {
542 let span = tcx.hir_span(hir_id);
543 let from = self.resolve(from, &span);
544 let to = self.resolve(to, &span);
545 self.typeck_results.transmutes_to_check.push((from, to, hir_id));
546 }
547 }
548
549 #[instrument(skip(self), level = "debug")]
550 fn visit_opaque_types(&mut self) {
551 let tcx = self.tcx();
552 let opaque_types = self.fcx.infcx.clone_opaque_types();
555 let num_entries = self.fcx.inner.borrow_mut().opaque_types().num_entries();
556 let prev = self.fcx.checked_opaque_types_storage_entries.replace(Some(num_entries));
557 debug_assert_eq!(prev, None);
558 for (opaque_type_key, hidden_type) in opaque_types {
559 let hidden_type = self.resolve(hidden_type, &hidden_type.span);
560 let opaque_type_key = self.resolve(opaque_type_key, &hidden_type.span);
561
562 if !self.fcx.next_trait_solver() {
563 if let ty::Alias(ty::Opaque, alias_ty) = hidden_type.ty.kind()
564 && alias_ty.def_id == opaque_type_key.def_id.to_def_id()
565 && alias_ty.args == opaque_type_key.args
566 {
567 continue;
568 }
569 }
570
571 if let Err(err) = check_opaque_type_parameter_valid(
572 &self.fcx,
573 opaque_type_key,
574 hidden_type.span,
575 DefiningScopeKind::HirTypeck,
576 ) {
577 self.typeck_results.concrete_opaque_types.insert(
578 opaque_type_key.def_id,
579 ty::OpaqueHiddenType::new_error(tcx, err.report(self.fcx)),
580 );
581 }
582
583 let hidden_type = hidden_type.remap_generic_params_to_declaration_params(
584 opaque_type_key,
585 tcx,
586 DefiningScopeKind::HirTypeck,
587 );
588
589 if let Some(prev) = self
590 .typeck_results
591 .concrete_opaque_types
592 .insert(opaque_type_key.def_id, hidden_type)
593 {
594 let entry = &mut self
595 .typeck_results
596 .concrete_opaque_types
597 .get_mut(&opaque_type_key.def_id)
598 .unwrap();
599 if prev.ty != hidden_type.ty {
600 if let Some(guar) = self.typeck_results.tainted_by_errors {
601 entry.ty = Ty::new_error(tcx, guar);
602 } else {
603 let (Ok(guar) | Err(guar)) =
604 prev.build_mismatch_error(&hidden_type, tcx).map(|d| d.emit());
605 entry.ty = Ty::new_error(tcx, guar);
606 }
607 }
608
609 entry.span = prev.span.substitute_dummy(hidden_type.span);
612 }
613 }
614
615 let recursive_opaques: Vec<_> = self
616 .typeck_results
617 .concrete_opaque_types
618 .iter()
619 .filter(|&(&def_id, hidden_ty)| {
620 hidden_ty
621 .ty
622 .visit_with(&mut HasRecursiveOpaque {
623 def_id,
624 seen: Default::default(),
625 opaques: &self.typeck_results.concrete_opaque_types,
626 tcx,
627 })
628 .is_break()
629 })
630 .map(|(def_id, hidden_ty)| (*def_id, hidden_ty.span))
631 .collect();
632 for (def_id, span) in recursive_opaques {
633 let guar = self
634 .fcx
635 .dcx()
636 .struct_span_err(span, "cannot resolve opaque type")
637 .with_code(E0720)
638 .emit();
639 self.typeck_results
640 .concrete_opaque_types
641 .insert(def_id, OpaqueHiddenType { span, ty: Ty::new_error(tcx, guar) });
642 }
643 }
644
645 fn visit_field_id(&mut self, hir_id: HirId) {
646 if let Some(index) = self.fcx.typeck_results.borrow_mut().field_indices_mut().remove(hir_id)
647 {
648 self.typeck_results.field_indices_mut().insert(hir_id, index);
649 }
650 }
651
652 #[instrument(skip(self, span), level = "debug")]
653 fn visit_node_id(&mut self, span: Span, hir_id: HirId) {
654 if let Some(def) =
656 self.fcx.typeck_results.borrow_mut().type_dependent_defs_mut().remove(hir_id)
657 {
658 self.typeck_results.type_dependent_defs_mut().insert(hir_id, def);
659 }
660
661 self.visit_adjustments(span, hir_id);
663
664 let n_ty = self.fcx.node_ty(hir_id);
666 let n_ty = self.resolve(n_ty, &span);
667 self.write_ty_to_typeck_results(hir_id, n_ty);
668 debug!(?n_ty);
669
670 if let Some(args) = self.fcx.typeck_results.borrow().node_args_opt(hir_id) {
672 let args = self.resolve(args, &span);
673 debug!("write_args_to_tcx({:?}, {:?})", hir_id, args);
674 assert!(!args.has_infer() && !args.has_placeholders());
675 self.typeck_results.node_args_mut().insert(hir_id, args);
676 }
677 }
678
679 #[instrument(skip(self, span), level = "debug")]
680 fn visit_adjustments(&mut self, span: Span, hir_id: HirId) {
681 let adjustment = self.fcx.typeck_results.borrow_mut().adjustments_mut().remove(hir_id);
682 match adjustment {
683 None => {
684 debug!("no adjustments for node");
685 }
686
687 Some(adjustment) => {
688 let resolved_adjustment = self.resolve(adjustment, &span);
689 debug!(?resolved_adjustment);
690 self.typeck_results.adjustments_mut().insert(hir_id, resolved_adjustment);
691 }
692 }
693 }
694
695 #[instrument(skip(self), level = "debug")]
696 fn visit_rust_2024_migration_desugared_pats(&mut self, hir_id: hir::HirId) {
697 if let Some(is_hard_error) = self
698 .fcx
699 .typeck_results
700 .borrow_mut()
701 .rust_2024_migration_desugared_pats_mut()
702 .remove(hir_id)
703 {
704 debug!(
705 "node is a pat whose match ergonomics are desugared by the Rust 2024 migration lint"
706 );
707 self.typeck_results
708 .rust_2024_migration_desugared_pats_mut()
709 .insert(hir_id, is_hard_error);
710 }
711 }
712
713 #[instrument(skip(self, span), level = "debug")]
714 fn visit_pat_adjustments(&mut self, span: Span, hir_id: HirId) {
715 let adjustment = self.fcx.typeck_results.borrow_mut().pat_adjustments_mut().remove(hir_id);
716 match adjustment {
717 None => {
718 debug!("no pat_adjustments for node");
719 }
720
721 Some(adjustment) => {
722 let resolved_adjustment = self.resolve(adjustment, &span);
723 debug!(?resolved_adjustment);
724 self.typeck_results.pat_adjustments_mut().insert(hir_id, resolved_adjustment);
725 }
726 }
727 }
728
729 #[instrument(skip(self), level = "debug")]
730 fn visit_skipped_ref_pats(&mut self, hir_id: hir::HirId) {
731 if self.fcx.typeck_results.borrow_mut().skipped_ref_pats_mut().remove(hir_id) {
732 debug!("node is a skipped ref pat");
733 self.typeck_results.skipped_ref_pats_mut().insert(hir_id);
734 }
735 }
736
737 fn visit_liberated_fn_sigs(&mut self) {
738 let fcx_typeck_results = self.fcx.typeck_results.borrow();
739 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
740 let common_hir_owner = fcx_typeck_results.hir_owner;
741
742 let fcx_liberated_fn_sigs = fcx_typeck_results.liberated_fn_sigs().items_in_stable_order();
743
744 for (local_id, &fn_sig) in fcx_liberated_fn_sigs {
745 let hir_id = HirId { owner: common_hir_owner, local_id };
746 let fn_sig = self.resolve(fn_sig, &hir_id);
747 self.typeck_results.liberated_fn_sigs_mut().insert(hir_id, fn_sig);
748 }
749 }
750
751 fn visit_fru_field_types(&mut self) {
752 let fcx_typeck_results = self.fcx.typeck_results.borrow();
753 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
754 let common_hir_owner = fcx_typeck_results.hir_owner;
755
756 let fcx_fru_field_types = fcx_typeck_results.fru_field_types().items_in_stable_order();
757
758 for (local_id, ftys) in fcx_fru_field_types {
759 let hir_id = HirId { owner: common_hir_owner, local_id };
760 let ftys = self.resolve(ftys.clone(), &hir_id);
761 self.typeck_results.fru_field_types_mut().insert(hir_id, ftys);
762 }
763 }
764
765 fn visit_offset_of_container_types(&mut self) {
766 let fcx_typeck_results = self.fcx.typeck_results.borrow();
767 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
768 let common_hir_owner = fcx_typeck_results.hir_owner;
769
770 for (local_id, &(container, ref indices)) in
771 fcx_typeck_results.offset_of_data().items_in_stable_order()
772 {
773 let hir_id = HirId { owner: common_hir_owner, local_id };
774 let container = self.resolve(container, &hir_id);
775 self.typeck_results.offset_of_data_mut().insert(hir_id, (container, indices.clone()));
776 }
777 }
778
779 fn visit_potentially_region_dependent_goals(&mut self) {
780 let obligations = self.fcx.take_hir_typeck_potentially_region_dependent_goals();
781 if let None = self.fcx.tainted_by_errors() {
782 for obligation in obligations {
783 let (predicate, mut cause) =
784 self.fcx.resolve_vars_if_possible((obligation.predicate, obligation.cause));
785 if predicate.has_non_region_infer() {
786 self.fcx.dcx().span_delayed_bug(
787 cause.span,
788 format!("unexpected inference variable after writeback: {predicate:?}"),
789 );
790 } else {
791 let predicate = self.tcx().erase_regions(predicate);
792 if cause.has_infer() || cause.has_placeholders() {
793 cause = self.fcx.misc(cause.span);
796 }
797 self.typeck_results
798 .potentially_region_dependent_goals
799 .insert((predicate, cause));
800 }
801 }
802 }
803 }
804
805 fn resolve<T>(&mut self, value: T, span: &dyn Locatable) -> T
806 where
807 T: TypeFoldable<TyCtxt<'tcx>>,
808 {
809 let value = self.fcx.resolve_vars_if_possible(value);
810
811 let mut goals = vec![];
812 let value =
813 value.fold_with(&mut Resolver::new(self.fcx, span, self.body, true, &mut goals));
814
815 let mut unexpected_goals = vec![];
819 self.typeck_results.coroutine_stalled_predicates.extend(
820 goals
821 .into_iter()
822 .map(|pred| {
823 self.fcx.resolve_vars_if_possible(pred).fold_with(&mut Resolver::new(
824 self.fcx,
825 span,
826 self.body,
827 false,
828 &mut unexpected_goals,
829 ))
830 })
831 .map(|goal| (goal.predicate, self.fcx.misc(span.to_span(self.fcx.tcx)))),
833 );
834 assert_eq!(unexpected_goals, vec![]);
835
836 assert!(!value.has_infer());
837
838 if let Err(guar) = value.error_reported() {
842 self.typeck_results.tainted_by_errors = Some(guar);
843 }
844
845 value
846 }
847
848 fn resolve_coroutine_predicate<T>(&mut self, value: T, span: &dyn Locatable) -> T
849 where
850 T: TypeFoldable<TyCtxt<'tcx>>,
851 {
852 let value = self.fcx.resolve_vars_if_possible(value);
853
854 let mut goals = vec![];
855 let value =
856 value.fold_with(&mut Resolver::new(self.fcx, span, self.body, false, &mut goals));
857 assert_eq!(goals, vec![]);
858
859 assert!(!value.has_infer());
860
861 if let Err(guar) = value.error_reported() {
865 self.typeck_results.tainted_by_errors = Some(guar);
866 }
867
868 value
869 }
870}
871
872pub(crate) trait Locatable {
873 fn to_span(&self, tcx: TyCtxt<'_>) -> Span;
874}
875
876impl Locatable for Span {
877 fn to_span(&self, _: TyCtxt<'_>) -> Span {
878 *self
879 }
880}
881
882impl Locatable for HirId {
883 fn to_span(&self, tcx: TyCtxt<'_>) -> Span {
884 tcx.hir_span(*self)
885 }
886}
887
888struct Resolver<'cx, 'tcx> {
889 fcx: &'cx FnCtxt<'cx, 'tcx>,
890 span: &'cx dyn Locatable,
891 body: &'tcx hir::Body<'tcx>,
892 should_normalize: bool,
895 nested_goals: &'cx mut Vec<Goal<'tcx, ty::Predicate<'tcx>>>,
896}
897
898impl<'cx, 'tcx> Resolver<'cx, 'tcx> {
899 fn new(
900 fcx: &'cx FnCtxt<'cx, 'tcx>,
901 span: &'cx dyn Locatable,
902 body: &'tcx hir::Body<'tcx>,
903 should_normalize: bool,
904 nested_goals: &'cx mut Vec<Goal<'tcx, ty::Predicate<'tcx>>>,
905 ) -> Resolver<'cx, 'tcx> {
906 Resolver { fcx, span, body, nested_goals, should_normalize }
907 }
908
909 fn report_error(&self, p: impl Into<ty::Term<'tcx>>) -> ErrorGuaranteed {
910 if let Some(guar) = self.fcx.tainted_by_errors() {
911 guar
912 } else {
913 self.fcx
914 .err_ctxt()
915 .emit_inference_failure_err(
916 self.fcx.tcx.hir_body_owner_def_id(self.body.id()),
917 self.span.to_span(self.fcx.tcx),
918 p.into(),
919 TypeAnnotationNeeded::E0282,
920 false,
921 )
922 .emit()
923 }
924 }
925
926 fn handle_term<T>(
927 &mut self,
928 value: T,
929 outer_exclusive_binder: impl FnOnce(T) -> ty::DebruijnIndex,
930 new_err: impl Fn(TyCtxt<'tcx>, ErrorGuaranteed) -> T,
931 ) -> T
932 where
933 T: Into<ty::Term<'tcx>> + TypeSuperFoldable<TyCtxt<'tcx>> + Copy,
934 {
935 let tcx = self.fcx.tcx;
936 let mut value = if self.should_normalize && self.fcx.next_trait_solver() {
939 let body_id = tcx.hir_body_owner_def_id(self.body.id());
940 let cause = ObligationCause::misc(self.span.to_span(tcx), body_id);
941 let at = self.fcx.at(&cause, self.fcx.param_env);
942 let universes = vec![None; outer_exclusive_binder(value).as_usize()];
943 match solve::deeply_normalize_with_skipped_universes_and_ambiguous_coroutine_goals(
944 at, value, universes,
945 ) {
946 Ok((value, goals)) => {
947 self.nested_goals.extend(goals);
948 value
949 }
950 Err(errors) => {
951 let guar = self.fcx.err_ctxt().report_fulfillment_errors(errors);
952 new_err(tcx, guar)
953 }
954 }
955 } else {
956 value
957 };
958
959 if value.has_non_region_infer() {
961 let guar = self.report_error(value);
962 value = new_err(tcx, guar);
963 }
964
965 value = fold_regions(tcx, value, |_, _| tcx.lifetimes.re_erased);
975
976 if tcx.features().generic_const_exprs() {
978 value = value.fold_with(&mut EagerlyNormalizeConsts::new(self.fcx));
979 }
980
981 value
982 }
983}
984
985impl<'cx, 'tcx> TypeFolder<TyCtxt<'tcx>> for Resolver<'cx, 'tcx> {
986 fn cx(&self) -> TyCtxt<'tcx> {
987 self.fcx.tcx
988 }
989
990 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
991 debug_assert!(!r.is_bound(), "Should not be resolving bound region.");
992 self.fcx.tcx.lifetimes.re_erased
993 }
994
995 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
996 self.handle_term(ty, Ty::outer_exclusive_binder, Ty::new_error)
997 }
998
999 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1000 self.handle_term(ct, ty::Const::outer_exclusive_binder, ty::Const::new_error)
1001 }
1002
1003 fn fold_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
1004 assert!(
1005 !self.should_normalize,
1006 "normalizing predicates in writeback is not generally sound"
1007 );
1008 predicate.super_fold_with(self)
1009 }
1010}
1011
1012struct EagerlyNormalizeConsts<'tcx> {
1013 tcx: TyCtxt<'tcx>,
1014 typing_env: ty::TypingEnv<'tcx>,
1015}
1016impl<'tcx> EagerlyNormalizeConsts<'tcx> {
1017 fn new(fcx: &FnCtxt<'_, 'tcx>) -> Self {
1018 EagerlyNormalizeConsts { tcx: fcx.tcx, typing_env: fcx.typing_env(fcx.param_env) }
1021 }
1022}
1023
1024impl<'tcx> TypeFolder<TyCtxt<'tcx>> for EagerlyNormalizeConsts<'tcx> {
1025 fn cx(&self) -> TyCtxt<'tcx> {
1026 self.tcx
1027 }
1028
1029 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1030 self.tcx.try_normalize_erasing_regions(self.typing_env, ct).unwrap_or(ct)
1031 }
1032}
1033
1034struct HasRecursiveOpaque<'a, 'tcx> {
1035 def_id: LocalDefId,
1036 seen: FxHashSet<LocalDefId>,
1037 opaques: &'a FxIndexMap<LocalDefId, ty::OpaqueHiddenType<'tcx>>,
1038 tcx: TyCtxt<'tcx>,
1039}
1040
1041impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasRecursiveOpaque<'_, 'tcx> {
1042 type Result = ControlFlow<()>;
1043
1044 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1045 if let ty::Alias(ty::Opaque, alias_ty) = *t.kind()
1046 && let Some(def_id) = alias_ty.def_id.as_local()
1047 {
1048 if self.def_id == def_id {
1049 return ControlFlow::Break(());
1050 }
1051
1052 if self.seen.insert(def_id)
1053 && let Some(hidden_ty) = self.opaques.get(&def_id)
1054 {
1055 ty::EarlyBinder::bind(hidden_ty.ty)
1056 .instantiate(self.tcx, alias_ty.args)
1057 .visit_with(self)?;
1058 }
1059 }
1060
1061 t.super_visit_with(self)
1062 }
1063}