]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs
Rollup merge of #89793 - ibraheemdev:from_ptr_range, r=m-ou-se
[rust.git] / compiler / rustc_typeck / src / check / fn_ctxt / _impl.rs
1 use crate::astconv::{
2     AstConv, CreateSubstsForGenericArgsCtxt, ExplicitLateBound, GenericArgCountMismatch,
3     GenericArgCountResult, IsMethodCall, PathSeg,
4 };
5 use crate::check::callee::{self, DeferredCallResolution};
6 use crate::check::method::{self, MethodCallee, SelfSource};
7 use crate::check::{BreakableCtxt, Diverges, Expectation, FnCtxt, LocalTy};
8
9 use rustc_data_structures::captures::Captures;
10 use rustc_data_structures::fx::FxHashSet;
11 use rustc_errors::{Applicability, Diagnostic, ErrorReported};
12 use rustc_hir as hir;
13 use rustc_hir::def::{CtorOf, DefKind, Res};
14 use rustc_hir::def_id::DefId;
15 use rustc_hir::lang_items::LangItem;
16 use rustc_hir::{ExprKind, GenericArg, Node, QPath};
17 use rustc_infer::infer::canonical::{Canonical, OriginalQueryValues, QueryResponse};
18 use rustc_infer::infer::error_reporting::TypeAnnotationNeeded::E0282;
19 use rustc_infer::infer::{InferOk, InferResult};
20 use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability};
21 use rustc_middle::ty::fold::TypeFoldable;
22 use rustc_middle::ty::subst::{
23     self, GenericArgKind, InternalSubsts, Subst, SubstsRef, UserSelfTy, UserSubsts,
24 };
25 use rustc_middle::ty::{
26     self, AdtKind, CanonicalUserType, DefIdTree, GenericParamDefKind, ToPolyTraitRef, ToPredicate,
27     Ty, UserType,
28 };
29 use rustc_session::lint;
30 use rustc_span::hygiene::DesugaringKind;
31 use rustc_span::source_map::{original_sp, DUMMY_SP};
32 use rustc_span::symbol::{kw, sym, Ident};
33 use rustc_span::{self, BytePos, MultiSpan, Span};
34 use rustc_trait_selection::infer::InferCtxtExt as _;
35 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
36 use rustc_trait_selection::traits::{
37     self, ObligationCause, ObligationCauseCode, StatementAsExpression, TraitEngine, TraitEngineExt,
38     WellFormedLoc,
39 };
40
41 use std::collections::hash_map::Entry;
42 use std::iter;
43 use std::slice;
44
45 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
46     /// Produces warning on the given node, if the current point in the
47     /// function is unreachable, and there hasn't been another warning.
48     pub(in super::super) fn warn_if_unreachable(&self, id: hir::HirId, span: Span, kind: &str) {
49         // FIXME: Combine these two 'if' expressions into one once
50         // let chains are implemented
51         if let Diverges::Always { span: orig_span, custom_note } = self.diverges.get() {
52             // If span arose from a desugaring of `if` or `while`, then it is the condition itself,
53             // which diverges, that we are about to lint on. This gives suboptimal diagnostics.
54             // Instead, stop here so that the `if`- or `while`-expression's block is linted instead.
55             if !span.is_desugaring(DesugaringKind::CondTemporary)
56                 && !span.is_desugaring(DesugaringKind::Async)
57                 && !orig_span.is_desugaring(DesugaringKind::Await)
58             {
59                 self.diverges.set(Diverges::WarnedAlways);
60
61                 debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind);
62
63                 self.tcx().struct_span_lint_hir(lint::builtin::UNREACHABLE_CODE, id, span, |lint| {
64                     let msg = format!("unreachable {}", kind);
65                     lint.build(&msg)
66                         .span_label(span, &msg)
67                         .span_label(
68                             orig_span,
69                             custom_note
70                                 .unwrap_or("any code following this expression is unreachable"),
71                         )
72                         .emit();
73                 })
74             }
75         }
76     }
77
78     /// Resolves type and const variables in `ty` if possible. Unlike the infcx
79     /// version (resolve_vars_if_possible), this version will
80     /// also select obligations if it seems useful, in an effort
81     /// to get more type information.
82     pub(in super::super) fn resolve_vars_with_obligations(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
83         self.resolve_vars_with_obligations_and_mutate_fulfillment(ty, |_| {})
84     }
85
86     #[instrument(skip(self, mutate_fulfillment_errors), level = "debug")]
87     pub(in super::super) fn resolve_vars_with_obligations_and_mutate_fulfillment(
88         &self,
89         mut ty: Ty<'tcx>,
90         mutate_fulfillment_errors: impl Fn(&mut Vec<traits::FulfillmentError<'tcx>>),
91     ) -> Ty<'tcx> {
92         // No Infer()? Nothing needs doing.
93         if !ty.has_infer_types_or_consts() {
94             debug!("no inference var, nothing needs doing");
95             return ty;
96         }
97
98         // If `ty` is a type variable, see whether we already know what it is.
99         ty = self.resolve_vars_if_possible(ty);
100         if !ty.has_infer_types_or_consts() {
101             debug!(?ty);
102             return ty;
103         }
104
105         // If not, try resolving pending obligations as much as
106         // possible. This can help substantially when there are
107         // indirect dependencies that don't seem worth tracking
108         // precisely.
109         self.select_obligations_where_possible(false, mutate_fulfillment_errors);
110         ty = self.resolve_vars_if_possible(ty);
111
112         debug!(?ty);
113         ty
114     }
115
116     pub(in super::super) fn record_deferred_call_resolution(
117         &self,
118         closure_def_id: DefId,
119         r: DeferredCallResolution<'tcx>,
120     ) {
121         let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
122         deferred_call_resolutions.entry(closure_def_id).or_default().push(r);
123     }
124
125     pub(in super::super) fn remove_deferred_call_resolutions(
126         &self,
127         closure_def_id: DefId,
128     ) -> Vec<DeferredCallResolution<'tcx>> {
129         let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
130         deferred_call_resolutions.remove(&closure_def_id).unwrap_or_default()
131     }
132
133     pub fn tag(&self) -> String {
134         format!("{:p}", self)
135     }
136
137     pub fn local_ty(&self, span: Span, nid: hir::HirId) -> LocalTy<'tcx> {
138         self.locals.borrow().get(&nid).cloned().unwrap_or_else(|| {
139             span_bug!(span, "no type for local variable {}", self.tcx.hir().node_to_string(nid))
140         })
141     }
142
143     #[inline]
144     pub fn write_ty(&self, id: hir::HirId, ty: Ty<'tcx>) {
145         debug!("write_ty({:?}, {:?}) in fcx {}", id, self.resolve_vars_if_possible(ty), self.tag());
146         self.typeck_results.borrow_mut().node_types_mut().insert(id, ty);
147
148         if ty.references_error() {
149             self.has_errors.set(true);
150             self.set_tainted_by_errors();
151         }
152     }
153
154     pub fn write_field_index(&self, hir_id: hir::HirId, index: usize) {
155         self.typeck_results.borrow_mut().field_indices_mut().insert(hir_id, index);
156     }
157
158     pub(in super::super) fn write_resolution(
159         &self,
160         hir_id: hir::HirId,
161         r: Result<(DefKind, DefId), ErrorReported>,
162     ) {
163         self.typeck_results.borrow_mut().type_dependent_defs_mut().insert(hir_id, r);
164     }
165
166     pub fn write_method_call(&self, hir_id: hir::HirId, method: MethodCallee<'tcx>) {
167         debug!("write_method_call(hir_id={:?}, method={:?})", hir_id, method);
168         self.write_resolution(hir_id, Ok((DefKind::AssocFn, method.def_id)));
169         self.write_substs(hir_id, method.substs);
170
171         // When the method is confirmed, the `method.substs` includes
172         // parameters from not just the method, but also the impl of
173         // the method -- in particular, the `Self` type will be fully
174         // resolved. However, those are not something that the "user
175         // specified" -- i.e., those types come from the inferred type
176         // of the receiver, not something the user wrote. So when we
177         // create the user-substs, we want to replace those earlier
178         // types with just the types that the user actually wrote --
179         // that is, those that appear on the *method itself*.
180         //
181         // As an example, if the user wrote something like
182         // `foo.bar::<u32>(...)` -- the `Self` type here will be the
183         // type of `foo` (possibly adjusted), but we don't want to
184         // include that. We want just the `[_, u32]` part.
185         if !method.substs.is_empty() {
186             let method_generics = self.tcx.generics_of(method.def_id);
187             if !method_generics.params.is_empty() {
188                 let user_type_annotation = self.infcx.probe(|_| {
189                     let user_substs = UserSubsts {
190                         substs: InternalSubsts::for_item(self.tcx, method.def_id, |param, _| {
191                             let i = param.index as usize;
192                             if i < method_generics.parent_count {
193                                 self.infcx.var_for_def(DUMMY_SP, param)
194                             } else {
195                                 method.substs[i]
196                             }
197                         }),
198                         user_self_ty: None, // not relevant here
199                     };
200
201                     self.infcx.canonicalize_user_type_annotation(UserType::TypeOf(
202                         method.def_id,
203                         user_substs,
204                     ))
205                 });
206
207                 debug!("write_method_call: user_type_annotation={:?}", user_type_annotation);
208                 self.write_user_type_annotation(hir_id, user_type_annotation);
209             }
210         }
211     }
212
213     pub fn write_substs(&self, node_id: hir::HirId, substs: SubstsRef<'tcx>) {
214         if !substs.is_empty() {
215             debug!("write_substs({:?}, {:?}) in fcx {}", node_id, substs, self.tag());
216
217             self.typeck_results.borrow_mut().node_substs_mut().insert(node_id, substs);
218         }
219     }
220
221     /// Given the substs that we just converted from the HIR, try to
222     /// canonicalize them and store them as user-given substitutions
223     /// (i.e., substitutions that must be respected by the NLL check).
224     ///
225     /// This should be invoked **before any unifications have
226     /// occurred**, so that annotations like `Vec<_>` are preserved
227     /// properly.
228     #[instrument(skip(self), level = "debug")]
229     pub fn write_user_type_annotation_from_substs(
230         &self,
231         hir_id: hir::HirId,
232         def_id: DefId,
233         substs: SubstsRef<'tcx>,
234         user_self_ty: Option<UserSelfTy<'tcx>>,
235     ) {
236         debug!("fcx {}", self.tag());
237
238         if Self::can_contain_user_lifetime_bounds((substs, user_self_ty)) {
239             let canonicalized = self.infcx.canonicalize_user_type_annotation(UserType::TypeOf(
240                 def_id,
241                 UserSubsts { substs, user_self_ty },
242             ));
243             debug!(?canonicalized);
244             self.write_user_type_annotation(hir_id, canonicalized);
245         }
246     }
247
248     #[instrument(skip(self), level = "debug")]
249     pub fn write_user_type_annotation(
250         &self,
251         hir_id: hir::HirId,
252         canonical_user_type_annotation: CanonicalUserType<'tcx>,
253     ) {
254         debug!("fcx {}", self.tag());
255
256         if !canonical_user_type_annotation.is_identity() {
257             self.typeck_results
258                 .borrow_mut()
259                 .user_provided_types_mut()
260                 .insert(hir_id, canonical_user_type_annotation);
261         } else {
262             debug!("skipping identity substs");
263         }
264     }
265
266     #[instrument(skip(self, expr), level = "debug")]
267     pub fn apply_adjustments(&self, expr: &hir::Expr<'_>, adj: Vec<Adjustment<'tcx>>) {
268         debug!("expr = {:#?}", expr);
269
270         if adj.is_empty() {
271             return;
272         }
273
274         for a in &adj {
275             if let Adjust::NeverToAny = a.kind {
276                 if a.target.is_ty_var() {
277                     self.diverging_type_vars.borrow_mut().insert(a.target);
278                     debug!("apply_adjustments: adding `{:?}` as diverging type var", a.target);
279                 }
280             }
281         }
282
283         let autoborrow_mut = adj.iter().any(|adj| {
284             matches!(
285                 adj,
286                 &Adjustment {
287                     kind: Adjust::Borrow(AutoBorrow::Ref(_, AutoBorrowMutability::Mut { .. })),
288                     ..
289                 }
290             )
291         });
292
293         match self.typeck_results.borrow_mut().adjustments_mut().entry(expr.hir_id) {
294             Entry::Vacant(entry) => {
295                 entry.insert(adj);
296             }
297             Entry::Occupied(mut entry) => {
298                 debug!(" - composing on top of {:?}", entry.get());
299                 match (&entry.get()[..], &adj[..]) {
300                     // Applying any adjustment on top of a NeverToAny
301                     // is a valid NeverToAny adjustment, because it can't
302                     // be reached.
303                     (&[Adjustment { kind: Adjust::NeverToAny, .. }], _) => return,
304                     (
305                         &[
306                             Adjustment { kind: Adjust::Deref(_), .. },
307                             Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), .. },
308                         ],
309                         &[
310                             Adjustment { kind: Adjust::Deref(_), .. },
311                             .., // Any following adjustments are allowed.
312                         ],
313                     ) => {
314                         // A reborrow has no effect before a dereference.
315                     }
316                     // Catch cases which have Deref(None)
317                     // having them slip to bug! causes ICE
318                     // see #94291 for more info
319                     (&[Adjustment { kind: Adjust::Deref(None), .. }], _) => {
320                         self.tcx.sess.delay_span_bug(
321                             DUMMY_SP,
322                             &format!("Can't compose Deref(None) expressions"),
323                         )
324                     }
325                     // FIXME: currently we never try to compose autoderefs
326                     // and ReifyFnPointer/UnsafeFnPointer, but we could.
327                     _ => bug!(
328                         "while adjusting {:?}, can't compose {:?} and {:?}",
329                         expr,
330                         entry.get(),
331                         adj
332                     ),
333                 };
334                 *entry.get_mut() = adj;
335             }
336         }
337
338         // If there is an mutable auto-borrow, it is equivalent to `&mut <expr>`.
339         // In this case implicit use of `Deref` and `Index` within `<expr>` should
340         // instead be `DerefMut` and `IndexMut`, so fix those up.
341         if autoborrow_mut {
342             self.convert_place_derefs_to_mutable(expr);
343         }
344     }
345
346     /// Basically whenever we are converting from a type scheme into
347     /// the fn body space, we always want to normalize associated
348     /// types as well. This function combines the two.
349     fn instantiate_type_scheme<T>(&self, span: Span, substs: SubstsRef<'tcx>, value: T) -> T
350     where
351         T: TypeFoldable<'tcx>,
352     {
353         debug!("instantiate_type_scheme(value={:?}, substs={:?})", value, substs);
354         let value = value.subst(self.tcx, substs);
355         let result = self.normalize_associated_types_in(span, value);
356         debug!("instantiate_type_scheme = {:?}", result);
357         result
358     }
359
360     /// As `instantiate_type_scheme`, but for the bounds found in a
361     /// generic type scheme.
362     pub(in super::super) fn instantiate_bounds(
363         &self,
364         span: Span,
365         def_id: DefId,
366         substs: SubstsRef<'tcx>,
367     ) -> (ty::InstantiatedPredicates<'tcx>, Vec<Span>) {
368         let bounds = self.tcx.predicates_of(def_id);
369         let spans: Vec<Span> = bounds.predicates.iter().map(|(_, span)| *span).collect();
370         let result = bounds.instantiate(self.tcx, substs);
371         let result = self.normalize_associated_types_in(span, result);
372         debug!(
373             "instantiate_bounds(bounds={:?}, substs={:?}) = {:?}, {:?}",
374             bounds, substs, result, spans,
375         );
376         (result, spans)
377     }
378
379     /// Replaces the opaque types from the given value with type variables,
380     /// and records the `OpaqueTypeMap` for later use during writeback. See
381     /// `InferCtxt::instantiate_opaque_types` for more details.
382     #[instrument(skip(self, value_span), level = "debug")]
383     pub(in super::super) fn instantiate_opaque_types_from_value<T: TypeFoldable<'tcx>>(
384         &self,
385         value: T,
386         value_span: Span,
387     ) -> T {
388         self.register_infer_ok_obligations(self.instantiate_opaque_types(
389             self.body_id,
390             self.param_env,
391             value,
392             value_span,
393         ))
394     }
395
396     /// Convenience method which tracks extra diagnostic information for normalization
397     /// that occurs as a result of WF checking. The `hir_id` is the `HirId` of the hir item
398     /// whose type is being wf-checked - this is used to construct a more precise span if
399     /// an error occurs.
400     ///
401     /// It is never necessary to call this method - calling `normalize_associated_types_in` will
402     /// just result in a slightly worse diagnostic span, and will still be sound.
403     pub(in super::super) fn normalize_associated_types_in_wf<T>(
404         &self,
405         span: Span,
406         value: T,
407         loc: WellFormedLoc,
408     ) -> T
409     where
410         T: TypeFoldable<'tcx>,
411     {
412         self.inh.normalize_associated_types_in_with_cause(
413             ObligationCause::new(span, self.body_id, ObligationCauseCode::WellFormed(Some(loc))),
414             self.param_env,
415             value,
416         )
417     }
418
419     pub(in super::super) fn normalize_associated_types_in<T>(&self, span: Span, value: T) -> T
420     where
421         T: TypeFoldable<'tcx>,
422     {
423         self.inh.normalize_associated_types_in(span, self.body_id, self.param_env, value)
424     }
425
426     pub(in super::super) fn normalize_associated_types_in_as_infer_ok<T>(
427         &self,
428         span: Span,
429         value: T,
430     ) -> InferOk<'tcx, T>
431     where
432         T: TypeFoldable<'tcx>,
433     {
434         self.inh.partially_normalize_associated_types_in(
435             ObligationCause::misc(span, self.body_id),
436             self.param_env,
437             value,
438         )
439     }
440
441     pub(in super::super) fn normalize_op_associated_types_in_as_infer_ok<T>(
442         &self,
443         span: Span,
444         value: T,
445         opt_input_expr: Option<&hir::Expr<'_>>,
446     ) -> InferOk<'tcx, T>
447     where
448         T: TypeFoldable<'tcx>,
449     {
450         self.inh.partially_normalize_associated_types_in(
451             ObligationCause::new(
452                 span,
453                 self.body_id,
454                 traits::BinOp {
455                     rhs_span: opt_input_expr.map(|expr| expr.span),
456                     is_lit: opt_input_expr
457                         .map_or(false, |expr| matches!(expr.kind, ExprKind::Lit(_))),
458                 },
459             ),
460             self.param_env,
461             value,
462         )
463     }
464
465     pub fn require_type_meets(
466         &self,
467         ty: Ty<'tcx>,
468         span: Span,
469         code: traits::ObligationCauseCode<'tcx>,
470         def_id: DefId,
471     ) {
472         self.register_bound(ty, def_id, traits::ObligationCause::new(span, self.body_id, code));
473     }
474
475     pub fn require_type_is_sized(
476         &self,
477         ty: Ty<'tcx>,
478         span: Span,
479         code: traits::ObligationCauseCode<'tcx>,
480     ) {
481         if !ty.references_error() {
482             let lang_item = self.tcx.require_lang_item(LangItem::Sized, None);
483             self.require_type_meets(ty, span, code, lang_item);
484         }
485     }
486
487     pub fn require_type_is_sized_deferred(
488         &self,
489         ty: Ty<'tcx>,
490         span: Span,
491         code: traits::ObligationCauseCode<'tcx>,
492     ) {
493         if !ty.references_error() {
494             self.deferred_sized_obligations.borrow_mut().push((ty, span, code));
495         }
496     }
497
498     pub fn register_bound(
499         &self,
500         ty: Ty<'tcx>,
501         def_id: DefId,
502         cause: traits::ObligationCause<'tcx>,
503     ) {
504         if !ty.references_error() {
505             self.fulfillment_cx.borrow_mut().register_bound(
506                 self,
507                 self.param_env,
508                 ty,
509                 def_id,
510                 cause,
511             );
512         }
513     }
514
515     pub fn to_ty(&self, ast_t: &hir::Ty<'_>) -> Ty<'tcx> {
516         let t = <dyn AstConv<'_>>::ast_ty_to_ty(self, ast_t);
517         self.register_wf_obligation(t.into(), ast_t.span, traits::MiscObligation);
518         t
519     }
520
521     pub fn to_ty_saving_user_provided_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
522         let ty = self.to_ty(ast_ty);
523         debug!("to_ty_saving_user_provided_ty: ty={:?}", ty);
524
525         if Self::can_contain_user_lifetime_bounds(ty) {
526             let c_ty = self.infcx.canonicalize_response(UserType::Ty(ty));
527             debug!("to_ty_saving_user_provided_ty: c_ty={:?}", c_ty);
528             self.typeck_results.borrow_mut().user_provided_types_mut().insert(ast_ty.hir_id, c_ty);
529         }
530
531         ty
532     }
533
534     pub fn array_length_to_const(&self, length: &hir::ArrayLen) -> ty::Const<'tcx> {
535         match length {
536             &hir::ArrayLen::Infer(_, span) => self.ct_infer(self.tcx.types.usize, None, span),
537             hir::ArrayLen::Body(anon_const) => self.to_const(anon_const),
538         }
539     }
540
541     pub fn to_const(&self, ast_c: &hir::AnonConst) -> ty::Const<'tcx> {
542         let const_def_id = self.tcx.hir().local_def_id(ast_c.hir_id);
543         let c = ty::Const::from_anon_const(self.tcx, const_def_id);
544         self.register_wf_obligation(
545             c.into(),
546             self.tcx.hir().span(ast_c.hir_id),
547             ObligationCauseCode::MiscObligation,
548         );
549         c
550     }
551
552     pub fn const_arg_to_const(
553         &self,
554         ast_c: &hir::AnonConst,
555         param_def_id: DefId,
556     ) -> ty::Const<'tcx> {
557         let const_def = ty::WithOptConstParam {
558             did: self.tcx.hir().local_def_id(ast_c.hir_id),
559             const_param_did: Some(param_def_id),
560         };
561         let c = ty::Const::from_opt_const_arg_anon_const(self.tcx, const_def);
562         self.register_wf_obligation(
563             c.into(),
564             self.tcx.hir().span(ast_c.hir_id),
565             ObligationCauseCode::MiscObligation,
566         );
567         c
568     }
569
570     // If the type given by the user has free regions, save it for later, since
571     // NLL would like to enforce those. Also pass in types that involve
572     // projections, since those can resolve to `'static` bounds (modulo #54940,
573     // which hopefully will be fixed by the time you see this comment, dear
574     // reader, although I have my doubts). Also pass in types with inference
575     // types, because they may be repeated. Other sorts of things are already
576     // sufficiently enforced with erased regions. =)
577     fn can_contain_user_lifetime_bounds<T>(t: T) -> bool
578     where
579         T: TypeFoldable<'tcx>,
580     {
581         t.has_free_regions() || t.has_projections() || t.has_infer_types()
582     }
583
584     pub fn node_ty(&self, id: hir::HirId) -> Ty<'tcx> {
585         match self.typeck_results.borrow().node_types().get(id) {
586             Some(&t) => t,
587             None if self.is_tainted_by_errors() => self.tcx.ty_error(),
588             None => {
589                 bug!(
590                     "no type for node {}: {} in fcx {}",
591                     id,
592                     self.tcx.hir().node_to_string(id),
593                     self.tag()
594                 );
595             }
596         }
597     }
598
599     pub fn node_ty_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
600         match self.typeck_results.borrow().node_types().get(id) {
601             Some(&t) => Some(t),
602             None if self.is_tainted_by_errors() => Some(self.tcx.ty_error()),
603             None => None,
604         }
605     }
606
607     /// Registers an obligation for checking later, during regionck, that `arg` is well-formed.
608     pub fn register_wf_obligation(
609         &self,
610         arg: subst::GenericArg<'tcx>,
611         span: Span,
612         code: traits::ObligationCauseCode<'tcx>,
613     ) {
614         // WF obligations never themselves fail, so no real need to give a detailed cause:
615         let cause = traits::ObligationCause::new(span, self.body_id, code);
616         self.register_predicate(traits::Obligation::new(
617             cause,
618             self.param_env,
619             ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(self.tcx),
620         ));
621     }
622
623     /// Registers obligations that all `substs` are well-formed.
624     pub fn add_wf_bounds(&self, substs: SubstsRef<'tcx>, expr: &hir::Expr<'_>) {
625         for arg in substs.iter().filter(|arg| {
626             matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
627         }) {
628             self.register_wf_obligation(arg, expr.span, traits::MiscObligation);
629         }
630     }
631
632     // FIXME(arielb1): use this instead of field.ty everywhere
633     // Only for fields! Returns <none> for methods>
634     // Indifferent to privacy flags
635     pub fn field_ty(
636         &self,
637         span: Span,
638         field: &'tcx ty::FieldDef,
639         substs: SubstsRef<'tcx>,
640     ) -> Ty<'tcx> {
641         self.normalize_associated_types_in(span, field.ty(self.tcx, substs))
642     }
643
644     pub(in super::super) fn resolve_generator_interiors(&self, def_id: DefId) {
645         let mut generators = self.deferred_generator_interiors.borrow_mut();
646         for (body_id, interior, kind) in generators.drain(..) {
647             self.select_obligations_where_possible(false, |_| {});
648             crate::check::generator_interior::resolve_interior(
649                 self, def_id, body_id, interior, kind,
650             );
651         }
652     }
653
654     #[instrument(skip(self), level = "debug")]
655     pub(in super::super) fn select_all_obligations_or_error(&self) {
656         let errors = self.fulfillment_cx.borrow_mut().select_all_or_error(&self);
657
658         if !errors.is_empty() {
659             self.report_fulfillment_errors(&errors, self.inh.body_id, false);
660         }
661     }
662
663     /// Select as many obligations as we can at present.
664     pub(in super::super) fn select_obligations_where_possible(
665         &self,
666         fallback_has_occurred: bool,
667         mutate_fulfillment_errors: impl Fn(&mut Vec<traits::FulfillmentError<'tcx>>),
668     ) {
669         let mut result = self.fulfillment_cx.borrow_mut().select_where_possible(self);
670         if !result.is_empty() {
671             mutate_fulfillment_errors(&mut result);
672             self.report_fulfillment_errors(&result, self.inh.body_id, fallback_has_occurred);
673         }
674     }
675
676     /// For the overloaded place expressions (`*x`, `x[3]`), the trait
677     /// returns a type of `&T`, but the actual type we assign to the
678     /// *expression* is `T`. So this function just peels off the return
679     /// type by one layer to yield `T`.
680     pub(in super::super) fn make_overloaded_place_return_type(
681         &self,
682         method: MethodCallee<'tcx>,
683     ) -> ty::TypeAndMut<'tcx> {
684         // extract method return type, which will be &T;
685         let ret_ty = method.sig.output();
686
687         // method returns &T, but the type as visible to user is T, so deref
688         ret_ty.builtin_deref(true).unwrap()
689     }
690
691     #[instrument(skip(self), level = "debug")]
692     fn self_type_matches_expected_vid(
693         &self,
694         trait_ref: ty::PolyTraitRef<'tcx>,
695         expected_vid: ty::TyVid,
696     ) -> bool {
697         let self_ty = self.shallow_resolve(trait_ref.skip_binder().self_ty());
698         debug!(?self_ty);
699
700         match *self_ty.kind() {
701             ty::Infer(ty::TyVar(found_vid)) => {
702                 // FIXME: consider using `sub_root_var` here so we
703                 // can see through subtyping.
704                 let found_vid = self.root_var(found_vid);
705                 debug!("self_type_matches_expected_vid - found_vid={:?}", found_vid);
706                 expected_vid == found_vid
707             }
708             _ => false,
709         }
710     }
711
712     #[instrument(skip(self), level = "debug")]
713     pub(in super::super) fn obligations_for_self_ty<'b>(
714         &'b self,
715         self_ty: ty::TyVid,
716     ) -> impl Iterator<Item = (ty::PolyTraitRef<'tcx>, traits::PredicateObligation<'tcx>)>
717     + Captures<'tcx>
718     + 'b {
719         // FIXME: consider using `sub_root_var` here so we
720         // can see through subtyping.
721         let ty_var_root = self.root_var(self_ty);
722         trace!("pending_obligations = {:#?}", self.fulfillment_cx.borrow().pending_obligations());
723
724         self.fulfillment_cx
725             .borrow()
726             .pending_obligations()
727             .into_iter()
728             .filter_map(move |obligation| {
729                 let bound_predicate = obligation.predicate.kind();
730                 match bound_predicate.skip_binder() {
731                     ty::PredicateKind::Projection(data) => Some((
732                         bound_predicate.rebind(data).required_poly_trait_ref(self.tcx),
733                         obligation,
734                     )),
735                     ty::PredicateKind::Trait(data) => {
736                         Some((bound_predicate.rebind(data).to_poly_trait_ref(), obligation))
737                     }
738                     ty::PredicateKind::Subtype(..) => None,
739                     ty::PredicateKind::Coerce(..) => None,
740                     ty::PredicateKind::RegionOutlives(..) => None,
741                     ty::PredicateKind::TypeOutlives(..) => None,
742                     ty::PredicateKind::WellFormed(..) => None,
743                     ty::PredicateKind::ObjectSafe(..) => None,
744                     ty::PredicateKind::ConstEvaluatable(..) => None,
745                     ty::PredicateKind::ConstEquate(..) => None,
746                     // N.B., this predicate is created by breaking down a
747                     // `ClosureType: FnFoo()` predicate, where
748                     // `ClosureType` represents some `Closure`. It can't
749                     // possibly be referring to the current closure,
750                     // because we haven't produced the `Closure` for
751                     // this closure yet; this is exactly why the other
752                     // code is looking for a self type of an unresolved
753                     // inference variable.
754                     ty::PredicateKind::ClosureKind(..) => None,
755                     ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
756                 }
757             })
758             .filter(move |(tr, _)| self.self_type_matches_expected_vid(*tr, ty_var_root))
759     }
760
761     pub(in super::super) fn type_var_is_sized(&self, self_ty: ty::TyVid) -> bool {
762         self.obligations_for_self_ty(self_ty)
763             .any(|(tr, _)| Some(tr.def_id()) == self.tcx.lang_items().sized_trait())
764     }
765
766     pub(in super::super) fn err_args(&self, len: usize) -> Vec<Ty<'tcx>> {
767         vec![self.tcx.ty_error(); len]
768     }
769
770     /// Unifies the output type with the expected type early, for more coercions
771     /// and forward type information on the input expressions.
772     #[instrument(skip(self, call_span), level = "debug")]
773     pub(in super::super) fn expected_inputs_for_expected_output(
774         &self,
775         call_span: Span,
776         expected_ret: Expectation<'tcx>,
777         formal_ret: Ty<'tcx>,
778         formal_args: &[Ty<'tcx>],
779     ) -> Vec<Ty<'tcx>> {
780         let formal_ret = self.resolve_vars_with_obligations(formal_ret);
781         let Some(ret_ty) = expected_ret.only_has_type(self) else { return Vec::new() };
782         let expect_args = self
783             .fudge_inference_if_ok(|| {
784                 // Attempt to apply a subtyping relationship between the formal
785                 // return type (likely containing type variables if the function
786                 // is polymorphic) and the expected return type.
787                 // No argument expectations are produced if unification fails.
788                 let origin = self.misc(call_span);
789                 let ures = self.at(&origin, self.param_env).sup(ret_ty, formal_ret);
790
791                 // FIXME(#27336) can't use ? here, Try::from_error doesn't default
792                 // to identity so the resulting type is not constrained.
793                 match ures {
794                     Ok(ok) => {
795                         // Process any obligations locally as much as
796                         // we can.  We don't care if some things turn
797                         // out unconstrained or ambiguous, as we're
798                         // just trying to get hints here.
799                         let errors = self.save_and_restore_in_snapshot_flag(|_| {
800                             let mut fulfill = <dyn TraitEngine<'_>>::new(self.tcx);
801                             for obligation in ok.obligations {
802                                 fulfill.register_predicate_obligation(self, obligation);
803                             }
804                             fulfill.select_where_possible(self)
805                         });
806
807                         if !errors.is_empty() {
808                             return Err(());
809                         }
810                     }
811                     Err(_) => return Err(()),
812                 }
813
814                 // Record all the argument types, with the substitutions
815                 // produced from the above subtyping unification.
816                 Ok(formal_args.iter().map(|&ty| self.resolve_vars_if_possible(ty)).collect())
817             })
818             .unwrap_or_default();
819         debug!(?formal_args, ?formal_ret, ?expect_args, ?expected_ret);
820         expect_args
821     }
822
823     pub(in super::super) fn resolve_lang_item_path(
824         &self,
825         lang_item: hir::LangItem,
826         span: Span,
827         hir_id: hir::HirId,
828         expr_hir_id: Option<hir::HirId>,
829     ) -> (Res, Ty<'tcx>) {
830         let def_id = self.tcx.require_lang_item(lang_item, Some(span));
831         let def_kind = self.tcx.def_kind(def_id);
832
833         let item_ty = if let DefKind::Variant = def_kind {
834             self.tcx.type_of(self.tcx.parent(def_id).expect("variant w/out parent"))
835         } else {
836             self.tcx.type_of(def_id)
837         };
838         let substs = self.infcx.fresh_substs_for_item(span, def_id);
839         let ty = item_ty.subst(self.tcx, substs);
840
841         self.write_resolution(hir_id, Ok((def_kind, def_id)));
842         self.add_required_obligations_with_code(
843             span,
844             def_id,
845             &substs,
846             match lang_item {
847                 hir::LangItem::IntoFutureIntoFuture => {
848                     ObligationCauseCode::AwaitableExpr(expr_hir_id)
849                 }
850                 hir::LangItem::IteratorNext | hir::LangItem::IntoIterIntoIter => {
851                     ObligationCauseCode::ForLoopIterator
852                 }
853                 hir::LangItem::TryTraitFromOutput
854                 | hir::LangItem::TryTraitFromResidual
855                 | hir::LangItem::TryTraitBranch => ObligationCauseCode::QuestionMark,
856                 _ => traits::ItemObligation(def_id),
857             },
858         );
859         (Res::Def(def_kind, def_id), ty)
860     }
861
862     /// Resolves an associated value path into a base type and associated constant, or method
863     /// resolution. The newly resolved definition is written into `type_dependent_defs`.
864     pub fn resolve_ty_and_res_fully_qualified_call(
865         &self,
866         qpath: &'tcx QPath<'tcx>,
867         hir_id: hir::HirId,
868         span: Span,
869     ) -> (Res, Option<Ty<'tcx>>, &'tcx [hir::PathSegment<'tcx>]) {
870         debug!(
871             "resolve_ty_and_res_fully_qualified_call: qpath={:?} hir_id={:?} span={:?}",
872             qpath, hir_id, span
873         );
874         let (ty, qself, item_segment) = match *qpath {
875             QPath::Resolved(ref opt_qself, ref path) => {
876                 return (
877                     path.res,
878                     opt_qself.as_ref().map(|qself| self.to_ty(qself)),
879                     path.segments,
880                 );
881             }
882             QPath::TypeRelative(ref qself, ref segment) => {
883                 // Don't use `self.to_ty`, since this will register a WF obligation.
884                 // If we're trying to call a non-existent method on a trait
885                 // (e.g. `MyTrait::missing_method`), then resolution will
886                 // give us a `QPath::TypeRelative` with a trait object as
887                 // `qself`. In that case, we want to avoid registering a WF obligation
888                 // for `dyn MyTrait`, since we don't actually need the trait
889                 // to be object-safe.
890                 // We manually call `register_wf_obligation` in the success path
891                 // below.
892                 (<dyn AstConv<'_>>::ast_ty_to_ty_in_path(self, qself), qself, segment)
893             }
894             QPath::LangItem(..) => {
895                 bug!("`resolve_ty_and_res_fully_qualified_call` called on `LangItem`")
896             }
897         };
898         if let Some(&cached_result) = self.typeck_results.borrow().type_dependent_defs().get(hir_id)
899         {
900             self.register_wf_obligation(ty.into(), qself.span, traits::WellFormed(None));
901             // Return directly on cache hit. This is useful to avoid doubly reporting
902             // errors with default match binding modes. See #44614.
903             let def = cached_result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id));
904             return (def, Some(ty), slice::from_ref(&**item_segment));
905         }
906         let item_name = item_segment.ident;
907         let result = self
908             .resolve_fully_qualified_call(span, item_name, ty, qself.span, hir_id)
909             .or_else(|error| {
910                 let result = match error {
911                     method::MethodError::PrivateMatch(kind, def_id, _) => Ok((kind, def_id)),
912                     _ => Err(ErrorReported),
913                 };
914
915                 // If we have a path like `MyTrait::missing_method`, then don't register
916                 // a WF obligation for `dyn MyTrait` when method lookup fails. Otherwise,
917                 // register a WF obligation so that we can detect any additional
918                 // errors in the self type.
919                 if !(matches!(error, method::MethodError::NoMatch(_)) && ty.is_trait()) {
920                     self.register_wf_obligation(ty.into(), qself.span, traits::WellFormed(None));
921                 }
922                 if item_name.name != kw::Empty {
923                     if let Some(mut e) = self.report_method_error(
924                         span,
925                         ty,
926                         item_name,
927                         SelfSource::QPath(qself),
928                         error,
929                         None,
930                     ) {
931                         e.emit();
932                     }
933                 }
934                 result
935             });
936
937         if result.is_ok() {
938             self.register_wf_obligation(ty.into(), qself.span, traits::WellFormed(None));
939         }
940
941         // Write back the new resolution.
942         self.write_resolution(hir_id, result);
943         (
944             result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
945             Some(ty),
946             slice::from_ref(&**item_segment),
947         )
948     }
949
950     /// Given a function `Node`, return its `FnDecl` if it exists, or `None` otherwise.
951     pub(in super::super) fn get_node_fn_decl(
952         &self,
953         node: Node<'tcx>,
954     ) -> Option<(&'tcx hir::FnDecl<'tcx>, Ident, bool)> {
955         match node {
956             Node::Item(&hir::Item { ident, kind: hir::ItemKind::Fn(ref sig, ..), .. }) => {
957                 // This is less than ideal, it will not suggest a return type span on any
958                 // method called `main`, regardless of whether it is actually the entry point,
959                 // but it will still present it as the reason for the expected type.
960                 Some((&sig.decl, ident, ident.name != sym::main))
961             }
962             Node::TraitItem(&hir::TraitItem {
963                 ident,
964                 kind: hir::TraitItemKind::Fn(ref sig, ..),
965                 ..
966             }) => Some((&sig.decl, ident, true)),
967             Node::ImplItem(&hir::ImplItem {
968                 ident,
969                 kind: hir::ImplItemKind::Fn(ref sig, ..),
970                 ..
971             }) => Some((&sig.decl, ident, false)),
972             _ => None,
973         }
974     }
975
976     /// Given a `HirId`, return the `FnDecl` of the method it is enclosed by and whether a
977     /// suggestion can be made, `None` otherwise.
978     pub fn get_fn_decl(&self, blk_id: hir::HirId) -> Option<(&'tcx hir::FnDecl<'tcx>, bool)> {
979         // Get enclosing Fn, if it is a function or a trait method, unless there's a `loop` or
980         // `while` before reaching it, as block tail returns are not available in them.
981         self.tcx.hir().get_return_block(blk_id).and_then(|blk_id| {
982             let parent = self.tcx.hir().get(blk_id);
983             self.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main))
984         })
985     }
986
987     pub(in super::super) fn note_internal_mutation_in_method(
988         &self,
989         err: &mut Diagnostic,
990         expr: &hir::Expr<'_>,
991         expected: Ty<'tcx>,
992         found: Ty<'tcx>,
993     ) {
994         if found != self.tcx.types.unit {
995             return;
996         }
997         if let ExprKind::MethodCall(path_segment, [rcvr, ..], _) = expr.kind {
998             if self
999                 .typeck_results
1000                 .borrow()
1001                 .expr_ty_adjusted_opt(rcvr)
1002                 .map_or(true, |ty| expected.peel_refs() != ty.peel_refs())
1003             {
1004                 return;
1005             }
1006             let mut sp = MultiSpan::from_span(path_segment.ident.span);
1007             sp.push_span_label(
1008                 path_segment.ident.span,
1009                 format!(
1010                     "this call modifies {} in-place",
1011                     match rcvr.kind {
1012                         ExprKind::Path(QPath::Resolved(
1013                             None,
1014                             hir::Path { segments: [segment], .. },
1015                         )) => format!("`{}`", segment.ident),
1016                         _ => "its receiver".to_string(),
1017                     }
1018                 ),
1019             );
1020             sp.push_span_label(
1021                 rcvr.span,
1022                 "you probably want to use this value after calling the method...".to_string(),
1023             );
1024             err.span_note(
1025                 sp,
1026                 &format!("method `{}` modifies its receiver in-place", path_segment.ident),
1027             );
1028             err.note(&format!("...instead of the `()` output of method `{}`", path_segment.ident));
1029         }
1030     }
1031
1032     pub(in super::super) fn note_need_for_fn_pointer(
1033         &self,
1034         err: &mut Diagnostic,
1035         expected: Ty<'tcx>,
1036         found: Ty<'tcx>,
1037     ) {
1038         let (sig, did, substs) = match (&expected.kind(), &found.kind()) {
1039             (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => {
1040                 let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1);
1041                 let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2);
1042                 if sig1 != sig2 {
1043                     return;
1044                 }
1045                 err.note(
1046                     "different `fn` items always have unique types, even if their signatures are \
1047                      the same",
1048                 );
1049                 (sig1, *did1, substs1)
1050             }
1051             (ty::FnDef(did, substs), ty::FnPtr(sig2)) => {
1052                 let sig1 = self.tcx.fn_sig(*did).subst(self.tcx, substs);
1053                 if sig1 != *sig2 {
1054                     return;
1055                 }
1056                 (sig1, *did, substs)
1057             }
1058             _ => return,
1059         };
1060         err.help(&format!("change the expected type to be function pointer `{}`", sig));
1061         err.help(&format!(
1062             "if the expected type is due to type inference, cast the expected `fn` to a function \
1063              pointer: `{} as {}`",
1064             self.tcx.def_path_str_with_substs(did, substs),
1065             sig
1066         ));
1067     }
1068
1069     pub(in super::super) fn could_remove_semicolon(
1070         &self,
1071         blk: &'tcx hir::Block<'tcx>,
1072         expected_ty: Ty<'tcx>,
1073     ) -> Option<(Span, StatementAsExpression)> {
1074         // Be helpful when the user wrote `{... expr;}` and
1075         // taking the `;` off is enough to fix the error.
1076         let last_stmt = blk.stmts.last()?;
1077         let hir::StmtKind::Semi(ref last_expr) = last_stmt.kind else {
1078             return None;
1079         };
1080         let last_expr_ty = self.node_ty(last_expr.hir_id);
1081         let needs_box = match (last_expr_ty.kind(), expected_ty.kind()) {
1082             (ty::Opaque(last_def_id, _), ty::Opaque(exp_def_id, _))
1083                 if last_def_id == exp_def_id =>
1084             {
1085                 StatementAsExpression::CorrectType
1086             }
1087             (ty::Opaque(last_def_id, last_bounds), ty::Opaque(exp_def_id, exp_bounds)) => {
1088                 debug!(
1089                     "both opaque, likely future {:?} {:?} {:?} {:?}",
1090                     last_def_id, last_bounds, exp_def_id, exp_bounds
1091                 );
1092
1093                 let last_local_id = last_def_id.as_local()?;
1094                 let exp_local_id = exp_def_id.as_local()?;
1095
1096                 match (
1097                     &self.tcx.hir().expect_item(last_local_id).kind,
1098                     &self.tcx.hir().expect_item(exp_local_id).kind,
1099                 ) {
1100                     (
1101                         hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds: last_bounds, .. }),
1102                         hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds: exp_bounds, .. }),
1103                     ) if iter::zip(*last_bounds, *exp_bounds).all(|(left, right)| {
1104                         match (left, right) {
1105                             (
1106                                 hir::GenericBound::Trait(tl, ml),
1107                                 hir::GenericBound::Trait(tr, mr),
1108                             ) if tl.trait_ref.trait_def_id() == tr.trait_ref.trait_def_id()
1109                                 && ml == mr =>
1110                             {
1111                                 true
1112                             }
1113                             (
1114                                 hir::GenericBound::LangItemTrait(langl, _, _, argsl),
1115                                 hir::GenericBound::LangItemTrait(langr, _, _, argsr),
1116                             ) if langl == langr => {
1117                                 // FIXME: consider the bounds!
1118                                 debug!("{:?} {:?}", argsl, argsr);
1119                                 true
1120                             }
1121                             _ => false,
1122                         }
1123                     }) =>
1124                     {
1125                         StatementAsExpression::NeedsBoxing
1126                     }
1127                     _ => StatementAsExpression::CorrectType,
1128                 }
1129             }
1130             _ => StatementAsExpression::CorrectType,
1131         };
1132         if (matches!(last_expr_ty.kind(), ty::Error(_))
1133             || self.can_sub(self.param_env, last_expr_ty, expected_ty).is_err())
1134             && matches!(needs_box, StatementAsExpression::CorrectType)
1135         {
1136             return None;
1137         }
1138         let span = if last_stmt.span.from_expansion() {
1139             let mac_call = original_sp(last_stmt.span, blk.span);
1140             self.tcx.sess.source_map().mac_call_stmt_semi_span(mac_call)?
1141         } else {
1142             last_stmt.span.with_lo(last_stmt.span.hi() - BytePos(1))
1143         };
1144         Some((span, needs_box))
1145     }
1146
1147     // Instantiates the given path, which must refer to an item with the given
1148     // number of type parameters and type.
1149     #[instrument(skip(self, span), level = "debug")]
1150     pub fn instantiate_value_path(
1151         &self,
1152         segments: &[hir::PathSegment<'_>],
1153         self_ty: Option<Ty<'tcx>>,
1154         res: Res,
1155         span: Span,
1156         hir_id: hir::HirId,
1157     ) -> (Ty<'tcx>, Res) {
1158         let tcx = self.tcx;
1159
1160         let path_segs = match res {
1161             Res::Local(_) | Res::SelfCtor(_) => vec![],
1162             Res::Def(kind, def_id) => <dyn AstConv<'_>>::def_ids_for_value_path_segments(
1163                 self, segments, self_ty, kind, def_id,
1164             ),
1165             _ => bug!("instantiate_value_path on {:?}", res),
1166         };
1167
1168         let mut user_self_ty = None;
1169         let mut is_alias_variant_ctor = false;
1170         match res {
1171             Res::Def(DefKind::Ctor(CtorOf::Variant, _), _)
1172                 if let Some(self_ty) = self_ty =>
1173             {
1174                 let adt_def = self_ty.ty_adt_def().unwrap();
1175                 user_self_ty = Some(UserSelfTy { impl_def_id: adt_def.did, self_ty });
1176                 is_alias_variant_ctor = true;
1177             }
1178             Res::Def(DefKind::AssocFn | DefKind::AssocConst, def_id) => {
1179                 let container = tcx.associated_item(def_id).container;
1180                 debug!(?def_id, ?container);
1181                 match container {
1182                     ty::TraitContainer(trait_did) => {
1183                         callee::check_legal_trait_for_method_call(tcx, span, None, span, trait_did)
1184                     }
1185                     ty::ImplContainer(impl_def_id) => {
1186                         if segments.len() == 1 {
1187                             // `<T>::assoc` will end up here, and so
1188                             // can `T::assoc`. It this came from an
1189                             // inherent impl, we need to record the
1190                             // `T` for posterity (see `UserSelfTy` for
1191                             // details).
1192                             let self_ty = self_ty.expect("UFCS sugared assoc missing Self");
1193                             user_self_ty = Some(UserSelfTy { impl_def_id, self_ty });
1194                         }
1195                     }
1196                 }
1197             }
1198             _ => {}
1199         }
1200
1201         // Now that we have categorized what space the parameters for each
1202         // segment belong to, let's sort out the parameters that the user
1203         // provided (if any) into their appropriate spaces. We'll also report
1204         // errors if type parameters are provided in an inappropriate place.
1205
1206         let generic_segs: FxHashSet<_> = path_segs.iter().map(|PathSeg(_, index)| index).collect();
1207         let generics_has_err = <dyn AstConv<'_>>::prohibit_generics(
1208             self,
1209             segments.iter().enumerate().filter_map(|(index, seg)| {
1210                 if !generic_segs.contains(&index) || is_alias_variant_ctor {
1211                     Some(seg)
1212                 } else {
1213                     None
1214                 }
1215             }),
1216         );
1217
1218         if let Res::Local(hid) = res {
1219             let ty = self.local_ty(span, hid).decl_ty;
1220             let ty = self.normalize_associated_types_in(span, ty);
1221             self.write_ty(hir_id, ty);
1222             return (ty, res);
1223         }
1224
1225         if generics_has_err {
1226             // Don't try to infer type parameters when prohibited generic arguments were given.
1227             user_self_ty = None;
1228         }
1229
1230         // Now we have to compare the types that the user *actually*
1231         // provided against the types that were *expected*. If the user
1232         // did not provide any types, then we want to substitute inference
1233         // variables. If the user provided some types, we may still need
1234         // to add defaults. If the user provided *too many* types, that's
1235         // a problem.
1236
1237         let mut infer_args_for_err = FxHashSet::default();
1238
1239         let mut explicit_late_bound = ExplicitLateBound::No;
1240         for &PathSeg(def_id, index) in &path_segs {
1241             let seg = &segments[index];
1242             let generics = tcx.generics_of(def_id);
1243
1244             // Argument-position `impl Trait` is treated as a normal generic
1245             // parameter internally, but we don't allow users to specify the
1246             // parameter's value explicitly, so we have to do some error-
1247             // checking here.
1248             let arg_count = <dyn AstConv<'_>>::check_generic_arg_count_for_call(
1249                 tcx,
1250                 span,
1251                 def_id,
1252                 &generics,
1253                 seg,
1254                 IsMethodCall::No,
1255             );
1256
1257             if let ExplicitLateBound::Yes = arg_count.explicit_late_bound {
1258                 explicit_late_bound = ExplicitLateBound::Yes;
1259             }
1260
1261             if let Err(GenericArgCountMismatch { reported: Some(_), .. }) = arg_count.correct {
1262                 infer_args_for_err.insert(index);
1263                 self.set_tainted_by_errors(); // See issue #53251.
1264             }
1265         }
1266
1267         let has_self = path_segs
1268             .last()
1269             .map(|PathSeg(def_id, _)| tcx.generics_of(*def_id).has_self)
1270             .unwrap_or(false);
1271
1272         let (res, self_ctor_substs) = if let Res::SelfCtor(impl_def_id) = res {
1273             let ty = self.normalize_ty(span, tcx.at(span).type_of(impl_def_id));
1274             match *ty.kind() {
1275                 ty::Adt(adt_def, substs) if adt_def.has_ctor() => {
1276                     let variant = adt_def.non_enum_variant();
1277                     let ctor_def_id = variant.ctor_def_id.unwrap();
1278                     (
1279                         Res::Def(DefKind::Ctor(CtorOf::Struct, variant.ctor_kind), ctor_def_id),
1280                         Some(substs),
1281                     )
1282                 }
1283                 _ => {
1284                     let mut err = tcx.sess.struct_span_err(
1285                         span,
1286                         "the `Self` constructor can only be used with tuple or unit structs",
1287                     );
1288                     if let Some(adt_def) = ty.ty_adt_def() {
1289                         match adt_def.adt_kind() {
1290                             AdtKind::Enum => {
1291                                 err.help("did you mean to use one of the enum's variants?");
1292                             }
1293                             AdtKind::Struct | AdtKind::Union => {
1294                                 err.span_suggestion(
1295                                     span,
1296                                     "use curly brackets",
1297                                     String::from("Self { /* fields */ }"),
1298                                     Applicability::HasPlaceholders,
1299                                 );
1300                             }
1301                         }
1302                     }
1303                     err.emit();
1304
1305                     return (tcx.ty_error(), res);
1306                 }
1307             }
1308         } else {
1309             (res, None)
1310         };
1311         let def_id = res.def_id();
1312
1313         // The things we are substituting into the type should not contain
1314         // escaping late-bound regions, and nor should the base type scheme.
1315         let ty = tcx.type_of(def_id);
1316
1317         let arg_count = GenericArgCountResult {
1318             explicit_late_bound,
1319             correct: if infer_args_for_err.is_empty() {
1320                 Ok(())
1321             } else {
1322                 Err(GenericArgCountMismatch::default())
1323             },
1324         };
1325
1326         struct CreateCtorSubstsContext<'a, 'tcx> {
1327             fcx: &'a FnCtxt<'a, 'tcx>,
1328             span: Span,
1329             path_segs: &'a [PathSeg],
1330             infer_args_for_err: &'a FxHashSet<usize>,
1331             segments: &'a [hir::PathSegment<'a>],
1332         }
1333         impl<'tcx, 'a> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for CreateCtorSubstsContext<'a, 'tcx> {
1334             fn args_for_def_id(
1335                 &mut self,
1336                 def_id: DefId,
1337             ) -> (Option<&'a hir::GenericArgs<'a>>, bool) {
1338                 if let Some(&PathSeg(_, index)) =
1339                     self.path_segs.iter().find(|&PathSeg(did, _)| *did == def_id)
1340                 {
1341                     // If we've encountered an `impl Trait`-related error, we're just
1342                     // going to infer the arguments for better error messages.
1343                     if !self.infer_args_for_err.contains(&index) {
1344                         // Check whether the user has provided generic arguments.
1345                         if let Some(ref data) = self.segments[index].args {
1346                             return (Some(data), self.segments[index].infer_args);
1347                         }
1348                     }
1349                     return (None, self.segments[index].infer_args);
1350                 }
1351
1352                 (None, true)
1353             }
1354
1355             fn provided_kind(
1356                 &mut self,
1357                 param: &ty::GenericParamDef,
1358                 arg: &GenericArg<'_>,
1359             ) -> subst::GenericArg<'tcx> {
1360                 match (&param.kind, arg) {
1361                     (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
1362                         <dyn AstConv<'_>>::ast_region_to_region(self.fcx, lt, Some(param)).into()
1363                     }
1364                     (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
1365                         self.fcx.to_ty(ty).into()
1366                     }
1367                     (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => {
1368                         self.fcx.const_arg_to_const(&ct.value, param.def_id).into()
1369                     }
1370                     (GenericParamDefKind::Type { .. }, GenericArg::Infer(inf)) => {
1371                         self.fcx.ty_infer(Some(param), inf.span).into()
1372                     }
1373                     (GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
1374                         let tcx = self.fcx.tcx();
1375                         self.fcx.ct_infer(tcx.type_of(param.def_id), Some(param), inf.span).into()
1376                     }
1377                     _ => unreachable!(),
1378                 }
1379             }
1380
1381             fn inferred_kind(
1382                 &mut self,
1383                 substs: Option<&[subst::GenericArg<'tcx>]>,
1384                 param: &ty::GenericParamDef,
1385                 infer_args: bool,
1386             ) -> subst::GenericArg<'tcx> {
1387                 let tcx = self.fcx.tcx();
1388                 match param.kind {
1389                     GenericParamDefKind::Lifetime => {
1390                         self.fcx.re_infer(Some(param), self.span).unwrap().into()
1391                     }
1392                     GenericParamDefKind::Type { has_default, .. } => {
1393                         if !infer_args && has_default {
1394                             // If we have a default, then we it doesn't matter that we're not
1395                             // inferring the type arguments: we provide the default where any
1396                             // is missing.
1397                             let default = tcx.type_of(param.def_id);
1398                             self.fcx
1399                                 .normalize_ty(
1400                                     self.span,
1401                                     default.subst_spanned(tcx, substs.unwrap(), Some(self.span)),
1402                                 )
1403                                 .into()
1404                         } else {
1405                             // If no type arguments were provided, we have to infer them.
1406                             // This case also occurs as a result of some malformed input, e.g.
1407                             // a lifetime argument being given instead of a type parameter.
1408                             // Using inference instead of `Error` gives better error messages.
1409                             self.fcx.var_for_def(self.span, param)
1410                         }
1411                     }
1412                     GenericParamDefKind::Const { has_default, .. } => {
1413                         if !infer_args && has_default {
1414                             tcx.const_param_default(param.def_id)
1415                                 .subst_spanned(tcx, substs.unwrap(), Some(self.span))
1416                                 .into()
1417                         } else {
1418                             self.fcx.var_for_def(self.span, param)
1419                         }
1420                     }
1421                 }
1422             }
1423         }
1424
1425         let substs = self_ctor_substs.unwrap_or_else(|| {
1426             <dyn AstConv<'_>>::create_substs_for_generic_args(
1427                 tcx,
1428                 def_id,
1429                 &[],
1430                 has_self,
1431                 self_ty,
1432                 &arg_count,
1433                 &mut CreateCtorSubstsContext {
1434                     fcx: self,
1435                     span,
1436                     path_segs: &path_segs,
1437                     infer_args_for_err: &infer_args_for_err,
1438                     segments,
1439                 },
1440             )
1441         });
1442         assert!(!substs.has_escaping_bound_vars());
1443         assert!(!ty.has_escaping_bound_vars());
1444
1445         // First, store the "user substs" for later.
1446         self.write_user_type_annotation_from_substs(hir_id, def_id, substs, user_self_ty);
1447
1448         self.add_required_obligations(span, def_id, &substs);
1449
1450         // Substitute the values for the type parameters into the type of
1451         // the referenced item.
1452         let ty_substituted = self.instantiate_type_scheme(span, &substs, ty);
1453
1454         if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty {
1455             // In the case of `Foo<T>::method` and `<Foo<T>>::method`, if `method`
1456             // is inherent, there is no `Self` parameter; instead, the impl needs
1457             // type parameters, which we can infer by unifying the provided `Self`
1458             // with the substituted impl type.
1459             // This also occurs for an enum variant on a type alias.
1460             let ty = tcx.type_of(impl_def_id);
1461
1462             let impl_ty = self.instantiate_type_scheme(span, &substs, ty);
1463             match self.at(&self.misc(span), self.param_env).eq(impl_ty, self_ty) {
1464                 Ok(ok) => self.register_infer_ok_obligations(ok),
1465                 Err(_) => {
1466                     self.tcx.sess.delay_span_bug(
1467                         span,
1468                         &format!(
1469                         "instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?",
1470                         self_ty,
1471                         impl_ty,
1472                     ),
1473                     );
1474                 }
1475             }
1476         }
1477
1478         debug!("instantiate_value_path: type of {:?} is {:?}", hir_id, ty_substituted);
1479         self.write_substs(hir_id, substs);
1480
1481         (ty_substituted, res)
1482     }
1483
1484     /// Add all the obligations that are required, substituting and normalized appropriately.
1485     crate fn add_required_obligations(&self, span: Span, def_id: DefId, substs: &SubstsRef<'tcx>) {
1486         self.add_required_obligations_with_code(
1487             span,
1488             def_id,
1489             substs,
1490             traits::ItemObligation(def_id),
1491         )
1492     }
1493
1494     #[tracing::instrument(level = "debug", skip(self, span, def_id, substs))]
1495     fn add_required_obligations_with_code(
1496         &self,
1497         span: Span,
1498         def_id: DefId,
1499         substs: &SubstsRef<'tcx>,
1500         code: ObligationCauseCode<'tcx>,
1501     ) {
1502         let (bounds, _) = self.instantiate_bounds(span, def_id, &substs);
1503
1504         for obligation in traits::predicates_for_generics(
1505             traits::ObligationCause::new(span, self.body_id, code),
1506             self.param_env,
1507             bounds,
1508         ) {
1509             self.register_predicate(obligation);
1510         }
1511     }
1512
1513     /// Resolves `typ` by a single level if `typ` is a type variable.
1514     /// If no resolution is possible, then an error is reported.
1515     /// Numeric inference variables may be left unresolved.
1516     pub fn structurally_resolved_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
1517         let ty = self.resolve_vars_with_obligations(ty);
1518         if !ty.is_ty_var() {
1519             ty
1520         } else {
1521             if !self.is_tainted_by_errors() {
1522                 self.emit_inference_failure_err((**self).body_id, sp, ty.into(), vec![], E0282)
1523                     .note("type must be known at this point")
1524                     .emit();
1525             }
1526             let err = self.tcx.ty_error();
1527             self.demand_suptype(sp, err, ty);
1528             err
1529         }
1530     }
1531
1532     pub(in super::super) fn with_breakable_ctxt<F: FnOnce() -> R, R>(
1533         &self,
1534         id: hir::HirId,
1535         ctxt: BreakableCtxt<'tcx>,
1536         f: F,
1537     ) -> (BreakableCtxt<'tcx>, R) {
1538         let index;
1539         {
1540             let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
1541             index = enclosing_breakables.stack.len();
1542             enclosing_breakables.by_id.insert(id, index);
1543             enclosing_breakables.stack.push(ctxt);
1544         }
1545         let result = f();
1546         let ctxt = {
1547             let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
1548             debug_assert!(enclosing_breakables.stack.len() == index + 1);
1549             enclosing_breakables.by_id.remove(&id).expect("missing breakable context");
1550             enclosing_breakables.stack.pop().expect("missing breakable context")
1551         };
1552         (ctxt, result)
1553     }
1554
1555     /// Instantiate a QueryResponse in a probe context, without a
1556     /// good ObligationCause.
1557     pub(in super::super) fn probe_instantiate_query_response(
1558         &self,
1559         span: Span,
1560         original_values: &OriginalQueryValues<'tcx>,
1561         query_result: &Canonical<'tcx, QueryResponse<'tcx, Ty<'tcx>>>,
1562     ) -> InferResult<'tcx, Ty<'tcx>> {
1563         self.instantiate_query_response_and_region_obligations(
1564             &traits::ObligationCause::misc(span, self.body_id),
1565             self.param_env,
1566             original_values,
1567             query_result,
1568         )
1569     }
1570
1571     /// Returns `true` if an expression is contained inside the LHS of an assignment expression.
1572     pub(in super::super) fn expr_in_place(&self, mut expr_id: hir::HirId) -> bool {
1573         let mut contained_in_place = false;
1574
1575         while let hir::Node::Expr(parent_expr) =
1576             self.tcx.hir().get(self.tcx.hir().get_parent_node(expr_id))
1577         {
1578             match &parent_expr.kind {
1579                 hir::ExprKind::Assign(lhs, ..) | hir::ExprKind::AssignOp(_, lhs, ..) => {
1580                     if lhs.hir_id == expr_id {
1581                         contained_in_place = true;
1582                         break;
1583                     }
1584                 }
1585                 _ => (),
1586             }
1587             expr_id = parent_expr.hir_id;
1588         }
1589
1590         contained_in_place
1591     }
1592 }