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