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