1use std::collections::hash_map::Entry;
2use std::slice;
3
4use rustc_abi::FieldIdx;
5use rustc_data_structures::fx::FxHashSet;
6use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan};
7use rustc_hir::def::{CtorOf, DefKind, Res};
8use rustc_hir::def_id::DefId;
9use rustc_hir::intravisit::VisitorExt;
10use rustc_hir::lang_items::LangItem;
11use rustc_hir::{self as hir, AmbigArg, ExprKind, GenericArg, HirId, Node, QPath, intravisit};
12use rustc_hir_analysis::hir_ty_lowering::errors::GenericsArgsErrExtend;
13use rustc_hir_analysis::hir_ty_lowering::generics::{
14 check_generic_arg_count_for_call, lower_generic_args,
15};
16use rustc_hir_analysis::hir_ty_lowering::{
17 ExplicitLateBound, FeedConstTy, GenericArgCountMismatch, GenericArgCountResult,
18 GenericArgsLowerer, GenericPathSegment, HirTyLowerer, IsMethodCall, RegionInferReason,
19};
20use rustc_infer::infer::canonical::{Canonical, OriginalQueryValues, QueryResponse};
21use rustc_infer::infer::{DefineOpaqueTypes, InferResult};
22use rustc_lint::builtin::SELF_CONSTRUCTOR_FROM_OUTER_ITEM;
23use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability};
24use rustc_middle::ty::{
25 self, AdtKind, CanonicalUserType, GenericArgsRef, GenericParamDefKind, IsIdentity, Ty, TyCtxt,
26 TypeFoldable, TypeVisitable, TypeVisitableExt, UserArgs, UserSelfTy,
27};
28use rustc_middle::{bug, span_bug};
29use rustc_session::lint;
30use rustc_span::Span;
31use rustc_span::def_id::LocalDefId;
32use rustc_span::hygiene::DesugaringKind;
33use rustc_trait_selection::error_reporting::infer::need_type_info::TypeAnnotationNeeded;
34use rustc_trait_selection::traits::{
35 self, NormalizeExt, ObligationCauseCode, StructurallyNormalizeExt,
36};
37use tracing::{debug, instrument};
38
39use crate::callee::{self, DeferredCallResolution};
40use crate::errors::{self, CtorIsPrivate};
41use crate::method::{self, MethodCallee};
42use crate::{BreakableCtxt, Diverges, Expectation, FnCtxt, LoweredTy, rvalue_scopes};
43
44impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
45 pub(crate) fn warn_if_unreachable(&self, id: HirId, span: Span, kind: &str) {
48 let Diverges::Always { span: orig_span, custom_note } = self.diverges.get() else {
49 return;
50 };
51
52 match span.desugaring_kind() {
53 Some(DesugaringKind::CondTemporary) => return,
58
59 Some(DesugaringKind::Async) => return,
62
63 Some(DesugaringKind::Await) => return,
67
68 _ => {}
69 }
70
71 self.diverges.set(Diverges::WarnedAlways);
73
74 debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind);
75
76 let msg = format!("unreachable {kind}");
77 self.tcx().node_span_lint(lint::builtin::UNREACHABLE_CODE, id, span, |lint| {
78 lint.primary_message(msg.clone());
79 lint.span_label(span, msg).span_label(
80 orig_span,
81 custom_note.unwrap_or("any code following this expression is unreachable"),
82 );
83 })
84 }
85
86 #[instrument(skip(self), level = "debug", ret)]
93 pub(crate) fn resolve_vars_with_obligations<T: TypeFoldable<TyCtxt<'tcx>>>(
94 &self,
95 mut t: T,
96 ) -> T {
97 if !t.has_non_region_infer() {
99 debug!("no inference var, nothing needs doing");
100 return t;
101 }
102
103 t = self.resolve_vars_if_possible(t);
105 if !t.has_non_region_infer() {
106 debug!(?t);
107 return t;
108 }
109
110 self.select_obligations_where_possible(|_| {});
115 self.resolve_vars_if_possible(t)
116 }
117
118 pub(crate) fn record_deferred_call_resolution(
119 &self,
120 closure_def_id: LocalDefId,
121 r: DeferredCallResolution<'tcx>,
122 ) {
123 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
124 deferred_call_resolutions.entry(closure_def_id).or_default().push(r);
125 }
126
127 pub(crate) fn remove_deferred_call_resolutions(
128 &self,
129 closure_def_id: LocalDefId,
130 ) -> Vec<DeferredCallResolution<'tcx>> {
131 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
132 deferred_call_resolutions.remove(&closure_def_id).unwrap_or_default()
133 }
134
135 fn tag(&self) -> String {
136 format!("{self:p}")
137 }
138
139 pub(crate) fn local_ty(&self, span: Span, nid: HirId) -> Ty<'tcx> {
140 self.locals.borrow().get(&nid).cloned().unwrap_or_else(|| {
141 span_bug!(span, "no type for local variable {}", self.tcx.hir_id_to_string(nid))
142 })
143 }
144
145 #[inline]
146 pub(crate) fn write_ty(&self, id: HirId, ty: Ty<'tcx>) {
147 debug!("write_ty({:?}, {:?}) in fcx {}", id, self.resolve_vars_if_possible(ty), self.tag());
148 let mut typeck = self.typeck_results.borrow_mut();
149 let mut node_ty = typeck.node_types_mut();
150
151 if let Some(prev) = node_ty.insert(id, ty) {
152 if prev.references_error() {
153 node_ty.insert(id, prev);
154 } else if !ty.references_error() {
155 self.dcx().span_delayed_bug(
160 self.tcx.hir_span(id),
161 format!("`{prev}` overridden by `{ty}` for {id:?} in {:?}", self.body_id),
162 );
163 }
164 }
165
166 if let Err(e) = ty.error_reported() {
167 self.set_tainted_by_errors(e);
168 }
169 }
170
171 pub(crate) fn write_field_index(&self, hir_id: HirId, index: FieldIdx) {
172 self.typeck_results.borrow_mut().field_indices_mut().insert(hir_id, index);
173 }
174
175 #[instrument(level = "debug", skip(self))]
176 pub(crate) fn write_resolution(
177 &self,
178 hir_id: HirId,
179 r: Result<(DefKind, DefId), ErrorGuaranteed>,
180 ) {
181 self.typeck_results.borrow_mut().type_dependent_defs_mut().insert(hir_id, r);
182 }
183
184 #[instrument(level = "debug", skip(self))]
185 pub(crate) fn write_method_call_and_enforce_effects(
186 &self,
187 hir_id: HirId,
188 span: Span,
189 method: MethodCallee<'tcx>,
190 ) {
191 self.enforce_context_effects(Some(hir_id), span, method.def_id, method.args);
192 self.write_resolution(hir_id, Ok((DefKind::AssocFn, method.def_id)));
193 self.write_args(hir_id, method.args);
194 }
195
196 fn write_args(&self, node_id: HirId, args: GenericArgsRef<'tcx>) {
197 if !args.is_empty() {
198 debug!("write_args({:?}, {:?}) in fcx {}", node_id, args, self.tag());
199
200 self.typeck_results.borrow_mut().node_args_mut().insert(node_id, args);
201 }
202 }
203
204 #[instrument(skip(self), level = "debug")]
212 pub(crate) fn write_user_type_annotation_from_args(
213 &self,
214 hir_id: HirId,
215 def_id: DefId,
216 args: GenericArgsRef<'tcx>,
217 user_self_ty: Option<UserSelfTy<'tcx>>,
218 ) {
219 debug!("fcx {}", self.tag());
220
221 if matches!(self.tcx.def_kind(def_id), DefKind::ConstParam) {
225 return;
226 }
227
228 if Self::can_contain_user_lifetime_bounds((args, user_self_ty)) {
229 let canonicalized = self.canonicalize_user_type_annotation(ty::UserType::new(
230 ty::UserTypeKind::TypeOf(def_id, UserArgs { args, user_self_ty }),
231 ));
232 debug!(?canonicalized);
233 self.write_user_type_annotation(hir_id, canonicalized);
234 }
235 }
236
237 #[instrument(skip(self), level = "debug")]
238 pub(crate) fn write_user_type_annotation(
239 &self,
240 hir_id: HirId,
241 canonical_user_type_annotation: CanonicalUserType<'tcx>,
242 ) {
243 debug!("fcx {}", self.tag());
244
245 if !canonical_user_type_annotation.is_identity() {
247 self.typeck_results
248 .borrow_mut()
249 .user_provided_types_mut()
250 .insert(hir_id, canonical_user_type_annotation);
251 } else {
252 debug!("skipping identity args");
253 }
254 }
255
256 #[instrument(skip(self, expr), level = "debug")]
257 pub(crate) fn apply_adjustments(&self, expr: &hir::Expr<'_>, adj: Vec<Adjustment<'tcx>>) {
258 debug!("expr = {:#?}", expr);
259
260 if adj.is_empty() {
261 return;
262 }
263
264 let mut expr_ty = self.typeck_results.borrow().expr_ty_adjusted(expr);
265
266 for a in &adj {
267 match a.kind {
268 Adjust::NeverToAny => {
269 if a.target.is_ty_var() {
270 self.diverging_type_vars.borrow_mut().insert(a.target);
271 debug!("apply_adjustments: adding `{:?}` as diverging type var", a.target);
272 }
273 }
274 Adjust::Deref(Some(overloaded_deref)) => {
275 self.enforce_context_effects(
276 None,
277 expr.span,
278 overloaded_deref.method_call(self.tcx),
279 self.tcx.mk_args(&[expr_ty.into()]),
280 );
281 }
282 Adjust::Deref(None) => {
283 }
285 Adjust::Pointer(_pointer_coercion) => {
286 }
288 Adjust::ReborrowPin(_mutability) => {
289 }
292 Adjust::Borrow(_) => {
293 }
295 }
296
297 expr_ty = a.target;
298 }
299
300 let autoborrow_mut = adj.iter().any(|adj| {
301 matches!(
302 adj,
303 &Adjustment {
304 kind: Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::Mut { .. })),
305 ..
306 }
307 )
308 });
309
310 match self.typeck_results.borrow_mut().adjustments_mut().entry(expr.hir_id) {
311 Entry::Vacant(entry) => {
312 entry.insert(adj);
313 }
314 Entry::Occupied(mut entry) => {
315 debug!(" - composing on top of {:?}", entry.get());
316 match (&mut entry.get_mut()[..], &adj[..]) {
317 (
318 [Adjustment { kind: Adjust::NeverToAny, target }],
319 &[.., Adjustment { target: new_target, .. }],
320 ) => {
321 *target = new_target;
329 }
330
331 (
332 &mut [
333 Adjustment { kind: Adjust::Deref(_), .. },
334 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), .. },
335 ],
336 &[
337 Adjustment { kind: Adjust::Deref(_), .. },
338 .., ],
340 ) => {
341 *entry.get_mut() = adj;
343 }
344
345 _ => {
346 self.dcx().span_delayed_bug(
349 expr.span,
350 format!(
351 "while adjusting {:?}, can't compose {:?} and {:?}",
352 expr,
353 entry.get(),
354 adj
355 ),
356 );
357
358 *entry.get_mut() = adj;
359 }
360 }
361 }
362 }
363
364 if autoborrow_mut {
368 self.convert_place_derefs_to_mutable(expr);
369 }
370 }
371
372 pub(crate) fn instantiate_bounds(
374 &self,
375 span: Span,
376 def_id: DefId,
377 args: GenericArgsRef<'tcx>,
378 ) -> ty::InstantiatedPredicates<'tcx> {
379 let bounds = self.tcx.predicates_of(def_id);
380 let result = bounds.instantiate(self.tcx, args);
381 let result = self.normalize(span, result);
382 debug!("instantiate_bounds(bounds={:?}, args={:?}) = {:?}", bounds, args, result);
383 result
384 }
385
386 pub(crate) fn normalize<T>(&self, span: Span, value: T) -> T
387 where
388 T: TypeFoldable<TyCtxt<'tcx>>,
389 {
390 self.register_infer_ok_obligations(
391 self.at(&self.misc(span), self.param_env).normalize(value),
392 )
393 }
394
395 pub(crate) fn require_type_meets(
396 &self,
397 ty: Ty<'tcx>,
398 span: Span,
399 code: traits::ObligationCauseCode<'tcx>,
400 def_id: DefId,
401 ) {
402 self.register_bound(ty, def_id, self.cause(span, code));
403 }
404
405 pub(crate) fn require_type_is_sized(
406 &self,
407 ty: Ty<'tcx>,
408 span: Span,
409 code: traits::ObligationCauseCode<'tcx>,
410 ) {
411 if !ty.references_error() {
412 let lang_item = self.tcx.require_lang_item(LangItem::Sized, span);
413 self.require_type_meets(ty, span, code, lang_item);
414 }
415 }
416
417 pub(crate) fn require_type_is_sized_deferred(
418 &self,
419 ty: Ty<'tcx>,
420 span: Span,
421 code: traits::ObligationCauseCode<'tcx>,
422 ) {
423 if !ty.references_error() {
424 self.deferred_sized_obligations.borrow_mut().push((ty, span, code));
425 }
426 }
427
428 pub(crate) fn require_type_has_static_alignment(&self, ty: Ty<'tcx>, span: Span) {
429 if !ty.references_error() {
430 let tail = self.tcx.struct_tail_raw(
431 ty,
432 |ty| {
433 if self.next_trait_solver() {
434 self.try_structurally_resolve_type(span, ty)
435 } else {
436 self.normalize(span, ty)
437 }
438 },
439 || {},
440 );
441 if tail.is_trivially_sized(self.tcx) || matches!(tail.kind(), ty::Slice(..)) {
443 } else {
445 let lang_item = self.tcx.require_lang_item(LangItem::Sized, span);
447 self.require_type_meets(ty, span, ObligationCauseCode::Misc, lang_item);
448 }
449 }
450 }
451
452 pub(crate) fn register_bound(
453 &self,
454 ty: Ty<'tcx>,
455 def_id: DefId,
456 cause: traits::ObligationCause<'tcx>,
457 ) {
458 if !ty.references_error() {
459 self.fulfillment_cx.borrow_mut().register_bound(
460 self,
461 self.param_env,
462 ty,
463 def_id,
464 cause,
465 );
466 }
467 }
468
469 pub(crate) fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> LoweredTy<'tcx> {
470 let ty = self.lowerer().lower_ty(hir_ty);
471 self.register_wf_obligation(ty.into(), hir_ty.span, ObligationCauseCode::WellFormed(None));
472 LoweredTy::from_raw(self, hir_ty.span, ty)
473 }
474
475 pub(crate) fn collect_impl_trait_clauses_from_hir_ty(
479 &self,
480 hir_ty: &'tcx hir::Ty<'tcx>,
481 ) -> ty::Clauses<'tcx> {
482 struct CollectClauses<'a, 'tcx> {
483 clauses: Vec<ty::Clause<'tcx>>,
484 fcx: &'a FnCtxt<'a, 'tcx>,
485 }
486
487 impl<'tcx> intravisit::Visitor<'tcx> for CollectClauses<'_, 'tcx> {
488 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx, AmbigArg>) {
489 if let Some(clauses) = self.fcx.trait_ascriptions.borrow().get(&ty.hir_id.local_id)
490 {
491 self.clauses.extend(clauses.iter().cloned());
492 }
493 intravisit::walk_ty(self, ty)
494 }
495 }
496
497 let mut clauses = CollectClauses { clauses: vec![], fcx: self };
498 clauses.visit_ty_unambig(hir_ty);
499 self.tcx.mk_clauses(&clauses.clauses)
500 }
501
502 #[instrument(level = "debug", skip_all)]
503 pub(crate) fn lower_ty_saving_user_provided_ty(&self, hir_ty: &'tcx hir::Ty<'tcx>) -> Ty<'tcx> {
504 let ty = self.lower_ty(hir_ty);
505 debug!(?ty);
506
507 if Self::can_contain_user_lifetime_bounds(ty.raw) {
508 let c_ty = self.canonicalize_response(ty::UserType::new(ty::UserTypeKind::Ty(ty.raw)));
509 debug!(?c_ty);
510 self.typeck_results.borrow_mut().user_provided_types_mut().insert(hir_ty.hir_id, c_ty);
511 }
512
513 ty.normalized
514 }
515
516 pub(super) fn user_args_for_adt(ty: LoweredTy<'tcx>) -> UserArgs<'tcx> {
517 match (ty.raw.kind(), ty.normalized.kind()) {
518 (ty::Adt(_, args), _) => UserArgs { args, user_self_ty: None },
519 (_, ty::Adt(adt, args)) => UserArgs {
520 args,
521 user_self_ty: Some(UserSelfTy { impl_def_id: adt.did(), self_ty: ty.raw }),
522 },
523 _ => bug!("non-adt type {:?}", ty),
524 }
525 }
526
527 pub(crate) fn lower_const_arg(
528 &self,
529 const_arg: &'tcx hir::ConstArg<'tcx>,
530 feed: FeedConstTy<'_, 'tcx>,
531 ) -> ty::Const<'tcx> {
532 let ct = self.lowerer().lower_const_arg(const_arg, feed);
533 self.register_wf_obligation(
534 ct.into(),
535 self.tcx.hir_span(const_arg.hir_id),
536 ObligationCauseCode::WellFormed(None),
537 );
538 ct
539 }
540
541 fn can_contain_user_lifetime_bounds<T>(t: T) -> bool
549 where
550 T: TypeVisitable<TyCtxt<'tcx>>,
551 {
552 t.has_free_regions() || t.has_aliases() || t.has_infer_types()
553 }
554
555 pub(crate) fn node_ty(&self, id: HirId) -> Ty<'tcx> {
556 match self.typeck_results.borrow().node_types().get(id) {
557 Some(&t) => t,
558 None if let Some(e) = self.tainted_by_errors() => Ty::new_error(self.tcx, e),
559 None => {
560 bug!("no type for node {} in fcx {}", self.tcx.hir_id_to_string(id), self.tag());
561 }
562 }
563 }
564
565 pub(crate) fn node_ty_opt(&self, id: HirId) -> Option<Ty<'tcx>> {
566 match self.typeck_results.borrow().node_types().get(id) {
567 Some(&t) => Some(t),
568 None if let Some(e) = self.tainted_by_errors() => Some(Ty::new_error(self.tcx, e)),
569 None => None,
570 }
571 }
572
573 pub(crate) fn register_wf_obligation(
575 &self,
576 term: ty::Term<'tcx>,
577 span: Span,
578 code: traits::ObligationCauseCode<'tcx>,
579 ) {
580 let cause = self.cause(span, code);
582 self.register_predicate(traits::Obligation::new(
583 self.tcx,
584 cause,
585 self.param_env,
586 ty::ClauseKind::WellFormed(term),
587 ));
588 }
589
590 pub(crate) fn add_wf_bounds(&self, args: GenericArgsRef<'tcx>, span: Span) {
592 for term in args.iter().filter_map(ty::GenericArg::as_term) {
593 self.register_wf_obligation(term, span, ObligationCauseCode::WellFormed(None));
594 }
595 }
596
597 pub(crate) fn field_ty(
601 &self,
602 span: Span,
603 field: &'tcx ty::FieldDef,
604 args: GenericArgsRef<'tcx>,
605 ) -> Ty<'tcx> {
606 self.normalize(span, field.ty(self.tcx, args))
607 }
608
609 pub(crate) fn resolve_rvalue_scopes(&self, def_id: DefId) {
610 let scope_tree = self.tcx.region_scope_tree(def_id);
611 let rvalue_scopes = { rvalue_scopes::resolve_rvalue_scopes(self, scope_tree, def_id) };
612 let mut typeck_results = self.typeck_results.borrow_mut();
613 typeck_results.rvalue_scopes = rvalue_scopes;
614 }
615
616 #[instrument(level = "debug", skip(self))]
625 pub(crate) fn resolve_coroutine_interiors(&self) {
626 self.select_obligations_where_possible(|_| {});
630
631 let coroutines = std::mem::take(&mut *self.deferred_coroutine_interiors.borrow_mut());
632 debug!(?coroutines);
633
634 let mut obligations = vec![];
635
636 if !self.next_trait_solver() {
637 for &(coroutine_def_id, interior) in coroutines.iter() {
638 debug!(?coroutine_def_id);
639
640 let args = ty::GenericArgs::identity_for_item(
642 self.tcx,
643 self.tcx.typeck_root_def_id(coroutine_def_id.to_def_id()),
644 );
645 let witness =
646 Ty::new_coroutine_witness(self.tcx, coroutine_def_id.to_def_id(), args);
647
648 let span = self.tcx.hir_body_owned_by(coroutine_def_id).value.span;
650 let ty::Infer(ty::InferTy::TyVar(_)) = interior.kind() else {
651 span_bug!(span, "coroutine interior witness not infer: {:?}", interior.kind())
652 };
653 let ok = self
654 .at(&self.misc(span), self.param_env)
655 .eq(DefineOpaqueTypes::Yes, interior, witness)
657 .expect("Failed to unify coroutine interior type");
658
659 obligations.extend(ok.obligations);
660 }
661 }
662
663 if !coroutines.is_empty() {
664 obligations.extend(
665 self.fulfillment_cx
666 .borrow_mut()
667 .drain_stalled_obligations_for_coroutines(&self.infcx),
668 );
669 }
670
671 self.typeck_results
672 .borrow_mut()
673 .coroutine_stalled_predicates
674 .extend(obligations.into_iter().map(|o| (o.predicate, o.cause)));
675 }
676
677 #[instrument(skip(self), level = "debug")]
678 pub(crate) fn report_ambiguity_errors(&self) {
679 let mut errors = self.fulfillment_cx.borrow_mut().collect_remaining_errors(self);
680
681 if !errors.is_empty() {
682 self.adjust_fulfillment_errors_for_expr_obligation(&mut errors);
683 self.err_ctxt().report_fulfillment_errors(errors);
684 }
685 }
686
687 pub(crate) fn select_obligations_where_possible(
689 &self,
690 mutate_fulfillment_errors: impl Fn(&mut Vec<traits::FulfillmentError<'tcx>>),
691 ) {
692 let mut result = self.fulfillment_cx.borrow_mut().select_where_possible(self);
693 if !result.is_empty() {
694 mutate_fulfillment_errors(&mut result);
695 self.adjust_fulfillment_errors_for_expr_obligation(&mut result);
696 self.err_ctxt().report_fulfillment_errors(result);
697 }
698 }
699
700 pub(crate) fn make_overloaded_place_return_type(&self, method: MethodCallee<'tcx>) -> Ty<'tcx> {
705 let ret_ty = method.sig.output();
707
708 ret_ty.builtin_deref(true).unwrap()
710 }
711
712 pub(crate) fn type_var_is_sized(&self, self_ty: ty::TyVid) -> bool {
713 let sized_did = self.tcx.lang_items().sized_trait();
714 self.obligations_for_self_ty(self_ty).into_iter().any(|obligation| {
715 match obligation.predicate.kind().skip_binder() {
716 ty::PredicateKind::Clause(ty::ClauseKind::Trait(data)) => {
717 Some(data.def_id()) == sized_did
718 }
719 _ => false,
720 }
721 })
722 }
723
724 pub(crate) fn err_args(&self, len: usize, guar: ErrorGuaranteed) -> Vec<Ty<'tcx>> {
725 let ty_error = Ty::new_error(self.tcx, guar);
726 vec![ty_error; len]
727 }
728
729 pub(crate) fn resolve_lang_item_path(
730 &self,
731 lang_item: hir::LangItem,
732 span: Span,
733 hir_id: HirId,
734 ) -> (Res, Ty<'tcx>) {
735 let def_id = self.tcx.require_lang_item(lang_item, span);
736 let def_kind = self.tcx.def_kind(def_id);
737
738 let item_ty = if let DefKind::Variant = def_kind {
739 self.tcx.type_of(self.tcx.parent(def_id))
740 } else {
741 self.tcx.type_of(def_id)
742 };
743 let args = self.fresh_args_for_item(span, def_id);
744 let ty = item_ty.instantiate(self.tcx, args);
745
746 self.write_args(hir_id, args);
747 self.write_resolution(hir_id, Ok((def_kind, def_id)));
748
749 let code = match lang_item {
750 hir::LangItem::IntoFutureIntoFuture => {
751 if let hir::Node::Expr(into_future_call) = self.tcx.parent_hir_node(hir_id)
752 && let hir::ExprKind::Call(_, [arg0]) = &into_future_call.kind
753 {
754 Some(ObligationCauseCode::AwaitableExpr(arg0.hir_id))
755 } else {
756 None
757 }
758 }
759 hir::LangItem::IteratorNext | hir::LangItem::IntoIterIntoIter => {
760 Some(ObligationCauseCode::ForLoopIterator)
761 }
762 hir::LangItem::TryTraitFromOutput
763 | hir::LangItem::TryTraitFromResidual
764 | hir::LangItem::TryTraitBranch => Some(ObligationCauseCode::QuestionMark),
765 _ => None,
766 };
767 if let Some(code) = code {
768 self.add_required_obligations_with_code(span, def_id, args, move |_, _| code.clone());
769 } else {
770 self.add_required_obligations_for_hir(span, def_id, args, hir_id);
771 }
772
773 (Res::Def(def_kind, def_id), ty)
774 }
775
776 #[instrument(level = "trace", skip(self), ret)]
779 pub(crate) fn resolve_ty_and_res_fully_qualified_call(
780 &self,
781 qpath: &'tcx QPath<'tcx>,
782 hir_id: HirId,
783 span: Span,
784 ) -> (Res, Option<LoweredTy<'tcx>>, &'tcx [hir::PathSegment<'tcx>]) {
785 let (ty, qself, item_segment) = match *qpath {
786 QPath::Resolved(ref opt_qself, path) => {
787 return (
788 path.res,
789 opt_qself.as_ref().map(|qself| self.lower_ty(qself)),
790 path.segments,
791 );
792 }
793 QPath::TypeRelative(ref qself, ref segment) => {
794 let ty = self.lowerer().lower_ty(qself);
804 (LoweredTy::from_raw(self, span, ty), qself, segment)
805 }
806 QPath::LangItem(..) => {
807 bug!("`resolve_ty_and_res_fully_qualified_call` called on `LangItem`")
808 }
809 };
810
811 self.register_wf_obligation(
812 ty.raw.into(),
813 qself.span,
814 ObligationCauseCode::WellFormed(None),
815 );
816 self.select_obligations_where_possible(|_| {});
817
818 if let Some(&cached_result) = self.typeck_results.borrow().type_dependent_defs().get(hir_id)
819 {
820 let def = cached_result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id));
823 return (def, Some(ty), slice::from_ref(&**item_segment));
824 }
825 let item_name = item_segment.ident;
826 let result = self
827 .resolve_fully_qualified_call(span, item_name, ty.normalized, qself.span, hir_id)
828 .or_else(|error| {
829 let guar = self
830 .dcx()
831 .span_delayed_bug(span, "method resolution should've emitted an error");
832 let result = match error {
833 method::MethodError::PrivateMatch(kind, def_id, _) => Ok((kind, def_id)),
834 _ => Err(guar),
835 };
836
837 let trait_missing_method =
838 matches!(error, method::MethodError::NoMatch(_)) && ty.normalized.is_trait();
839 self.report_method_error(
840 hir_id,
841 ty.normalized,
842 error,
843 Expectation::NoExpectation,
844 trait_missing_method && span.edition().at_least_rust_2021(), );
846
847 result
848 });
849
850 self.write_resolution(hir_id, result);
852 (
853 result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
854 Some(ty),
855 slice::from_ref(&**item_segment),
856 )
857 }
858
859 pub(crate) fn get_fn_decl(
861 &self,
862 blk_id: HirId,
863 ) -> Option<(LocalDefId, &'tcx hir::FnDecl<'tcx>)> {
864 self.tcx.hir_get_fn_id_for_return_block(blk_id).and_then(|item_id| {
867 match self.tcx.hir_node(item_id) {
868 Node::Item(&hir::Item {
869 kind: hir::ItemKind::Fn { sig, .. }, owner_id, ..
870 }) => Some((owner_id.def_id, sig.decl)),
871 Node::TraitItem(&hir::TraitItem {
872 kind: hir::TraitItemKind::Fn(ref sig, ..),
873 owner_id,
874 ..
875 }) => Some((owner_id.def_id, sig.decl)),
876 Node::ImplItem(&hir::ImplItem {
877 kind: hir::ImplItemKind::Fn(ref sig, ..),
878 owner_id,
879 ..
880 }) => Some((owner_id.def_id, sig.decl)),
881 Node::Expr(&hir::Expr {
882 hir_id,
883 kind: hir::ExprKind::Closure(&hir::Closure { def_id, kind, fn_decl, .. }),
884 ..
885 }) => {
886 match kind {
887 hir::ClosureKind::CoroutineClosure(_) => {
888 return None;
890 }
891 hir::ClosureKind::Closure => Some((def_id, fn_decl)),
892 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
893 _,
894 hir::CoroutineSource::Fn,
895 )) => {
896 let (sig, owner_id) = match self.tcx.parent_hir_node(hir_id) {
897 Node::Item(&hir::Item {
898 kind: hir::ItemKind::Fn { ref sig, .. },
899 owner_id,
900 ..
901 }) => (sig, owner_id),
902 Node::TraitItem(&hir::TraitItem {
903 kind: hir::TraitItemKind::Fn(ref sig, ..),
904 owner_id,
905 ..
906 }) => (sig, owner_id),
907 Node::ImplItem(&hir::ImplItem {
908 kind: hir::ImplItemKind::Fn(ref sig, ..),
909 owner_id,
910 ..
911 }) => (sig, owner_id),
912 _ => return None,
913 };
914 Some((owner_id.def_id, sig.decl))
915 }
916 _ => None,
917 }
918 }
919 _ => None,
920 }
921 })
922 }
923
924 pub(crate) fn note_internal_mutation_in_method(
925 &self,
926 err: &mut Diag<'_>,
927 expr: &hir::Expr<'_>,
928 expected: Option<Ty<'tcx>>,
929 found: Ty<'tcx>,
930 ) {
931 if found != self.tcx.types.unit {
932 return;
933 }
934
935 let ExprKind::MethodCall(path_segment, rcvr, ..) = expr.kind else {
936 return;
937 };
938
939 let rcvr_has_the_expected_type = self
940 .typeck_results
941 .borrow()
942 .expr_ty_adjusted_opt(rcvr)
943 .zip(expected)
944 .is_some_and(|(ty, expected_ty)| expected_ty.peel_refs() == ty.peel_refs());
945
946 let prev_call_mutates_and_returns_unit = || {
947 self.typeck_results
948 .borrow()
949 .type_dependent_def_id(expr.hir_id)
950 .map(|def_id| self.tcx.fn_sig(def_id).skip_binder().skip_binder())
951 .and_then(|sig| sig.inputs_and_output.split_last())
952 .is_some_and(|(output, inputs)| {
953 output.is_unit()
954 && inputs
955 .get(0)
956 .and_then(|self_ty| self_ty.ref_mutability())
957 .is_some_and(rustc_ast::Mutability::is_mut)
958 })
959 };
960
961 if !(rcvr_has_the_expected_type || prev_call_mutates_and_returns_unit()) {
962 return;
963 }
964
965 let mut sp = MultiSpan::from_span(path_segment.ident.span);
966 sp.push_span_label(
967 path_segment.ident.span,
968 format!(
969 "this call modifies {} in-place",
970 match rcvr.kind {
971 ExprKind::Path(QPath::Resolved(
972 None,
973 hir::Path { segments: [segment], .. },
974 )) => format!("`{}`", segment.ident),
975 _ => "its receiver".to_string(),
976 }
977 ),
978 );
979
980 let modifies_rcvr_note =
981 format!("method `{}` modifies its receiver in-place", path_segment.ident);
982 if rcvr_has_the_expected_type {
983 sp.push_span_label(
984 rcvr.span,
985 "you probably want to use this value after calling the method...",
986 );
987 err.span_note(sp, modifies_rcvr_note);
988 err.note(format!("...instead of the `()` output of method `{}`", path_segment.ident));
989 } else if let ExprKind::MethodCall(..) = rcvr.kind {
990 err.span_note(
991 sp,
992 modifies_rcvr_note + ", it is not meant to be used in method chains.",
993 );
994 } else {
995 err.span_note(sp, modifies_rcvr_note);
996 }
997 }
998
999 #[instrument(skip(self, span), level = "debug")]
1002 pub(crate) fn instantiate_value_path(
1003 &self,
1004 segments: &'tcx [hir::PathSegment<'tcx>],
1005 self_ty: Option<LoweredTy<'tcx>>,
1006 res: Res,
1007 span: Span,
1008 path_span: Span,
1009 hir_id: HirId,
1010 ) -> (Ty<'tcx>, Res) {
1011 let tcx = self.tcx;
1012
1013 let generic_segments = match res {
1014 Res::Local(_) | Res::SelfCtor(_) => vec![],
1015 Res::Def(kind, def_id) => self.lowerer().probe_generic_path_segments(
1016 segments,
1017 self_ty.map(|ty| ty.raw),
1018 kind,
1019 def_id,
1020 span,
1021 ),
1022 Res::Err => {
1023 return (
1024 Ty::new_error(
1025 tcx,
1026 tcx.dcx().span_delayed_bug(span, "could not resolve path {:?}"),
1027 ),
1028 res,
1029 );
1030 }
1031 _ => bug!("instantiate_value_path on {:?}", res),
1032 };
1033
1034 let mut user_self_ty = None;
1035 let mut is_alias_variant_ctor = false;
1036 let mut err_extend = GenericsArgsErrExtend::None;
1037 match res {
1038 Res::Def(DefKind::Ctor(CtorOf::Variant, _), _) if let Some(self_ty) = self_ty => {
1039 let adt_def = self_ty.normalized.ty_adt_def().unwrap();
1040 user_self_ty =
1041 Some(UserSelfTy { impl_def_id: adt_def.did(), self_ty: self_ty.raw });
1042 is_alias_variant_ctor = true;
1043 err_extend = GenericsArgsErrExtend::DefVariant(segments);
1044 }
1045 Res::Def(DefKind::Ctor(CtorOf::Variant, _), _) => {
1046 err_extend = GenericsArgsErrExtend::DefVariant(segments);
1047 }
1048 Res::Def(DefKind::AssocFn | DefKind::AssocConst, def_id) => {
1049 let assoc_item = tcx.associated_item(def_id);
1050 let container = assoc_item.container;
1051 let container_id = assoc_item.container_id(tcx);
1052 debug!(?def_id, ?container, ?container_id);
1053 match container {
1054 ty::AssocItemContainer::Trait => {
1055 if let Err(e) = callee::check_legal_trait_for_method_call(
1056 tcx,
1057 path_span,
1058 None,
1059 span,
1060 container_id,
1061 self.body_id.to_def_id(),
1062 ) {
1063 self.set_tainted_by_errors(e);
1064 }
1065 }
1066 ty::AssocItemContainer::Impl => {
1067 if segments.len() == 1 {
1068 let self_ty = self_ty.expect("UFCS sugared assoc missing Self").raw;
1074 user_self_ty = Some(UserSelfTy { impl_def_id: container_id, self_ty });
1075 }
1076 }
1077 }
1078 }
1079 _ => {}
1080 }
1081
1082 let indices: FxHashSet<_> =
1088 generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
1089 let generics_err = self.lowerer().prohibit_generic_args(
1090 segments.iter().enumerate().filter_map(|(index, seg)| {
1091 if !indices.contains(&index) || is_alias_variant_ctor { Some(seg) } else { None }
1092 }),
1093 err_extend,
1094 );
1095
1096 if let Res::Local(hid) = res {
1097 let ty = self.local_ty(span, hid);
1098 let ty = self.normalize(span, ty);
1099 return (ty, res);
1100 }
1101
1102 if let Err(_) = generics_err {
1103 user_self_ty = None;
1105 }
1106
1107 let mut infer_args_for_err = None;
1115
1116 let mut explicit_late_bound = ExplicitLateBound::No;
1117 for &GenericPathSegment(def_id, index) in &generic_segments {
1118 let seg = &segments[index];
1119 let generics = tcx.generics_of(def_id);
1120
1121 let arg_count =
1126 check_generic_arg_count_for_call(self, def_id, generics, seg, IsMethodCall::No);
1127
1128 if let ExplicitLateBound::Yes = arg_count.explicit_late_bound {
1129 explicit_late_bound = ExplicitLateBound::Yes;
1130 }
1131
1132 if let Err(GenericArgCountMismatch { reported, .. }) = arg_count.correct {
1133 infer_args_for_err
1134 .get_or_insert_with(|| (reported, FxHashSet::default()))
1135 .1
1136 .insert(index);
1137 self.set_tainted_by_errors(reported); }
1139 }
1140
1141 let has_self = generic_segments
1142 .last()
1143 .is_some_and(|GenericPathSegment(def_id, _)| tcx.generics_of(*def_id).has_self);
1144
1145 let (res, implicit_args) = if let Res::Def(DefKind::ConstParam, def) = res {
1146 (res, Some(ty::GenericArgs::identity_for_item(tcx, tcx.parent(def))))
1156 } else if let Res::SelfCtor(impl_def_id) = res {
1157 let ty = LoweredTy::from_raw(
1158 self,
1159 span,
1160 tcx.at(span).type_of(impl_def_id).instantiate_identity(),
1161 );
1162
1163 if std::iter::successors(Some(self.body_id.to_def_id()), |def_id| {
1171 self.tcx.generics_of(def_id).parent
1172 })
1173 .all(|def_id| def_id != impl_def_id)
1174 {
1175 let sugg = ty.normalized.ty_adt_def().map(|def| errors::ReplaceWithName {
1176 span: path_span,
1177 name: self.tcx.item_name(def.did()).to_ident_string(),
1178 });
1179 if ty.raw.has_param() {
1180 let guar = self.dcx().emit_err(errors::SelfCtorFromOuterItem {
1181 span: path_span,
1182 impl_span: tcx.def_span(impl_def_id),
1183 sugg,
1184 });
1185 return (Ty::new_error(self.tcx, guar), res);
1186 } else {
1187 self.tcx.emit_node_span_lint(
1188 SELF_CONSTRUCTOR_FROM_OUTER_ITEM,
1189 hir_id,
1190 path_span,
1191 errors::SelfCtorFromOuterItemLint {
1192 impl_span: tcx.def_span(impl_def_id),
1193 sugg,
1194 },
1195 );
1196 }
1197 }
1198
1199 match ty.normalized.ty_adt_def() {
1200 Some(adt_def) if adt_def.has_ctor() => {
1201 let (ctor_kind, ctor_def_id) = adt_def.non_enum_variant().ctor.unwrap();
1202 let vis = tcx.visibility(ctor_def_id);
1204 if !vis.is_accessible_from(tcx.parent_module(hir_id).to_def_id(), tcx) {
1205 self.dcx()
1206 .emit_err(CtorIsPrivate { span, def: tcx.def_path_str(adt_def.did()) });
1207 }
1208 let new_res = Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id);
1209 let user_args = Self::user_args_for_adt(ty);
1210 user_self_ty = user_args.user_self_ty;
1211 (new_res, Some(user_args.args))
1212 }
1213 _ => {
1214 let mut err = self.dcx().struct_span_err(
1215 span,
1216 "the `Self` constructor can only be used with tuple or unit structs",
1217 );
1218 if let Some(adt_def) = ty.normalized.ty_adt_def() {
1219 match adt_def.adt_kind() {
1220 AdtKind::Enum => {
1221 err.help("did you mean to use one of the enum's variants?");
1222 }
1223 AdtKind::Struct | AdtKind::Union => {
1224 err.span_suggestion(
1225 span,
1226 "use curly brackets",
1227 "Self { /* fields */ }",
1228 Applicability::HasPlaceholders,
1229 );
1230 }
1231 }
1232 }
1233 let reported = err.emit();
1234 return (Ty::new_error(tcx, reported), res);
1235 }
1236 }
1237 } else {
1238 (res, None)
1239 };
1240 let def_id = res.def_id();
1241
1242 let (correct, infer_args_for_err) = match infer_args_for_err {
1243 Some((reported, args)) => {
1244 (Err(GenericArgCountMismatch { reported, invalid_args: vec![] }), args)
1245 }
1246 None => (Ok(()), Default::default()),
1247 };
1248
1249 let arg_count = GenericArgCountResult { explicit_late_bound, correct };
1250
1251 struct CtorGenericArgsCtxt<'a, 'tcx> {
1252 fcx: &'a FnCtxt<'a, 'tcx>,
1253 span: Span,
1254 generic_segments: &'a [GenericPathSegment],
1255 infer_args_for_err: &'a FxHashSet<usize>,
1256 segments: &'tcx [hir::PathSegment<'tcx>],
1257 }
1258 impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for CtorGenericArgsCtxt<'a, 'tcx> {
1259 fn args_for_def_id(
1260 &mut self,
1261 def_id: DefId,
1262 ) -> (Option<&'a hir::GenericArgs<'tcx>>, bool) {
1263 if let Some(&GenericPathSegment(_, index)) =
1264 self.generic_segments.iter().find(|&GenericPathSegment(did, _)| *did == def_id)
1265 {
1266 if !self.infer_args_for_err.contains(&index) {
1269 if let Some(data) = self.segments[index].args {
1271 return (Some(data), self.segments[index].infer_args);
1272 }
1273 }
1274 return (None, self.segments[index].infer_args);
1275 }
1276
1277 (None, true)
1278 }
1279
1280 fn provided_kind(
1281 &mut self,
1282 preceding_args: &[ty::GenericArg<'tcx>],
1283 param: &ty::GenericParamDef,
1284 arg: &GenericArg<'tcx>,
1285 ) -> ty::GenericArg<'tcx> {
1286 match (¶m.kind, arg) {
1287 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => self
1288 .fcx
1289 .lowerer()
1290 .lower_lifetime(lt, RegionInferReason::Param(param))
1291 .into(),
1292 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
1293 self.fcx.lower_ty(ty.as_unambig_ty()).raw.into()
1295 }
1296 (GenericParamDefKind::Type { .. }, GenericArg::Infer(inf)) => {
1297 self.fcx.lower_ty(&inf.to_ty()).raw.into()
1298 }
1299 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => self
1300 .fcx
1301 .lower_const_arg(
1303 ct.as_unambig_ct(),
1304 FeedConstTy::Param(param.def_id, preceding_args),
1305 )
1306 .into(),
1307 (&GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
1308 self.fcx.ct_infer(Some(param), inf.span).into()
1309 }
1310 _ => unreachable!(),
1311 }
1312 }
1313
1314 fn inferred_kind(
1315 &mut self,
1316 preceding_args: &[ty::GenericArg<'tcx>],
1317 param: &ty::GenericParamDef,
1318 infer_args: bool,
1319 ) -> ty::GenericArg<'tcx> {
1320 let tcx = self.fcx.tcx();
1321 if !infer_args && let Some(default) = param.default_value(tcx) {
1322 return default.instantiate(tcx, preceding_args);
1325 }
1326 self.fcx.var_for_def(self.span, param)
1331 }
1332 }
1333
1334 let args_raw = implicit_args.unwrap_or_else(|| {
1335 lower_generic_args(
1336 self,
1337 def_id,
1338 &[],
1339 has_self,
1340 self_ty.map(|s| s.raw),
1341 &arg_count,
1342 &mut CtorGenericArgsCtxt {
1343 fcx: self,
1344 span,
1345 generic_segments: &generic_segments,
1346 infer_args_for_err: &infer_args_for_err,
1347 segments,
1348 },
1349 )
1350 });
1351
1352 self.write_user_type_annotation_from_args(hir_id, def_id, args_raw, user_self_ty);
1354
1355 let args = self.normalize(span, args_raw);
1357
1358 self.add_required_obligations_for_hir(span, def_id, args, hir_id);
1359
1360 let ty = tcx.type_of(def_id);
1363 assert!(!args.has_escaping_bound_vars());
1364 assert!(!ty.skip_binder().has_escaping_bound_vars());
1365 let ty_instantiated = self.normalize(span, ty.instantiate(tcx, args));
1366
1367 if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty {
1368 let impl_ty = self.normalize(span, tcx.type_of(impl_def_id).instantiate(tcx, args));
1374 let self_ty = self.normalize(span, self_ty);
1375 match self.at(&self.misc(span), self.param_env).eq(
1376 DefineOpaqueTypes::Yes,
1377 impl_ty,
1378 self_ty,
1379 ) {
1380 Ok(ok) => self.register_infer_ok_obligations(ok),
1381 Err(_) => {
1382 self.dcx().span_bug(
1383 span,
1384 format!(
1385 "instantiate_value_path: (UFCS) {self_ty:?} was a subtype of {impl_ty:?} but now is not?",
1386 ),
1387 );
1388 }
1389 }
1390 }
1391
1392 debug!("instantiate_value_path: type of {:?} is {:?}", hir_id, ty_instantiated);
1393 self.write_args(hir_id, args);
1394
1395 (ty_instantiated, res)
1396 }
1397
1398 pub(crate) fn add_required_obligations_for_hir(
1400 &self,
1401 span: Span,
1402 def_id: DefId,
1403 args: GenericArgsRef<'tcx>,
1404 hir_id: HirId,
1405 ) {
1406 self.add_required_obligations_with_code(span, def_id, args, |idx, span| {
1407 ObligationCauseCode::WhereClauseInExpr(def_id, span, hir_id, idx)
1408 })
1409 }
1410
1411 #[instrument(level = "debug", skip(self, code, span, args))]
1412 fn add_required_obligations_with_code(
1413 &self,
1414 span: Span,
1415 def_id: DefId,
1416 args: GenericArgsRef<'tcx>,
1417 code: impl Fn(usize, Span) -> ObligationCauseCode<'tcx>,
1418 ) {
1419 let param_env = self.param_env;
1420
1421 let bounds = self.instantiate_bounds(span, def_id, args);
1422
1423 for obligation in traits::predicates_for_generics(
1424 |idx, predicate_span| self.cause(span, code(idx, predicate_span)),
1425 param_env,
1426 bounds,
1427 ) {
1428 self.register_predicate(obligation);
1429 }
1430 }
1431
1432 #[instrument(level = "debug", skip(self, sp), ret)]
1438 pub(crate) fn try_structurally_resolve_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
1439 let ty = self.resolve_vars_with_obligations(ty);
1440
1441 if self.next_trait_solver()
1442 && let ty::Alias(..) = ty.kind()
1443 {
1444 let result = self
1448 .at(&self.misc(sp), self.param_env)
1449 .structurally_normalize_ty(ty, &mut **self.fulfillment_cx.borrow_mut());
1450 match result {
1451 Ok(normalized_ty) => normalized_ty,
1452 Err(errors) => {
1453 let guar = self.err_ctxt().report_fulfillment_errors(errors);
1454 return Ty::new_error(self.tcx, guar);
1455 }
1456 }
1457 } else {
1458 ty
1459 }
1460 }
1461
1462 #[instrument(level = "debug", skip(self, sp), ret)]
1463 pub(crate) fn try_structurally_resolve_const(
1464 &self,
1465 sp: Span,
1466 ct: ty::Const<'tcx>,
1467 ) -> ty::Const<'tcx> {
1468 let ct = self.resolve_vars_with_obligations(ct);
1469
1470 if self.next_trait_solver()
1471 && let ty::ConstKind::Unevaluated(..) = ct.kind()
1472 {
1473 let result = self
1477 .at(&self.misc(sp), self.param_env)
1478 .structurally_normalize_const(ct, &mut **self.fulfillment_cx.borrow_mut());
1479 match result {
1480 Ok(normalized_ct) => normalized_ct,
1481 Err(errors) => {
1482 let guar = self.err_ctxt().report_fulfillment_errors(errors);
1483 return ty::Const::new_error(self.tcx, guar);
1484 }
1485 }
1486 } else if self.tcx.features().generic_const_exprs() {
1487 rustc_trait_selection::traits::evaluate_const(&self.infcx, ct, self.param_env)
1488 } else {
1489 ct
1490 }
1491 }
1492
1493 pub(crate) fn structurally_resolve_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
1502 let ty = self.try_structurally_resolve_type(sp, ty);
1503
1504 if !ty.is_ty_var() {
1505 ty
1506 } else {
1507 let e = self.tainted_by_errors().unwrap_or_else(|| {
1508 self.err_ctxt()
1509 .emit_inference_failure_err(
1510 self.body_id,
1511 sp,
1512 ty.into(),
1513 TypeAnnotationNeeded::E0282,
1514 true,
1515 )
1516 .emit()
1517 });
1518 let err = Ty::new_error(self.tcx, e);
1519 self.demand_suptype(sp, err, ty);
1520 err
1521 }
1522 }
1523
1524 pub(crate) fn structurally_resolve_const(
1525 &self,
1526 sp: Span,
1527 ct: ty::Const<'tcx>,
1528 ) -> ty::Const<'tcx> {
1529 let ct = self.try_structurally_resolve_const(sp, ct);
1530
1531 if !ct.is_ct_infer() {
1532 ct
1533 } else {
1534 let e = self.tainted_by_errors().unwrap_or_else(|| {
1535 self.err_ctxt()
1536 .emit_inference_failure_err(
1537 self.body_id,
1538 sp,
1539 ct.into(),
1540 TypeAnnotationNeeded::E0282,
1541 true,
1542 )
1543 .emit()
1544 });
1545 ty::Const::new_error(self.tcx, e)
1547 }
1548 }
1549
1550 pub(crate) fn with_breakable_ctxt<F: FnOnce() -> R, R>(
1551 &self,
1552 id: HirId,
1553 ctxt: BreakableCtxt<'tcx>,
1554 f: F,
1555 ) -> (BreakableCtxt<'tcx>, R) {
1556 let index;
1557 {
1558 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
1559 index = enclosing_breakables.stack.len();
1560 enclosing_breakables.by_id.insert(id, index);
1561 enclosing_breakables.stack.push(ctxt);
1562 }
1563 let result = f();
1564 let ctxt = {
1565 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
1566 debug_assert!(enclosing_breakables.stack.len() == index + 1);
1567 enclosing_breakables.by_id.swap_remove(&id).expect("missing breakable context");
1569 enclosing_breakables.stack.pop().expect("missing breakable context")
1570 };
1571 (ctxt, result)
1572 }
1573
1574 pub(crate) fn probe_instantiate_query_response(
1577 &self,
1578 span: Span,
1579 original_values: &OriginalQueryValues<'tcx>,
1580 query_result: &Canonical<'tcx, QueryResponse<'tcx, Ty<'tcx>>>,
1581 ) -> InferResult<'tcx, Ty<'tcx>> {
1582 self.instantiate_query_response_and_region_obligations(
1583 &self.misc(span),
1584 self.param_env,
1585 original_values,
1586 query_result,
1587 )
1588 }
1589
1590 pub(crate) fn expr_in_place(&self, mut expr_id: HirId) -> bool {
1592 let mut contained_in_place = false;
1593
1594 while let hir::Node::Expr(parent_expr) = self.tcx.parent_hir_node(expr_id) {
1595 match &parent_expr.kind {
1596 hir::ExprKind::Assign(lhs, ..) | hir::ExprKind::AssignOp(_, lhs, ..) => {
1597 if lhs.hir_id == expr_id {
1598 contained_in_place = true;
1599 break;
1600 }
1601 }
1602 _ => (),
1603 }
1604 expr_id = parent_expr.hir_id;
1605 }
1606
1607 contained_in_place
1608 }
1609}