1use std::mem;
6
7use rustc_data_structures::unord::ExtendUnord;
8use rustc_errors::ErrorGuaranteed;
9use rustc_hir::intravisit::{self, InferKind, Visitor};
10use rustc_hir::{self as hir, AmbigArg, HirId};
11use rustc_middle::span_bug;
12use rustc_middle::traits::ObligationCause;
13use rustc_middle::ty::adjustment::{Adjust, Adjustment, PointerCoercion};
14use rustc_middle::ty::{
15 self, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, fold_regions,
16};
17use rustc_span::{Span, sym};
18use rustc_trait_selection::error_reporting::infer::need_type_info::TypeAnnotationNeeded;
19use rustc_trait_selection::solve;
20use tracing::{debug, instrument};
21
22use crate::FnCtxt;
23
24impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
37 pub(crate) fn resolve_type_vars_in_body(
38 &self,
39 body: &'tcx hir::Body<'tcx>,
40 ) -> &'tcx ty::TypeckResults<'tcx> {
41 let item_def_id = self.tcx.hir_body_owner_def_id(body.id());
42
43 let rustc_dump_user_args = self.tcx.has_attr(item_def_id, sym::rustc_dump_user_args);
46
47 let mut wbcx = WritebackCx::new(self, body, rustc_dump_user_args);
48 for param in body.params {
49 wbcx.visit_node_id(param.pat.span, param.hir_id);
50 }
51 match self.tcx.hir_body_owner_kind(item_def_id) {
52 hir::BodyOwnerKind::Const { .. }
54 | hir::BodyOwnerKind::Static(_)
55 | hir::BodyOwnerKind::GlobalAsm => {
56 let item_hir_id = self.tcx.local_def_id_to_hir_id(item_def_id);
57 wbcx.visit_node_id(body.value.span, item_hir_id);
58 }
59 hir::BodyOwnerKind::Closure | hir::BodyOwnerKind::Fn => {}
61 }
62 wbcx.visit_body(body);
63 wbcx.visit_min_capture_map();
64 wbcx.eval_closure_size();
65 wbcx.visit_fake_reads_map();
66 wbcx.visit_closures();
67 wbcx.visit_liberated_fn_sigs();
68 wbcx.visit_fru_field_types();
69 wbcx.visit_opaque_types();
70 wbcx.visit_coercion_casts();
71 wbcx.visit_user_provided_tys();
72 wbcx.visit_user_provided_sigs();
73 wbcx.visit_coroutine_interior();
74 wbcx.visit_offset_of_container_types();
75
76 wbcx.typeck_results.rvalue_scopes =
77 mem::take(&mut self.typeck_results.borrow_mut().rvalue_scopes);
78
79 let used_trait_imports =
80 mem::take(&mut self.typeck_results.borrow_mut().used_trait_imports);
81 debug!("used_trait_imports({:?}) = {:?}", item_def_id, used_trait_imports);
82 wbcx.typeck_results.used_trait_imports = used_trait_imports;
83
84 wbcx.typeck_results.treat_byte_string_as_slice =
85 mem::take(&mut self.typeck_results.borrow_mut().treat_byte_string_as_slice);
86
87 debug!("writeback: typeck results for {:?} are {:#?}", item_def_id, wbcx.typeck_results);
88
89 self.tcx.arena.alloc(wbcx.typeck_results)
90 }
91}
92
93struct 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 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 fn fix_scalar_builtin_expr(&mut self, e: &hir::Expr<'_>) {
154 match e.kind {
155 hir::ExprKind::Unary(hir::UnOp::Neg | hir::UnOp::Not, inner) => {
156 let inner_ty = self.typeck_results.node_type(inner.hir_id);
157
158 if inner_ty.is_scalar() {
159 self.typeck_results.type_dependent_defs_mut().remove(e.hir_id);
160 self.typeck_results.node_args_mut().remove(e.hir_id);
161 }
162 }
163 hir::ExprKind::Binary(ref op, lhs, rhs) | hir::ExprKind::AssignOp(ref op, lhs, rhs) => {
164 let lhs_ty = self.typeck_results.node_type(lhs.hir_id);
165 let rhs_ty = self.typeck_results.node_type(rhs.hir_id);
166
167 if lhs_ty.is_scalar() && rhs_ty.is_scalar() {
168 self.typeck_results.type_dependent_defs_mut().remove(e.hir_id);
169 self.typeck_results.node_args_mut().remove(e.hir_id);
170
171 match e.kind {
172 hir::ExprKind::Binary(..) => {
173 if !op.node.is_by_value() {
174 let mut adjustments = self.typeck_results.adjustments_mut();
175 if let Some(a) = adjustments.get_mut(lhs.hir_id) {
176 a.pop();
177 }
178 if let Some(a) = adjustments.get_mut(rhs.hir_id) {
179 a.pop();
180 }
181 }
182 }
183 hir::ExprKind::AssignOp(..)
184 if let Some(a) =
185 self.typeck_results.adjustments_mut().get_mut(lhs.hir_id) =>
186 {
187 a.pop();
188 }
189 _ => {}
190 }
191 }
192 }
193 _ => {}
194 }
195 }
196
197 fn is_builtin_index(
202 &mut self,
203 e: &hir::Expr<'_>,
204 base_ty: Ty<'tcx>,
205 index_ty: Ty<'tcx>,
206 ) -> bool {
207 if let Some(elem_ty) = base_ty.builtin_index()
208 && let Some(exp_ty) = self.typeck_results.expr_ty_opt(e)
209 {
210 elem_ty == exp_ty && index_ty == self.fcx.tcx.types.usize
211 } else {
212 false
213 }
214 }
215
216 fn fix_index_builtin_expr(&mut self, e: &hir::Expr<'_>) {
221 if let hir::ExprKind::Index(ref base, ref index, _) = e.kind {
222 let base_ty = self.typeck_results.expr_ty_adjusted(base);
224 if let ty::Ref(_, base_ty_inner, _) = *base_ty.kind() {
225 let index_ty = self.typeck_results.expr_ty_adjusted(index);
226 if self.is_builtin_index(e, base_ty_inner, index_ty) {
227 self.typeck_results.type_dependent_defs_mut().remove(e.hir_id);
229 self.typeck_results.node_args_mut().remove(e.hir_id);
230
231 if let Some(a) = self.typeck_results.adjustments_mut().get_mut(base.hir_id) {
232 if let Some(Adjustment {
239 kind: Adjust::Pointer(PointerCoercion::Unsize),
240 ..
241 }) = a.pop()
242 {
243 a.pop();
245 }
246 }
247 }
248 }
249 }
250 }
251}
252
253impl<'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 }
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 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 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 let span = self.tcx().hir().span(hir_id);
495 let err =
498 self.tcx().dcx().struct_span_err(span, format!("user args: {user_args:?}"));
499 errors_buffer.push(err);
500 }
501 }
502
503 if !errors_buffer.is_empty() {
504 errors_buffer.sort_by_key(|diag| diag.span.primary_span());
505 for err in errors_buffer {
506 err.emit();
507 }
508 }
509 }
510
511 self.typeck_results.user_provided_types_mut().extend(
512 fcx_typeck_results.user_provided_types().items().map(|(local_id, c_ty)| {
513 let hir_id = HirId { owner: common_hir_owner, local_id };
514
515 if cfg!(debug_assertions) && c_ty.has_infer() {
516 span_bug!(
517 hir_id.to_span(self.fcx.tcx),
518 "writeback: `{:?}` has inference variables",
519 c_ty
520 );
521 };
522
523 (hir_id, *c_ty)
524 }),
525 );
526 }
527
528 fn visit_user_provided_sigs(&mut self) {
529 let fcx_typeck_results = self.fcx.typeck_results.borrow();
530 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
531
532 self.typeck_results.user_provided_sigs.extend_unord(
533 fcx_typeck_results.user_provided_sigs.items().map(|(&def_id, c_sig)| {
534 if cfg!(debug_assertions) && c_sig.has_infer() {
535 span_bug!(
536 self.fcx.tcx.def_span(def_id),
537 "writeback: `{:?}` has inference variables",
538 c_sig
539 );
540 };
541
542 (def_id, *c_sig)
543 }),
544 );
545 }
546
547 fn visit_coroutine_interior(&mut self) {
548 let fcx_typeck_results = self.fcx.typeck_results.borrow();
549 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
550 for (predicate, cause) in &fcx_typeck_results.coroutine_stalled_predicates {
551 let (predicate, cause) =
552 self.resolve_coroutine_predicate((*predicate, cause.clone()), &cause.span);
553 self.typeck_results.coroutine_stalled_predicates.insert((predicate, cause));
554 }
555 }
556
557 #[instrument(skip(self), level = "debug")]
558 fn visit_opaque_types(&mut self) {
559 let opaque_types = self.fcx.infcx.clone_opaque_types();
568 for (opaque_type_key, hidden_type) in opaque_types {
569 let hidden_type = self.resolve(hidden_type, &hidden_type.span);
570 let opaque_type_key = self.resolve(opaque_type_key, &hidden_type.span);
571
572 if !self.fcx.next_trait_solver() {
573 if let ty::Alias(ty::Opaque, alias_ty) = hidden_type.ty.kind()
574 && alias_ty.def_id == opaque_type_key.def_id.to_def_id()
575 && alias_ty.args == opaque_type_key.args
576 {
577 continue;
578 }
579 }
580
581 if let Some(last_opaque_ty) =
584 self.typeck_results.concrete_opaque_types.insert(opaque_type_key, hidden_type)
585 && last_opaque_ty.ty != hidden_type.ty
586 {
587 assert!(!self.fcx.next_trait_solver());
588 if let Ok(d) = hidden_type.build_mismatch_error(&last_opaque_ty, self.tcx()) {
589 d.emit();
590 }
591 }
592 }
593 }
594
595 fn visit_field_id(&mut self, hir_id: HirId) {
596 if let Some(index) = self.fcx.typeck_results.borrow_mut().field_indices_mut().remove(hir_id)
597 {
598 self.typeck_results.field_indices_mut().insert(hir_id, index);
599 }
600 }
601
602 #[instrument(skip(self, span), level = "debug")]
603 fn visit_node_id(&mut self, span: Span, hir_id: HirId) {
604 if let Some(def) =
606 self.fcx.typeck_results.borrow_mut().type_dependent_defs_mut().remove(hir_id)
607 {
608 self.typeck_results.type_dependent_defs_mut().insert(hir_id, def);
609 }
610
611 self.visit_adjustments(span, hir_id);
613
614 let n_ty = self.fcx.node_ty(hir_id);
616 let n_ty = self.resolve(n_ty, &span);
617 self.write_ty_to_typeck_results(hir_id, n_ty);
618 debug!(?n_ty);
619
620 if let Some(args) = self.fcx.typeck_results.borrow().node_args_opt(hir_id) {
622 let args = self.resolve(args, &span);
623 debug!("write_args_to_tcx({:?}, {:?})", hir_id, args);
624 assert!(!args.has_infer() && !args.has_placeholders());
625 self.typeck_results.node_args_mut().insert(hir_id, args);
626 }
627 }
628
629 #[instrument(skip(self, span), level = "debug")]
630 fn visit_adjustments(&mut self, span: Span, hir_id: HirId) {
631 let adjustment = self.fcx.typeck_results.borrow_mut().adjustments_mut().remove(hir_id);
632 match adjustment {
633 None => {
634 debug!("no adjustments for node");
635 }
636
637 Some(adjustment) => {
638 let resolved_adjustment = self.resolve(adjustment, &span);
639 debug!(?resolved_adjustment);
640 self.typeck_results.adjustments_mut().insert(hir_id, resolved_adjustment);
641 }
642 }
643 }
644
645 #[instrument(skip(self), level = "debug")]
646 fn visit_rust_2024_migration_desugared_pats(&mut self, hir_id: hir::HirId) {
647 if let Some(is_hard_error) = self
648 .fcx
649 .typeck_results
650 .borrow_mut()
651 .rust_2024_migration_desugared_pats_mut()
652 .remove(hir_id)
653 {
654 debug!(
655 "node is a pat whose match ergonomics are desugared by the Rust 2024 migration lint"
656 );
657 self.typeck_results
658 .rust_2024_migration_desugared_pats_mut()
659 .insert(hir_id, is_hard_error);
660 }
661 }
662
663 #[instrument(skip(self, span), level = "debug")]
664 fn visit_pat_adjustments(&mut self, span: Span, hir_id: HirId) {
665 let adjustment = self.fcx.typeck_results.borrow_mut().pat_adjustments_mut().remove(hir_id);
666 match adjustment {
667 None => {
668 debug!("no pat_adjustments for node");
669 }
670
671 Some(adjustment) => {
672 let resolved_adjustment = self.resolve(adjustment, &span);
673 debug!(?resolved_adjustment);
674 self.typeck_results.pat_adjustments_mut().insert(hir_id, resolved_adjustment);
675 }
676 }
677 }
678
679 #[instrument(skip(self), level = "debug")]
680 fn visit_skipped_ref_pats(&mut self, hir_id: hir::HirId) {
681 if self.fcx.typeck_results.borrow_mut().skipped_ref_pats_mut().remove(hir_id) {
682 debug!("node is a skipped ref pat");
683 self.typeck_results.skipped_ref_pats_mut().insert(hir_id);
684 }
685 }
686
687 fn visit_liberated_fn_sigs(&mut self) {
688 let fcx_typeck_results = self.fcx.typeck_results.borrow();
689 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
690 let common_hir_owner = fcx_typeck_results.hir_owner;
691
692 let fcx_liberated_fn_sigs = fcx_typeck_results.liberated_fn_sigs().items_in_stable_order();
693
694 for (local_id, &fn_sig) in fcx_liberated_fn_sigs {
695 let hir_id = HirId { owner: common_hir_owner, local_id };
696 let fn_sig = self.resolve(fn_sig, &hir_id);
697 self.typeck_results.liberated_fn_sigs_mut().insert(hir_id, fn_sig);
698 }
699 }
700
701 fn visit_fru_field_types(&mut self) {
702 let fcx_typeck_results = self.fcx.typeck_results.borrow();
703 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
704 let common_hir_owner = fcx_typeck_results.hir_owner;
705
706 let fcx_fru_field_types = fcx_typeck_results.fru_field_types().items_in_stable_order();
707
708 for (local_id, ftys) in fcx_fru_field_types {
709 let hir_id = HirId { owner: common_hir_owner, local_id };
710 let ftys = self.resolve(ftys.clone(), &hir_id);
711 self.typeck_results.fru_field_types_mut().insert(hir_id, ftys);
712 }
713 }
714
715 fn visit_offset_of_container_types(&mut self) {
716 let fcx_typeck_results = self.fcx.typeck_results.borrow();
717 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
718 let common_hir_owner = fcx_typeck_results.hir_owner;
719
720 for (local_id, &(container, ref indices)) in
721 fcx_typeck_results.offset_of_data().items_in_stable_order()
722 {
723 let hir_id = HirId { owner: common_hir_owner, local_id };
724 let container = self.resolve(container, &hir_id);
725 self.typeck_results.offset_of_data_mut().insert(hir_id, (container, indices.clone()));
726 }
727 }
728
729 fn resolve<T>(&mut self, value: T, span: &dyn Locatable) -> T
730 where
731 T: TypeFoldable<TyCtxt<'tcx>>,
732 {
733 let value = self.fcx.resolve_vars_if_possible(value);
734 let value = value.fold_with(&mut Resolver::new(self.fcx, span, self.body, true));
735 assert!(!value.has_infer());
736
737 if let Err(guar) = value.error_reported() {
741 self.typeck_results.tainted_by_errors = Some(guar);
742 }
743
744 value
745 }
746
747 fn resolve_coroutine_predicate<T>(&mut self, value: T, span: &dyn Locatable) -> T
748 where
749 T: TypeFoldable<TyCtxt<'tcx>>,
750 {
751 let value = self.fcx.resolve_vars_if_possible(value);
752 let value = value.fold_with(&mut Resolver::new(self.fcx, span, self.body, false));
753 assert!(!value.has_infer());
754
755 if let Err(guar) = value.error_reported() {
759 self.typeck_results.tainted_by_errors = Some(guar);
760 }
761
762 value
763 }
764}
765
766pub(crate) trait Locatable {
767 fn to_span(&self, tcx: TyCtxt<'_>) -> Span;
768}
769
770impl Locatable for Span {
771 fn to_span(&self, _: TyCtxt<'_>) -> Span {
772 *self
773 }
774}
775
776impl Locatable for HirId {
777 fn to_span(&self, tcx: TyCtxt<'_>) -> Span {
778 tcx.hir().span(*self)
779 }
780}
781
782struct Resolver<'cx, 'tcx> {
783 fcx: &'cx FnCtxt<'cx, 'tcx>,
784 span: &'cx dyn Locatable,
785 body: &'tcx hir::Body<'tcx>,
786 should_normalize: bool,
789}
790
791impl<'cx, 'tcx> Resolver<'cx, 'tcx> {
792 fn new(
793 fcx: &'cx FnCtxt<'cx, 'tcx>,
794 span: &'cx dyn Locatable,
795 body: &'tcx hir::Body<'tcx>,
796 should_normalize: bool,
797 ) -> Resolver<'cx, 'tcx> {
798 Resolver { fcx, span, body, should_normalize }
799 }
800
801 fn report_error(&self, p: impl Into<ty::GenericArg<'tcx>>) -> ErrorGuaranteed {
802 if let Some(guar) = self.fcx.tainted_by_errors() {
803 guar
804 } else {
805 self.fcx
806 .err_ctxt()
807 .emit_inference_failure_err(
808 self.fcx.tcx.hir_body_owner_def_id(self.body.id()),
809 self.span.to_span(self.fcx.tcx),
810 p.into(),
811 TypeAnnotationNeeded::E0282,
812 false,
813 )
814 .emit()
815 }
816 }
817
818 fn handle_term<T>(
819 &mut self,
820 value: T,
821 outer_exclusive_binder: impl FnOnce(T) -> ty::DebruijnIndex,
822 new_err: impl Fn(TyCtxt<'tcx>, ErrorGuaranteed) -> T,
823 ) -> T
824 where
825 T: Into<ty::GenericArg<'tcx>> + TypeSuperFoldable<TyCtxt<'tcx>> + Copy,
826 {
827 let tcx = self.fcx.tcx;
828 let mut value = if self.should_normalize && self.fcx.next_trait_solver() {
831 let body_id = tcx.hir_body_owner_def_id(self.body.id());
832 let cause = ObligationCause::misc(self.span.to_span(tcx), body_id);
833 let at = self.fcx.at(&cause, self.fcx.param_env);
834 let universes = vec![None; outer_exclusive_binder(value).as_usize()];
835 solve::deeply_normalize_with_skipped_universes(at, value, universes).unwrap_or_else(
836 |errors| {
837 let guar = self.fcx.err_ctxt().report_fulfillment_errors(errors);
838 new_err(tcx, guar)
839 },
840 )
841 } else {
842 value
843 };
844
845 if value.has_non_region_infer() {
847 let guar = self.report_error(value);
848 value = new_err(tcx, guar);
849 }
850
851 value = fold_regions(tcx, value, |_, _| tcx.lifetimes.re_erased);
861
862 if tcx.features().generic_const_exprs() {
864 value = value.fold_with(&mut EagerlyNormalizeConsts::new(self.fcx));
865 }
866
867 value
868 }
869}
870
871impl<'cx, 'tcx> TypeFolder<TyCtxt<'tcx>> for Resolver<'cx, 'tcx> {
872 fn cx(&self) -> TyCtxt<'tcx> {
873 self.fcx.tcx
874 }
875
876 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
877 debug_assert!(!r.is_bound(), "Should not be resolving bound region.");
878 self.fcx.tcx.lifetimes.re_erased
879 }
880
881 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
882 self.handle_term(ty, Ty::outer_exclusive_binder, Ty::new_error)
883 }
884
885 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
886 self.handle_term(ct, ty::Const::outer_exclusive_binder, ty::Const::new_error)
887 }
888
889 fn fold_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
890 assert!(
891 !self.should_normalize,
892 "normalizing predicates in writeback is not generally sound"
893 );
894 predicate.super_fold_with(self)
895 }
896}
897
898struct EagerlyNormalizeConsts<'tcx> {
899 tcx: TyCtxt<'tcx>,
900 typing_env: ty::TypingEnv<'tcx>,
901}
902impl<'tcx> EagerlyNormalizeConsts<'tcx> {
903 fn new(fcx: &FnCtxt<'_, 'tcx>) -> Self {
904 EagerlyNormalizeConsts { tcx: fcx.tcx, typing_env: fcx.typing_env(fcx.param_env) }
907 }
908}
909
910impl<'tcx> TypeFolder<TyCtxt<'tcx>> for EagerlyNormalizeConsts<'tcx> {
911 fn cx(&self) -> TyCtxt<'tcx> {
912 self.tcx
913 }
914
915 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
916 self.tcx.try_normalize_erasing_regions(self.typing_env, ct).unwrap_or(ct)
917 }
918}