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