rustc_hir_typeck/fn_ctxt/
_impl.rs

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    /// Produces warning on the given node, if the current point in the
48    /// function is unreachable, and there hasn't been another warning.
49    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            // If span arose from a desugaring of `if` or `while`, then it is the condition
56            // itself, which diverges, that we are about to lint on. This gives suboptimal
57            // diagnostics. Instead, stop here so that the `if`- or `while`-expression's
58            // block is linted instead.
59            Some(DesugaringKind::CondTemporary) => return,
60
61            // Don't lint if the result of an async block or async function is `!`.
62            // This does not affect the unreachable lints *within* the body.
63            Some(DesugaringKind::Async) => return,
64
65            // Don't lint *within* the `.await` operator, since that's all just desugaring
66            // junk. We only want to lint if there is a subsequent expression after the
67            // `.await` operator.
68            Some(DesugaringKind::Await) => return,
69
70            _ => {}
71        }
72
73        // Don't warn twice.
74        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    /// Resolves type and const variables in `ty` if possible. Unlike the infcx
89    /// version (resolve_vars_if_possible), this version will
90    /// also select obligations if it seems useful, in an effort
91    /// to get more type information.
92    // FIXME(-Znext-solver): A lot of the calls to this method should
93    // probably be `try_structurally_resolve_type` or `structurally_resolve_type` instead.
94    #[instrument(skip(self), level = "debug", ret)]
95    pub(crate) fn resolve_vars_with_obligations(&self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
96        // No Infer()? Nothing needs doing.
97        if !ty.has_non_region_infer() {
98            debug!("no inference var, nothing needs doing");
99            return ty;
100        }
101
102        // If `ty` is a type variable, see whether we already know what it is.
103        ty = self.resolve_vars_if_possible(ty);
104        if !ty.has_non_region_infer() {
105            debug!(?ty);
106            return ty;
107        }
108
109        // If not, try resolving pending obligations as much as
110        // possible. This can help substantially when there are
111        // indirect dependencies that don't seem worth tracking
112        // precisely.
113        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                // Could change this to a bug, but there's lots of diagnostic code re-lowering
155                // or re-typechecking nodes that were already typecked.
156                // Lots of that diagnostics code relies on subtle effects of re-lowering, so we'll
157                // let it keep doing that and just ensure that compilation won't succeed.
158                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    /// Given the args that we just converted from the HIR, try to
204    /// canonicalize them and store them as user-given parameters
205    /// (i.e., parameters that must be respected by the NLL check).
206    ///
207    /// This should be invoked **before any unifications have
208    /// occurred**, so that annotations like `Vec<_>` are preserved
209    /// properly.
210    #[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        // FIXME: is_identity being on `UserType` and not `Canonical<UserType>` is awkward
238        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                    // FIXME(const_trait_impl): We *could* enforce `&T: ~const Deref` here.
276                }
277                Adjust::Pointer(_pointer_coercion) => {
278                    // FIXME(const_trait_impl): We should probably enforce these.
279                }
280                Adjust::ReborrowPin(_mutability) => {
281                    // FIXME(const_trait_impl): We could enforce these; they correspond to
282                    // `&mut T: DerefMut` tho, so it's kinda moot.
283                }
284                Adjust::Borrow(_) => {
285                    // No effects to enforce here.
286                }
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                        // NeverToAny coercion can target any type, so instead of adding a new
314                        // adjustment on top we can change the target.
315                        //
316                        // This is required for things like `a == a` (where `a: !`) to produce
317                        // valid MIR -- we need borrow adjustment from things like `==` to change
318                        // the type to `&!` (or `&()` depending on the fallback). This might be
319                        // relevant even in unreachable code.
320                        *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                            .., // Any following adjustments are allowed.
331                        ],
332                    ) => {
333                        // A reborrow has no effect before a dereference, so we can safely replace adjustments.
334                        *entry.get_mut() = adj;
335                    }
336
337                    _ => {
338                        // FIXME: currently we never try to compose autoderefs
339                        // and ReifyFnPointer/UnsafeFnPointer, but we could.
340                        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 there is an mutable auto-borrow, it is equivalent to `&mut <expr>`.
357        // In this case implicit use of `Deref` and `Index` within `<expr>` should
358        // instead be `DerefMut` and `IndexMut`, so fix those up.
359        if autoborrow_mut {
360            self.convert_place_derefs_to_mutable(expr);
361        }
362    }
363
364    /// Instantiates and normalizes the bounds for a given item
365    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            // Sized types have static alignment, and so do slices.
434            if tail.is_trivially_sized(self.tcx) || matches!(tail.kind(), ty::Slice(..)) {
435                // Nothing else is required here.
436            } else {
437                // We can't be sure, let's required full `Sized`.
438                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    /// Walk a `hir_ty` and collect any clauses that may have come from a type
468    /// within the `hir_ty`. These clauses will be canonicalized with a user type
469    /// annotation so that we can enforce these bounds in borrowck, too.
470    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    // If the type given by the user has free regions, save it for later, since
534    // NLL would like to enforce those. Also pass in types that involve
535    // projections, since those can resolve to `'static` bounds (modulo #54940,
536    // which hopefully will be fixed by the time you see this comment, dear
537    // reader, although I have my doubts). Also pass in types with inference
538    // types, because they may be repeated. Other sorts of things are already
539    // sufficiently enforced with erased regions. =)
540    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    /// Registers an obligation for checking later, during regionck, that `arg` is well-formed.
570    pub(crate) fn register_wf_obligation(
571        &self,
572        arg: ty::GenericArg<'tcx>,
573        span: Span,
574        code: traits::ObligationCauseCode<'tcx>,
575    ) {
576        // WF obligations never themselves fail, so no real need to give a detailed cause:
577        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    /// Registers obligations that all `args` are well-formed.
587    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    // FIXME(arielb1): use this instead of field.ty everywhere
596    // Only for fields! Returns <none> for methods>
597    // Indifferent to privacy flags
598    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    /// Unify the inference variables corresponding to coroutine witnesses, and save all the
615    /// predicates that were stalled on those inference variables.
616    ///
617    /// This process allows to conservatively save all predicates that do depend on the coroutine
618    /// interior types, for later processing by `check_coroutine_obligations`.
619    ///
620    /// We must not attempt to select obligations after this method has run, or risk query cycle
621    /// ICE.
622    #[instrument(level = "debug", skip(self))]
623    pub(crate) fn resolve_coroutine_interiors(&self) {
624        // Try selecting all obligations that are not blocked on inference variables.
625        // Once we start unifying coroutine witnesses, trying to select obligations on them will
626        // trigger query cycle ICEs, as doing so requires MIR.
627        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            // Create the `CoroutineWitness` type that we will unify with `interior`.
636            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            // Unify `interior` with `witness` and collect all the resulting obligations.
643            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                // Will never define opaque types, as all we do is instantiate a type variable.
650                .eq(DefineOpaqueTypes::Yes, interior, witness)
651                .expect("Failed to unify coroutine interior type");
652            let mut obligations = ok.obligations;
653
654            // Also collect the obligations that were unstalled by this unification.
655            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    /// Select as many obligations as we can at present.
679    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    /// For the overloaded place expressions (`*x`, `x[3]`), the trait
692    /// returns a type of `&T`, but the actual type we assign to the
693    /// *expression* is `T`. So this function just peels off the return
694    /// type by one layer to yield `T`.
695    pub(crate) fn make_overloaded_place_return_type(&self, method: MethodCallee<'tcx>) -> Ty<'tcx> {
696        // extract method return type, which will be &T;
697        let ret_ty = method.sig.output();
698
699        // method returns &T, but the type as visible to user is T, so deref
700        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    /// Resolves an associated value path into a base type and associated constant, or method
768    /// resolution. The newly resolved definition is written into `type_dependent_defs`.
769    #[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                // Don't use `self.lower_ty`, since this will register a WF obligation.
786                // If we're trying to call a nonexistent method on a trait
787                // (e.g. `MyTrait::missing_method`), then resolution will
788                // give us a `QPath::TypeRelative` with a trait object as
789                // `qself`. In that case, we want to avoid registering a WF obligation
790                // for `dyn MyTrait`, since we don't actually need the trait
791                // to be dyn-compatible.
792                // We manually call `register_wf_obligation` in the success path
793                // below.
794                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            // Return directly on cache hit. This is useful to avoid doubly reporting
812            // errors with default match binding modes. See #44614.
813            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(), // emits missing method for trait only after edition 2021
837                    );
838                }
839
840                result
841            });
842
843        // Write back the new resolution.
844        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    /// Given a `HirId`, return the `HirId` of the enclosing function and its `FnDecl`.
853    pub(crate) fn get_fn_decl(
854        &self,
855        blk_id: HirId,
856    ) -> Option<(LocalDefId, &'tcx hir::FnDecl<'tcx>)> {
857        // Get enclosing Fn, if it is a function or a trait method, unless there's a `loop` or
858        // `while` before reaching it, as block tail returns are not available in them.
859        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                            // FIXME(async_closures): Implement this.
882                            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    // Instantiates the given path, which must refer to an item with the given
993    // number of type parameters and type.
994    #[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                            // `<T>::assoc` will end up here, and so
1062                            // can `T::assoc`. If this came from an
1063                            // inherent impl, we need to record the
1064                            // `T` for posterity (see `UserSelfTy` for
1065                            // details).
1066                            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        // Now that we have categorized what space the parameters for each
1076        // segment belong to, let's sort out the parameters that the user
1077        // provided (if any) into their appropriate spaces. We'll also report
1078        // errors if type parameters are provided in an inappropriate place.
1079
1080        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            // Don't try to infer type parameters when prohibited generic arguments were given.
1097            user_self_ty = None;
1098        }
1099
1100        // Now we have to compare the types that the user *actually*
1101        // provided against the types that were *expected*. If the user
1102        // did not provide any types, then we want to instantiate inference
1103        // variables. If the user provided some types, we may still need
1104        // to add defaults. If the user provided *too many* types, that's
1105        // a problem.
1106
1107        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            // Argument-position `impl Trait` is treated as a normal generic
1115            // parameter internally, but we don't allow users to specify the
1116            // parameter's value explicitly, so we have to do some error-
1117            // checking here.
1118            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); // See issue #53251.
1131            }
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            // Firstly, check that this SelfCtor even comes from the item we're currently
1146            // typechecking. This can happen because we never validated the resolution of
1147            // SelfCtors, and when we started doing so, we noticed regressions. After
1148            // sufficiently long time, we can remove this check and turn it into a hard
1149            // error in `validate_res_from_ribs` -- it's just difficult to tell whether the
1150            // self type has any generic types during rustc_resolve, which is what we use
1151            // to determine if this is a hard error or warning.
1152            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                    // Check the visibility of the ctor.
1185                    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 we've encountered an `impl Trait`-related error, we're just
1249                    // going to infer the arguments for better error messages.
1250                    if !self.infer_args_for_err.contains(&index) {
1251                        // Check whether the user has provided generic arguments.
1252                        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 (&param.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                        // We handle the ambig portions of `Ty` in match arm below
1275                        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                        // Ambiguous parts of `ConstArg` are handled in the match arms below
1283                        .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                            // If we have a default, then it doesn't matter that we're not inferring
1310                            // the type/const arguments: We provide the default where any is missing.
1311                            return default.instantiate(tcx, preceding_args);
1312                        }
1313                        // If no type/const arguments were provided, we have to infer them.
1314                        // This case also occurs as a result of some malformed input, e.g.,
1315                        // a lifetime argument being given instead of a type/const parameter.
1316                        // Using inference instead of `Error` gives better error messages.
1317                        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        // First, store the "user args" for later.
1342        self.write_user_type_annotation_from_args(hir_id, def_id, args_raw, user_self_ty);
1343
1344        // Normalize only after registering type annotations.
1345        let args = self.normalize(span, args_raw);
1346
1347        self.add_required_obligations_for_hir(span, def_id, args, hir_id);
1348
1349        // Instantiate the values for the type parameters into the type of
1350        // the referenced item.
1351        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            // In the case of `Foo<T>::method` and `<Foo<T>>::method`, if `method`
1358            // is inherent, there is no `Self` parameter; instead, the impl needs
1359            // type parameters, which we can infer by unifying the provided `Self`
1360            // with the instantiated impl type.
1361            // This also occurs for an enum variant on a type alias.
1362            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    /// Add all the obligations that are required, instantiated and normalized appropriately.
1388    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    /// Try to resolve `ty` to a structural type, normalizing aliases.
1422    ///
1423    /// In case there is still ambiguity, the returned type may be an inference
1424    /// variable. This is different from `structurally_resolve_type` which errors
1425    /// in this case.
1426    #[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            // We need to use a separate variable here as otherwise the temporary for
1434            // `self.fulfillment_cx.borrow_mut()` is alive in the `Err` branch, resulting
1435            // in a reentrant borrow, causing an ICE.
1436            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        // FIXME(min_const_generic_exprs): We could process obligations here if `ct` is a var.
1458
1459        if self.next_trait_solver()
1460            && let ty::ConstKind::Unevaluated(..) = ct.kind()
1461        {
1462            // We need to use a separate variable here as otherwise the temporary for
1463            // `self.fulfillment_cx.borrow_mut()` is alive in the `Err` branch, resulting
1464            // in a reentrant borrow, causing an ICE.
1465            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    /// Resolves `ty` by a single level if `ty` is a type variable.
1483    ///
1484    /// When the new solver is enabled, this will also attempt to normalize
1485    /// the type if it's a projection (note that it will not deeply normalize
1486    /// projections within the type, just the outermost layer of the type).
1487    ///
1488    /// If no resolution is possible, then an error is reported.
1489    /// Numeric inference variables may be left unresolved.
1490    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            // FIXME(#120456) - is `swap_remove` correct?
1531            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    /// Instantiate a QueryResponse in a probe context, without a
1538    /// good ObligationCause.
1539    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    /// Returns `true` if an expression is contained inside the LHS of an assignment expression.
1554    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}