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