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