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