2 AstConv, CreateSubstsForGenericArgsCtxt, ExplicitLateBound, GenericArgCountMismatch,
3 GenericArgCountResult, IsMethodCall, PathSeg,
5 use crate::check::callee::{self, DeferredCallResolution};
6 use crate::check::method::{self, MethodCallee, SelfSource};
7 use crate::check::{BreakableCtxt, Diverges, Expectation, FnCtxt, LocalTy};
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};
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,
26 use rustc_middle::ty::{
27 self, AdtKind, CanonicalUserType, DefIdTree, GenericParamDefKind, ToPolyTraitRef, ToPredicate,
30 use rustc_session::lint;
31 use rustc_session::lint::builtin::BARE_TRAIT_OBJECTS;
32 use rustc_span::edition::Edition;
33 use rustc_span::hygiene::DesugaringKind;
34 use rustc_span::source_map::{original_sp, DUMMY_SP};
35 use rustc_span::symbol::{kw, sym, Ident};
36 use rustc_span::{self, BytePos, MultiSpan, Span};
37 use rustc_trait_selection::infer::InferCtxtExt as _;
38 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
39 use rustc_trait_selection::traits::{
40 self, ObligationCause, ObligationCauseCode, StatementAsExpression, TraitEngine, TraitEngineExt,
44 use std::collections::hash_map::Entry;
48 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
49 /// Produces warning on the given node, if the current point in the
50 /// function is unreachable, and there hasn't been another warning.
51 pub(in super::super) fn warn_if_unreachable(&self, id: hir::HirId, span: Span, kind: &str) {
52 // FIXME: Combine these two 'if' expressions into one once
53 // let chains are implemented
54 if let Diverges::Always { span: orig_span, custom_note } = self.diverges.get() {
55 // If span arose from a desugaring of `if` or `while`, then it is the condition itself,
56 // which diverges, that we are about to lint on. This gives suboptimal diagnostics.
57 // Instead, stop here so that the `if`- or `while`-expression's block is linted instead.
58 if !span.is_desugaring(DesugaringKind::CondTemporary)
59 && !span.is_desugaring(DesugaringKind::Async)
60 && !orig_span.is_desugaring(DesugaringKind::Await)
62 self.diverges.set(Diverges::WarnedAlways);
64 debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind);
66 self.tcx().struct_span_lint_hir(lint::builtin::UNREACHABLE_CODE, id, span, |lint| {
67 let msg = format!("unreachable {}", kind);
69 .span_label(span, &msg)
73 .unwrap_or("any code following this expression is unreachable"),
81 /// Resolves type and const variables in `ty` if possible. Unlike the infcx
82 /// version (resolve_vars_if_possible), this version will
83 /// also select obligations if it seems useful, in an effort
84 /// to get more type information.
85 pub(in super::super) fn resolve_vars_with_obligations(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
86 self.resolve_vars_with_obligations_and_mutate_fulfillment(ty, |_| {})
89 #[instrument(skip(self, mutate_fulfillment_errors), level = "debug")]
90 pub(in super::super) fn resolve_vars_with_obligations_and_mutate_fulfillment(
93 mutate_fulfillment_errors: impl Fn(&mut Vec<traits::FulfillmentError<'tcx>>),
95 // No Infer()? Nothing needs doing.
96 if !ty.has_infer_types_or_consts() {
97 debug!("no inference var, nothing needs doing");
101 // If `ty` is a type variable, see whether we already know what it is.
102 ty = self.resolve_vars_if_possible(ty);
103 if !ty.has_infer_types_or_consts() {
108 // If not, try resolving pending obligations as much as
109 // possible. This can help substantially when there are
110 // indirect dependencies that don't seem worth tracking
112 self.select_obligations_where_possible(false, mutate_fulfillment_errors);
113 ty = self.resolve_vars_if_possible(ty);
119 pub(in super::super) fn record_deferred_call_resolution(
121 closure_def_id: DefId,
122 r: DeferredCallResolution<'tcx>,
124 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
125 deferred_call_resolutions.entry(closure_def_id).or_default().push(r);
128 pub(in super::super) fn remove_deferred_call_resolutions(
130 closure_def_id: DefId,
131 ) -> Vec<DeferredCallResolution<'tcx>> {
132 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
133 deferred_call_resolutions.remove(&closure_def_id).unwrap_or_default()
136 pub fn tag(&self) -> String {
137 format!("{:p}", self)
140 pub fn local_ty(&self, span: Span, nid: hir::HirId) -> LocalTy<'tcx> {
141 self.locals.borrow().get(&nid).cloned().unwrap_or_else(|| {
142 span_bug!(span, "no type for local variable {}", self.tcx.hir().node_to_string(nid))
147 pub fn write_ty(&self, id: hir::HirId, ty: Ty<'tcx>) {
148 debug!("write_ty({:?}, {:?}) in fcx {}", id, self.resolve_vars_if_possible(ty), self.tag());
149 self.typeck_results.borrow_mut().node_types_mut().insert(id, ty);
151 if ty.references_error() {
152 self.has_errors.set(true);
153 self.set_tainted_by_errors();
157 pub fn write_field_index(&self, hir_id: hir::HirId, index: usize) {
158 self.typeck_results.borrow_mut().field_indices_mut().insert(hir_id, index);
161 pub(in super::super) fn write_resolution(
164 r: Result<(DefKind, DefId), ErrorReported>,
166 self.typeck_results.borrow_mut().type_dependent_defs_mut().insert(hir_id, r);
169 pub fn write_method_call(&self, hir_id: hir::HirId, method: MethodCallee<'tcx>) {
170 debug!("write_method_call(hir_id={:?}, method={:?})", hir_id, method);
171 self.write_resolution(hir_id, Ok((DefKind::AssocFn, method.def_id)));
172 self.write_substs(hir_id, method.substs);
174 // When the method is confirmed, the `method.substs` includes
175 // parameters from not just the method, but also the impl of
176 // the method -- in particular, the `Self` type will be fully
177 // resolved. However, those are not something that the "user
178 // specified" -- i.e., those types come from the inferred type
179 // of the receiver, not something the user wrote. So when we
180 // create the user-substs, we want to replace those earlier
181 // types with just the types that the user actually wrote --
182 // that is, those that appear on the *method itself*.
184 // As an example, if the user wrote something like
185 // `foo.bar::<u32>(...)` -- the `Self` type here will be the
186 // type of `foo` (possibly adjusted), but we don't want to
187 // include that. We want just the `[_, u32]` part.
188 if !method.substs.is_noop() {
189 let method_generics = self.tcx.generics_of(method.def_id);
190 if !method_generics.params.is_empty() {
191 let user_type_annotation = self.infcx.probe(|_| {
192 let user_substs = UserSubsts {
193 substs: InternalSubsts::for_item(self.tcx, method.def_id, |param, _| {
194 let i = param.index as usize;
195 if i < method_generics.parent_count {
196 self.infcx.var_for_def(DUMMY_SP, param)
201 user_self_ty: None, // not relevant here
204 self.infcx.canonicalize_user_type_annotation(UserType::TypeOf(
210 debug!("write_method_call: user_type_annotation={:?}", user_type_annotation);
211 self.write_user_type_annotation(hir_id, user_type_annotation);
216 pub fn write_substs(&self, node_id: hir::HirId, substs: SubstsRef<'tcx>) {
217 if !substs.is_noop() {
218 debug!("write_substs({:?}, {:?}) in fcx {}", node_id, substs, self.tag());
220 self.typeck_results.borrow_mut().node_substs_mut().insert(node_id, substs);
224 /// Given the substs that we just converted from the HIR, try to
225 /// canonicalize them and store them as user-given substitutions
226 /// (i.e., substitutions that must be respected by the NLL check).
228 /// This should be invoked **before any unifications have
229 /// occurred**, so that annotations like `Vec<_>` are preserved
231 #[instrument(skip(self), level = "debug")]
232 pub fn write_user_type_annotation_from_substs(
236 substs: SubstsRef<'tcx>,
237 user_self_ty: Option<UserSelfTy<'tcx>>,
239 debug!("fcx {}", self.tag());
241 if self.can_contain_user_lifetime_bounds((substs, user_self_ty)) {
242 let canonicalized = self.infcx.canonicalize_user_type_annotation(UserType::TypeOf(
244 UserSubsts { substs, user_self_ty },
246 debug!(?canonicalized);
247 self.write_user_type_annotation(hir_id, canonicalized);
251 #[instrument(skip(self), level = "debug")]
252 pub fn write_user_type_annotation(
255 canonical_user_type_annotation: CanonicalUserType<'tcx>,
257 debug!("fcx {}", self.tag());
259 if !canonical_user_type_annotation.is_identity() {
262 .user_provided_types_mut()
263 .insert(hir_id, canonical_user_type_annotation);
265 debug!("skipping identity substs");
269 #[instrument(skip(self, expr), level = "debug")]
270 pub fn apply_adjustments(&self, expr: &hir::Expr<'_>, adj: Vec<Adjustment<'tcx>>) {
271 debug!("expr = {:#?}", expr);
278 if let Adjust::NeverToAny = a.kind {
279 if a.target.is_ty_var() {
280 self.diverging_type_vars.borrow_mut().insert(a.target);
281 debug!("apply_adjustments: adding `{:?}` as diverging type var", a.target);
286 let autoborrow_mut = adj.iter().any(|adj| {
290 kind: Adjust::Borrow(AutoBorrow::Ref(_, AutoBorrowMutability::Mut { .. })),
296 match self.typeck_results.borrow_mut().adjustments_mut().entry(expr.hir_id) {
297 Entry::Vacant(entry) => {
300 Entry::Occupied(mut entry) => {
301 debug!(" - composing on top of {:?}", entry.get());
302 match (&entry.get()[..], &adj[..]) {
303 // Applying any adjustment on top of a NeverToAny
304 // is a valid NeverToAny adjustment, because it can't
306 (&[Adjustment { kind: Adjust::NeverToAny, .. }], _) => return,
308 Adjustment { kind: Adjust::Deref(_), .. },
309 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), .. },
311 Adjustment { kind: Adjust::Deref(_), .. },
312 .. // Any following adjustments are allowed.
314 // A reborrow has no effect before a dereference.
316 // FIXME: currently we never try to compose autoderefs
317 // and ReifyFnPointer/UnsafeFnPointer, but we could.
319 bug!("while adjusting {:?}, can't compose {:?} and {:?}",
320 expr, entry.get(), adj)
322 *entry.get_mut() = adj;
326 // If there is an mutable auto-borrow, it is equivalent to `&mut <expr>`.
327 // In this case implicit use of `Deref` and `Index` within `<expr>` should
328 // instead be `DerefMut` and `IndexMut`, so fix those up.
330 self.convert_place_derefs_to_mutable(expr);
334 /// Basically whenever we are converting from a type scheme into
335 /// the fn body space, we always want to normalize associated
336 /// types as well. This function combines the two.
337 fn instantiate_type_scheme<T>(&self, span: Span, substs: SubstsRef<'tcx>, value: T) -> T
339 T: TypeFoldable<'tcx>,
341 debug!("instantiate_type_scheme(value={:?}, substs={:?})", value, substs);
342 let value = value.subst(self.tcx, substs);
343 let result = self.normalize_associated_types_in(span, value);
344 debug!("instantiate_type_scheme = {:?}", result);
348 /// As `instantiate_type_scheme`, but for the bounds found in a
349 /// generic type scheme.
350 pub(in super::super) fn instantiate_bounds(
354 substs: SubstsRef<'tcx>,
355 ) -> (ty::InstantiatedPredicates<'tcx>, Vec<Span>) {
356 let bounds = self.tcx.predicates_of(def_id);
357 let spans: Vec<Span> = bounds.predicates.iter().map(|(_, span)| *span).collect();
358 let result = bounds.instantiate(self.tcx, substs);
359 let result = self.normalize_associated_types_in(span, result);
361 "instantiate_bounds(bounds={:?}, substs={:?}) = {:?}, {:?}",
362 bounds, substs, result, spans,
367 /// Replaces the opaque types from the given value with type variables,
368 /// and records the `OpaqueTypeMap` for later use during writeback. See
369 /// `InferCtxt::instantiate_opaque_types` for more details.
370 #[instrument(skip(self, value_span), level = "debug")]
371 pub(in super::super) fn instantiate_opaque_types_from_value<T: TypeFoldable<'tcx>>(
376 self.register_infer_ok_obligations(self.instantiate_opaque_types(
384 /// Convenience method which tracks extra diagnostic information for normalization
385 /// that occurs as a result of WF checking. The `hir_id` is the `HirId` of the hir item
386 /// whose type is being wf-checked - this is used to construct a more precise span if
389 /// It is never necessary to call this method - calling `normalize_associated_types_in` will
390 /// just result in a slightly worse diagnostic span, and will still be sound.
391 pub(in super::super) fn normalize_associated_types_in_wf<T>(
398 T: TypeFoldable<'tcx>,
400 self.inh.normalize_associated_types_in_with_cause(
401 ObligationCause::new(span, self.body_id, ObligationCauseCode::WellFormed(Some(loc))),
407 pub(in super::super) fn normalize_associated_types_in<T>(&self, span: Span, value: T) -> T
409 T: TypeFoldable<'tcx>,
411 self.inh.normalize_associated_types_in(span, self.body_id, self.param_env, value)
414 pub(in super::super) fn normalize_associated_types_in_as_infer_ok<T>(
418 ) -> InferOk<'tcx, T>
420 T: TypeFoldable<'tcx>,
422 self.inh.partially_normalize_associated_types_in(
423 ObligationCause::misc(span, self.body_id),
429 pub fn require_type_meets(
433 code: traits::ObligationCauseCode<'tcx>,
436 self.register_bound(ty, def_id, traits::ObligationCause::new(span, self.body_id, code));
439 pub fn require_type_is_sized(
443 code: traits::ObligationCauseCode<'tcx>,
445 if !ty.references_error() {
446 let lang_item = self.tcx.require_lang_item(LangItem::Sized, None);
447 self.require_type_meets(ty, span, code, lang_item);
451 pub fn require_type_is_sized_deferred(
455 code: traits::ObligationCauseCode<'tcx>,
457 if !ty.references_error() {
458 self.deferred_sized_obligations.borrow_mut().push((ty, span, code));
462 pub fn register_bound(
466 cause: traits::ObligationCause<'tcx>,
468 if !ty.references_error() {
469 self.fulfillment_cx.borrow_mut().register_bound(
479 pub fn to_ty(&self, ast_t: &hir::Ty<'_>) -> Ty<'tcx> {
480 let t = <dyn AstConv<'_>>::ast_ty_to_ty(self, ast_t);
481 self.register_wf_obligation(t.into(), ast_t.span, traits::MiscObligation);
485 pub fn to_ty_saving_user_provided_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
486 let ty = self.to_ty(ast_ty);
487 debug!("to_ty_saving_user_provided_ty: ty={:?}", ty);
489 if self.can_contain_user_lifetime_bounds(ty) {
490 let c_ty = self.infcx.canonicalize_response(UserType::Ty(ty));
491 debug!("to_ty_saving_user_provided_ty: c_ty={:?}", c_ty);
492 self.typeck_results.borrow_mut().user_provided_types_mut().insert(ast_ty.hir_id, c_ty);
498 pub fn to_const(&self, ast_c: &hir::AnonConst) -> &'tcx ty::Const<'tcx> {
499 let const_def_id = self.tcx.hir().local_def_id(ast_c.hir_id);
500 let c = ty::Const::from_anon_const(self.tcx, const_def_id);
501 self.register_wf_obligation(
503 self.tcx.hir().span(ast_c.hir_id),
504 ObligationCauseCode::MiscObligation,
509 pub fn const_arg_to_const(
511 ast_c: &hir::AnonConst,
513 ) -> &'tcx ty::Const<'tcx> {
514 let const_def = ty::WithOptConstParam {
515 did: self.tcx.hir().local_def_id(ast_c.hir_id),
516 const_param_did: Some(param_def_id),
518 let c = ty::Const::from_opt_const_arg_anon_const(self.tcx, const_def);
519 self.register_wf_obligation(
521 self.tcx.hir().span(ast_c.hir_id),
522 ObligationCauseCode::MiscObligation,
527 // If the type given by the user has free regions, save it for later, since
528 // NLL would like to enforce those. Also pass in types that involve
529 // projections, since those can resolve to `'static` bounds (modulo #54940,
530 // which hopefully will be fixed by the time you see this comment, dear
531 // reader, although I have my doubts). Also pass in types with inference
532 // types, because they may be repeated. Other sorts of things are already
533 // sufficiently enforced with erased regions. =)
534 fn can_contain_user_lifetime_bounds<T>(&self, t: T) -> bool
536 T: TypeFoldable<'tcx>,
538 t.has_free_regions(self.tcx) || t.has_projections() || t.has_infer_types()
541 pub fn node_ty(&self, id: hir::HirId) -> Ty<'tcx> {
542 match self.typeck_results.borrow().node_types().get(id) {
544 None if self.is_tainted_by_errors() => self.tcx.ty_error(),
547 "no type for node {}: {} in fcx {}",
549 self.tcx.hir().node_to_string(id),
556 pub fn node_ty_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
557 match self.typeck_results.borrow().node_types().get(id) {
559 None if self.is_tainted_by_errors() => Some(self.tcx.ty_error()),
564 /// Registers an obligation for checking later, during regionck, that `arg` is well-formed.
565 pub fn register_wf_obligation(
567 arg: subst::GenericArg<'tcx>,
569 code: traits::ObligationCauseCode<'tcx>,
571 // WF obligations never themselves fail, so no real need to give a detailed cause:
572 let cause = traits::ObligationCause::new(span, self.body_id, code);
573 self.register_predicate(traits::Obligation::new(
576 ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(self.tcx),
580 /// Registers obligations that all `substs` are well-formed.
581 pub fn add_wf_bounds(&self, substs: SubstsRef<'tcx>, expr: &hir::Expr<'_>) {
582 for arg in substs.iter().filter(|arg| {
583 matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
585 self.register_wf_obligation(arg, expr.span, traits::MiscObligation);
589 /// Given a fully substituted set of bounds (`generic_bounds`), and the values with which each
590 /// type/region parameter was instantiated (`substs`), creates and registers suitable
591 /// trait/region obligations.
593 /// For example, if there is a function:
596 /// fn foo<'a,T:'a>(...)
605 /// Then we will create a fresh region variable `'$0` and a fresh type variable `$1` for `'a`
606 /// and `T`. This routine will add a region obligation `$1:'$0` and register it locally.
607 pub fn add_obligations_for_parameters(
609 cause: traits::ObligationCause<'tcx>,
610 predicates: ty::InstantiatedPredicates<'tcx>,
612 assert!(!predicates.has_escaping_bound_vars());
614 debug!("add_obligations_for_parameters(predicates={:?})", predicates);
616 for obligation in traits::predicates_for_generics(cause, self.param_env, predicates) {
617 self.register_predicate(obligation);
621 // FIXME(arielb1): use this instead of field.ty everywhere
622 // Only for fields! Returns <none> for methods>
623 // Indifferent to privacy flags
627 field: &'tcx ty::FieldDef,
628 substs: SubstsRef<'tcx>,
630 self.normalize_associated_types_in(span, &field.ty(self.tcx, substs))
633 pub(in super::super) fn resolve_generator_interiors(&self, def_id: DefId) {
634 let mut generators = self.deferred_generator_interiors.borrow_mut();
635 for (body_id, interior, kind) in generators.drain(..) {
636 self.select_obligations_where_possible(false, |_| {});
637 crate::check::generator_interior::resolve_interior(
638 self, def_id, body_id, interior, kind,
643 #[instrument(skip(self), level = "debug")]
644 pub(in super::super) fn select_all_obligations_or_error(&self) {
645 if let Err(errors) = self
648 .select_all_with_constness_or_error(&self, self.inh.constness)
650 self.report_fulfillment_errors(&errors, self.inh.body_id, false);
654 /// Select as many obligations as we can at present.
655 pub(in super::super) fn select_obligations_where_possible(
657 fallback_has_occurred: bool,
658 mutate_fulfillment_errors: impl Fn(&mut Vec<traits::FulfillmentError<'tcx>>),
663 .select_with_constness_where_possible(self, self.inh.constness);
664 if let Err(mut errors) = result {
665 mutate_fulfillment_errors(&mut errors);
666 self.report_fulfillment_errors(&errors, self.inh.body_id, fallback_has_occurred);
670 /// For the overloaded place expressions (`*x`, `x[3]`), the trait
671 /// returns a type of `&T`, but the actual type we assign to the
672 /// *expression* is `T`. So this function just peels off the return
673 /// type by one layer to yield `T`.
674 pub(in super::super) fn make_overloaded_place_return_type(
676 method: MethodCallee<'tcx>,
677 ) -> ty::TypeAndMut<'tcx> {
678 // extract method return type, which will be &T;
679 let ret_ty = method.sig.output();
681 // method returns &T, but the type as visible to user is T, so deref
682 ret_ty.builtin_deref(true).unwrap()
685 #[instrument(skip(self), level = "debug")]
686 fn self_type_matches_expected_vid(
688 trait_ref: ty::PolyTraitRef<'tcx>,
689 expected_vid: ty::TyVid,
691 let self_ty = self.shallow_resolve(trait_ref.skip_binder().self_ty());
694 match *self_ty.kind() {
695 ty::Infer(ty::TyVar(found_vid)) => {
696 // FIXME: consider using `sub_root_var` here so we
697 // can see through subtyping.
698 let found_vid = self.root_var(found_vid);
699 debug!("self_type_matches_expected_vid - found_vid={:?}", found_vid);
700 expected_vid == found_vid
706 #[instrument(skip(self), level = "debug")]
707 pub(in super::super) fn obligations_for_self_ty<'b>(
710 ) -> impl Iterator<Item = (ty::PolyTraitRef<'tcx>, traits::PredicateObligation<'tcx>)>
713 // FIXME: consider using `sub_root_var` here so we
714 // can see through subtyping.
715 let ty_var_root = self.root_var(self_ty);
716 trace!("pending_obligations = {:#?}", self.fulfillment_cx.borrow().pending_obligations());
720 .pending_obligations()
722 .filter_map(move |obligation| {
723 let bound_predicate = obligation.predicate.kind();
724 match bound_predicate.skip_binder() {
725 ty::PredicateKind::Projection(data) => Some((
726 bound_predicate.rebind(data).required_poly_trait_ref(self.tcx),
729 ty::PredicateKind::Trait(data) => {
730 Some((bound_predicate.rebind(data).to_poly_trait_ref(), obligation))
732 ty::PredicateKind::Subtype(..) => None,
733 ty::PredicateKind::Coerce(..) => None,
734 ty::PredicateKind::RegionOutlives(..) => None,
735 ty::PredicateKind::TypeOutlives(..) => None,
736 ty::PredicateKind::WellFormed(..) => None,
737 ty::PredicateKind::ObjectSafe(..) => None,
738 ty::PredicateKind::ConstEvaluatable(..) => None,
739 ty::PredicateKind::ConstEquate(..) => None,
740 // N.B., this predicate is created by breaking down a
741 // `ClosureType: FnFoo()` predicate, where
742 // `ClosureType` represents some `Closure`. It can't
743 // possibly be referring to the current closure,
744 // because we haven't produced the `Closure` for
745 // this closure yet; this is exactly why the other
746 // code is looking for a self type of an unresolved
747 // inference variable.
748 ty::PredicateKind::ClosureKind(..) => None,
749 ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
752 .filter(move |(tr, _)| self.self_type_matches_expected_vid(*tr, ty_var_root))
755 pub(in super::super) fn type_var_is_sized(&self, self_ty: ty::TyVid) -> bool {
756 self.obligations_for_self_ty(self_ty)
757 .any(|(tr, _)| Some(tr.def_id()) == self.tcx.lang_items().sized_trait())
760 pub(in super::super) fn err_args(&self, len: usize) -> Vec<Ty<'tcx>> {
761 vec![self.tcx.ty_error(); len]
764 /// Unifies the output type with the expected type early, for more coercions
765 /// and forward type information on the input expressions.
766 #[instrument(skip(self, call_span), level = "debug")]
767 pub(in super::super) fn expected_inputs_for_expected_output(
770 expected_ret: Expectation<'tcx>,
771 formal_ret: Ty<'tcx>,
772 formal_args: &[Ty<'tcx>],
774 let formal_ret = self.resolve_vars_with_obligations(formal_ret);
775 let ret_ty = match expected_ret.only_has_type(self) {
777 None => return Vec::new(),
779 let expect_args = self
780 .fudge_inference_if_ok(|| {
781 // Attempt to apply a subtyping relationship between the formal
782 // return type (likely containing type variables if the function
783 // is polymorphic) and the expected return type.
784 // No argument expectations are produced if unification fails.
785 let origin = self.misc(call_span);
786 let ures = self.at(&origin, self.param_env).sup(ret_ty, &formal_ret);
788 // FIXME(#27336) can't use ? here, Try::from_error doesn't default
789 // to identity so the resulting type is not constrained.
792 // Process any obligations locally as much as
793 // we can. We don't care if some things turn
794 // out unconstrained or ambiguous, as we're
795 // just trying to get hints here.
796 self.save_and_restore_in_snapshot_flag(|_| {
797 let mut fulfill = <dyn TraitEngine<'_>>::new(self.tcx);
798 for obligation in ok.obligations {
799 fulfill.register_predicate_obligation(self, obligation);
801 fulfill.select_where_possible(self)
805 Err(_) => return Err(()),
808 // Record all the argument types, with the substitutions
809 // produced from the above subtyping unification.
810 Ok(formal_args.iter().map(|&ty| self.resolve_vars_if_possible(ty)).collect())
812 .unwrap_or_default();
813 debug!(?formal_args, ?formal_ret, ?expect_args, ?expected_ret);
817 pub(in super::super) fn resolve_lang_item_path(
819 lang_item: hir::LangItem,
822 ) -> (Res, Ty<'tcx>) {
823 let def_id = self.tcx.require_lang_item(lang_item, Some(span));
824 let def_kind = self.tcx.def_kind(def_id);
826 let item_ty = if let DefKind::Variant = def_kind {
827 self.tcx.type_of(self.tcx.parent(def_id).expect("variant w/out parent"))
829 self.tcx.type_of(def_id)
831 let substs = self.infcx.fresh_substs_for_item(span, def_id);
832 let ty = item_ty.subst(self.tcx, substs);
834 self.write_resolution(hir_id, Ok((def_kind, def_id)));
835 self.add_required_obligations(span, def_id, &substs);
836 (Res::Def(def_kind, def_id), ty)
839 /// Resolves an associated value path into a base type and associated constant, or method
840 /// resolution. The newly resolved definition is written into `type_dependent_defs`.
841 pub fn resolve_ty_and_res_fully_qualified_call(
843 qpath: &'tcx QPath<'tcx>,
846 ) -> (Res, Option<Ty<'tcx>>, &'tcx [hir::PathSegment<'tcx>]) {
848 "resolve_ty_and_res_fully_qualified_call: qpath={:?} hir_id={:?} span={:?}",
851 let (ty, qself, item_segment) = match *qpath {
852 QPath::Resolved(ref opt_qself, ref path) => {
855 opt_qself.as_ref().map(|qself| self.to_ty(qself)),
859 QPath::TypeRelative(ref qself, ref segment) => {
860 // Don't use `self.to_ty`, since this will register a WF obligation.
861 // If we're trying to call a non-existent method on a trait
862 // (e.g. `MyTrait::missing_method`), then resolution will
863 // give us a `QPath::TypeRelative` with a trait object as
864 // `qself`. In that case, we want to avoid registering a WF obligation
865 // for `dyn MyTrait`, since we don't actually need the trait
866 // to be object-safe.
867 // We manually call `register_wf_obligation` in the success path
869 (<dyn AstConv<'_>>::ast_ty_to_ty(self, qself), qself, segment)
871 QPath::LangItem(..) => {
872 bug!("`resolve_ty_and_res_fully_qualified_call` called on `LangItem`")
875 if let Some(&cached_result) = self.typeck_results.borrow().type_dependent_defs().get(hir_id)
877 self.register_wf_obligation(ty.into(), qself.span, traits::WellFormed(None));
878 // Return directly on cache hit. This is useful to avoid doubly reporting
879 // errors with default match binding modes. See #44614.
880 let def = cached_result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id));
881 return (def, Some(ty), slice::from_ref(&**item_segment));
883 let item_name = item_segment.ident;
885 .resolve_fully_qualified_call(span, item_name, ty, qself.span, hir_id)
887 let result = match error {
888 method::MethodError::PrivateMatch(kind, def_id, _) => Ok((kind, def_id)),
889 _ => Err(ErrorReported),
892 // If we have a path like `MyTrait::missing_method`, then don't register
893 // a WF obligation for `dyn MyTrait` when method lookup fails. Otherwise,
894 // register a WF obligation so that we can detect any additional
895 // errors in the self type.
896 if !(matches!(error, method::MethodError::NoMatch(_)) && ty.is_trait()) {
897 self.register_wf_obligation(ty.into(), qself.span, traits::WellFormed(None));
899 if item_name.name != kw::Empty {
900 if let Some(mut e) = self.report_method_error(
904 SelfSource::QPath(qself),
915 self.maybe_lint_bare_trait(qpath, hir_id, span);
916 self.register_wf_obligation(ty.into(), qself.span, traits::WellFormed(None));
919 // Write back the new resolution.
920 self.write_resolution(hir_id, result);
922 result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
924 slice::from_ref(&**item_segment),
928 fn maybe_lint_bare_trait(&self, qpath: &QPath<'_>, hir_id: hir::HirId, span: Span) {
929 if let QPath::TypeRelative(self_ty, _) = qpath {
930 if let TyKind::TraitObject([poly_trait_ref, ..], _, TraitObjectSyntax::None) =
933 let msg = "trait objects without an explicit `dyn` are deprecated";
934 let (sugg, app) = match self.tcx.sess.source_map().span_to_snippet(self_ty.span) {
935 Ok(s) if poly_trait_ref.trait_ref.path.is_global() => {
936 (format!("dyn ({})", s), Applicability::MachineApplicable)
938 Ok(s) => (format!("dyn {}", s), Applicability::MachineApplicable),
939 Err(_) => ("dyn <type>".to_string(), Applicability::HasPlaceholders),
941 // Wrap in `<..>` if it isn't already.
942 let sugg = match self.tcx.sess.source_map().span_to_snippet(span) {
943 Ok(s) if s.starts_with('<') => sugg,
944 _ => format!("<{}>", sugg),
946 let sugg_label = "use `dyn`";
947 if self.sess().edition() >= Edition::Edition2021 {
948 let mut err = rustc_errors::struct_span_err!(
959 Applicability::MachineApplicable,
963 self.tcx.struct_span_lint_hir(
968 let mut db = lint.build(msg);
969 db.span_suggestion(self_ty.span, sugg_label, sugg, app);
978 /// Given a function `Node`, return its `FnDecl` if it exists, or `None` otherwise.
979 pub(in super::super) fn get_node_fn_decl(
982 ) -> Option<(&'tcx hir::FnDecl<'tcx>, Ident, bool)> {
984 Node::Item(&hir::Item { ident, kind: hir::ItemKind::Fn(ref sig, ..), .. }) => {
985 // This is less than ideal, it will not suggest a return type span on any
986 // method called `main`, regardless of whether it is actually the entry point,
987 // but it will still present it as the reason for the expected type.
988 Some((&sig.decl, ident, ident.name != sym::main))
990 Node::TraitItem(&hir::TraitItem {
992 kind: hir::TraitItemKind::Fn(ref sig, ..),
994 }) => Some((&sig.decl, ident, true)),
995 Node::ImplItem(&hir::ImplItem {
997 kind: hir::ImplItemKind::Fn(ref sig, ..),
999 }) => Some((&sig.decl, ident, false)),
1004 /// Given a `HirId`, return the `FnDecl` of the method it is enclosed by and whether a
1005 /// suggestion can be made, `None` otherwise.
1006 pub fn get_fn_decl(&self, blk_id: hir::HirId) -> Option<(&'tcx hir::FnDecl<'tcx>, bool)> {
1007 // Get enclosing Fn, if it is a function or a trait method, unless there's a `loop` or
1008 // `while` before reaching it, as block tail returns are not available in them.
1009 self.tcx.hir().get_return_block(blk_id).and_then(|blk_id| {
1010 let parent = self.tcx.hir().get(blk_id);
1011 self.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main))
1015 pub(in super::super) fn note_internal_mutation_in_method(
1017 err: &mut DiagnosticBuilder<'_>,
1018 expr: &hir::Expr<'_>,
1022 if found != self.tcx.types.unit {
1025 if let ExprKind::MethodCall(path_segment, _, [rcvr, ..], _) = expr.kind {
1029 .expr_ty_adjusted_opt(rcvr)
1030 .map_or(true, |ty| expected.peel_refs() != ty.peel_refs())
1034 let mut sp = MultiSpan::from_span(path_segment.ident.span);
1036 path_segment.ident.span,
1038 "this call modifies {} in-place",
1040 ExprKind::Path(QPath::Resolved(
1042 hir::Path { segments: [segment], .. },
1043 )) => format!("`{}`", segment.ident),
1044 _ => "its receiver".to_string(),
1050 "you probably want to use this value after calling the method...".to_string(),
1054 &format!("method `{}` modifies its receiver in-place", path_segment.ident),
1056 err.note(&format!("...instead of the `()` output of method `{}`", path_segment.ident));
1060 pub(in super::super) fn note_need_for_fn_pointer(
1062 err: &mut DiagnosticBuilder<'_>,
1066 let (sig, did, substs) = match (&expected.kind(), &found.kind()) {
1067 (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => {
1068 let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1);
1069 let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2);
1074 "different `fn` items always have unique types, even if their signatures are \
1077 (sig1, *did1, substs1)
1079 (ty::FnDef(did, substs), ty::FnPtr(sig2)) => {
1080 let sig1 = self.tcx.fn_sig(*did).subst(self.tcx, substs);
1084 (sig1, *did, substs)
1088 err.help(&format!("change the expected type to be function pointer `{}`", sig));
1090 "if the expected type is due to type inference, cast the expected `fn` to a function \
1091 pointer: `{} as {}`",
1092 self.tcx.def_path_str_with_substs(did, substs),
1097 pub(in super::super) fn could_remove_semicolon(
1099 blk: &'tcx hir::Block<'tcx>,
1100 expected_ty: Ty<'tcx>,
1101 ) -> Option<(Span, StatementAsExpression)> {
1102 // Be helpful when the user wrote `{... expr;}` and
1103 // taking the `;` off is enough to fix the error.
1104 let last_stmt = blk.stmts.last()?;
1105 let last_expr = match last_stmt.kind {
1106 hir::StmtKind::Semi(ref e) => e,
1109 let last_expr_ty = self.node_ty(last_expr.hir_id);
1110 let needs_box = match (last_expr_ty.kind(), expected_ty.kind()) {
1111 (ty::Opaque(last_def_id, _), ty::Opaque(exp_def_id, _))
1112 if last_def_id == exp_def_id =>
1114 StatementAsExpression::CorrectType
1116 (ty::Opaque(last_def_id, last_bounds), ty::Opaque(exp_def_id, exp_bounds)) => {
1118 "both opaque, likely future {:?} {:?} {:?} {:?}",
1119 last_def_id, last_bounds, exp_def_id, exp_bounds
1122 let (last_local_id, exp_local_id) =
1123 match (last_def_id.as_local(), exp_def_id.as_local()) {
1124 (Some(last_hir_id), Some(exp_hir_id)) => (last_hir_id, exp_hir_id),
1125 (_, _) => return None,
1128 let last_hir_id = self.tcx.hir().local_def_id_to_hir_id(last_local_id);
1129 let exp_hir_id = self.tcx.hir().local_def_id_to_hir_id(exp_local_id);
1132 &self.tcx.hir().expect_item(last_hir_id).kind,
1133 &self.tcx.hir().expect_item(exp_hir_id).kind,
1136 hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds: last_bounds, .. }),
1137 hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds: exp_bounds, .. }),
1138 ) if iter::zip(*last_bounds, *exp_bounds).all(|(left, right)| {
1139 match (left, right) {
1141 hir::GenericBound::Trait(tl, ml),
1142 hir::GenericBound::Trait(tr, mr),
1143 ) if tl.trait_ref.trait_def_id() == tr.trait_ref.trait_def_id()
1149 hir::GenericBound::LangItemTrait(langl, _, _, argsl),
1150 hir::GenericBound::LangItemTrait(langr, _, _, argsr),
1151 ) if langl == langr => {
1152 // FIXME: consider the bounds!
1153 debug!("{:?} {:?}", argsl, argsr);
1160 StatementAsExpression::NeedsBoxing
1162 _ => StatementAsExpression::CorrectType,
1165 _ => StatementAsExpression::CorrectType,
1167 if (matches!(last_expr_ty.kind(), ty::Error(_))
1168 || self.can_sub(self.param_env, last_expr_ty, expected_ty).is_err())
1169 && matches!(needs_box, StatementAsExpression::CorrectType)
1173 let span = if last_stmt.span.from_expansion() {
1174 let mac_call = original_sp(last_stmt.span, blk.span);
1175 self.tcx.sess.source_map().mac_call_stmt_semi_span(mac_call)?
1177 last_stmt.span.with_lo(last_stmt.span.hi() - BytePos(1))
1179 Some((span, needs_box))
1182 // Instantiates the given path, which must refer to an item with the given
1183 // number of type parameters and type.
1184 #[instrument(skip(self, span), level = "debug")]
1185 pub fn instantiate_value_path(
1187 segments: &[hir::PathSegment<'_>],
1188 self_ty: Option<Ty<'tcx>>,
1192 ) -> (Ty<'tcx>, Res) {
1195 let path_segs = match res {
1196 Res::Local(_) | Res::SelfCtor(_) => vec![],
1197 Res::Def(kind, def_id) => <dyn AstConv<'_>>::def_ids_for_value_path_segments(
1198 self, segments, self_ty, kind, def_id,
1200 _ => bug!("instantiate_value_path on {:?}", res),
1203 let mut user_self_ty = None;
1204 let mut is_alias_variant_ctor = false;
1206 Res::Def(DefKind::Ctor(CtorOf::Variant, _), _)
1207 if let Some(self_ty) = self_ty =>
1209 let adt_def = self_ty.ty_adt_def().unwrap();
1210 user_self_ty = Some(UserSelfTy { impl_def_id: adt_def.did, self_ty });
1211 is_alias_variant_ctor = true;
1213 Res::Def(DefKind::AssocFn | DefKind::AssocConst, def_id) => {
1214 let container = tcx.associated_item(def_id).container;
1215 debug!(?def_id, ?container);
1217 ty::TraitContainer(trait_did) => {
1218 callee::check_legal_trait_for_method_call(tcx, span, None, span, trait_did)
1220 ty::ImplContainer(impl_def_id) => {
1221 if segments.len() == 1 {
1222 // `<T>::assoc` will end up here, and so
1223 // can `T::assoc`. It this came from an
1224 // inherent impl, we need to record the
1225 // `T` for posterity (see `UserSelfTy` for
1227 let self_ty = self_ty.expect("UFCS sugared assoc missing Self");
1228 user_self_ty = Some(UserSelfTy { impl_def_id, self_ty });
1236 // Now that we have categorized what space the parameters for each
1237 // segment belong to, let's sort out the parameters that the user
1238 // provided (if any) into their appropriate spaces. We'll also report
1239 // errors if type parameters are provided in an inappropriate place.
1241 let generic_segs: FxHashSet<_> = path_segs.iter().map(|PathSeg(_, index)| index).collect();
1242 let generics_has_err = <dyn AstConv<'_>>::prohibit_generics(
1244 segments.iter().enumerate().filter_map(|(index, seg)| {
1245 if !generic_segs.contains(&index) || is_alias_variant_ctor {
1253 if let Res::Local(hid) = res {
1254 let ty = self.local_ty(span, hid).decl_ty;
1255 let ty = self.normalize_associated_types_in(span, ty);
1256 self.write_ty(hir_id, ty);
1260 if generics_has_err {
1261 // Don't try to infer type parameters when prohibited generic arguments were given.
1262 user_self_ty = None;
1265 // Now we have to compare the types that the user *actually*
1266 // provided against the types that were *expected*. If the user
1267 // did not provide any types, then we want to substitute inference
1268 // variables. If the user provided some types, we may still need
1269 // to add defaults. If the user provided *too many* types, that's
1272 let mut infer_args_for_err = FxHashSet::default();
1274 let mut explicit_late_bound = ExplicitLateBound::No;
1275 for &PathSeg(def_id, index) in &path_segs {
1276 let seg = &segments[index];
1277 let generics = tcx.generics_of(def_id);
1279 // Argument-position `impl Trait` is treated as a normal generic
1280 // parameter internally, but we don't allow users to specify the
1281 // parameter's value explicitly, so we have to do some error-
1283 let arg_count = <dyn AstConv<'_>>::check_generic_arg_count_for_call(
1292 if let ExplicitLateBound::Yes = arg_count.explicit_late_bound {
1293 explicit_late_bound = ExplicitLateBound::Yes;
1296 if let Err(GenericArgCountMismatch { reported: Some(_), .. }) = arg_count.correct {
1297 infer_args_for_err.insert(index);
1298 self.set_tainted_by_errors(); // See issue #53251.
1302 let has_self = path_segs
1304 .map(|PathSeg(def_id, _)| tcx.generics_of(*def_id).has_self)
1307 let (res, self_ctor_substs) = if let Res::SelfCtor(impl_def_id) = res {
1308 let ty = self.normalize_ty(span, tcx.at(span).type_of(impl_def_id));
1310 ty::Adt(adt_def, substs) if adt_def.has_ctor() => {
1311 let variant = adt_def.non_enum_variant();
1312 let ctor_def_id = variant.ctor_def_id.unwrap();
1314 Res::Def(DefKind::Ctor(CtorOf::Struct, variant.ctor_kind), ctor_def_id),
1319 let mut err = tcx.sess.struct_span_err(
1321 "the `Self` constructor can only be used with tuple or unit structs",
1323 if let Some(adt_def) = ty.ty_adt_def() {
1324 match adt_def.adt_kind() {
1326 err.help("did you mean to use one of the enum's variants?");
1328 AdtKind::Struct | AdtKind::Union => {
1329 err.span_suggestion(
1331 "use curly brackets",
1332 String::from("Self { /* fields */ }"),
1333 Applicability::HasPlaceholders,
1340 return (tcx.ty_error(), res);
1346 let def_id = res.def_id();
1348 // The things we are substituting into the type should not contain
1349 // escaping late-bound regions, and nor should the base type scheme.
1350 let ty = tcx.type_of(def_id);
1352 let arg_count = GenericArgCountResult {
1353 explicit_late_bound,
1354 correct: if infer_args_for_err.is_empty() {
1357 Err(GenericArgCountMismatch::default())
1361 struct CreateCtorSubstsContext<'a, 'tcx> {
1362 fcx: &'a FnCtxt<'a, 'tcx>,
1364 path_segs: &'a [PathSeg],
1365 infer_args_for_err: &'a FxHashSet<usize>,
1366 segments: &'a [hir::PathSegment<'a>],
1368 impl<'tcx, 'a> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for CreateCtorSubstsContext<'a, 'tcx> {
1372 ) -> (Option<&'a hir::GenericArgs<'a>>, bool) {
1373 if let Some(&PathSeg(_, index)) =
1374 self.path_segs.iter().find(|&PathSeg(did, _)| *did == def_id)
1376 // If we've encountered an `impl Trait`-related error, we're just
1377 // going to infer the arguments for better error messages.
1378 if !self.infer_args_for_err.contains(&index) {
1379 // Check whether the user has provided generic arguments.
1380 if let Some(ref data) = self.segments[index].args {
1381 return (Some(data), self.segments[index].infer_args);
1384 return (None, self.segments[index].infer_args);
1392 param: &ty::GenericParamDef,
1393 arg: &GenericArg<'_>,
1394 ) -> subst::GenericArg<'tcx> {
1395 match (¶m.kind, arg) {
1396 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
1397 <dyn AstConv<'_>>::ast_region_to_region(self.fcx, lt, Some(param)).into()
1399 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
1400 self.fcx.to_ty(ty).into()
1402 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => {
1403 self.fcx.const_arg_to_const(&ct.value, param.def_id).into()
1405 (GenericParamDefKind::Type { .. }, GenericArg::Infer(inf)) => {
1406 self.fcx.ty_infer(Some(param), inf.span).into()
1408 (GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
1409 let tcx = self.fcx.tcx();
1410 self.fcx.ct_infer(tcx.type_of(param.def_id), Some(param), inf.span).into()
1412 _ => unreachable!(),
1418 substs: Option<&[subst::GenericArg<'tcx>]>,
1419 param: &ty::GenericParamDef,
1421 ) -> subst::GenericArg<'tcx> {
1422 let tcx = self.fcx.tcx();
1424 GenericParamDefKind::Lifetime => {
1425 self.fcx.re_infer(Some(param), self.span).unwrap().into()
1427 GenericParamDefKind::Type { has_default, .. } => {
1428 if !infer_args && has_default {
1429 // If we have a default, then we it doesn't matter that we're not
1430 // inferring the type arguments: we provide the default where any
1432 let default = tcx.type_of(param.def_id);
1436 default.subst_spanned(tcx, substs.unwrap(), Some(self.span)),
1440 // If no type arguments were provided, we have to infer them.
1441 // This case also occurs as a result of some malformed input, e.g.
1442 // a lifetime argument being given instead of a type parameter.
1443 // Using inference instead of `Error` gives better error messages.
1444 self.fcx.var_for_def(self.span, param)
1447 GenericParamDefKind::Const { has_default, .. } => {
1448 if !infer_args && has_default {
1449 tcx.const_param_default(param.def_id)
1450 .subst_spanned(tcx, substs.unwrap(), Some(self.span))
1453 self.fcx.var_for_def(self.span, param)
1460 let substs = self_ctor_substs.unwrap_or_else(|| {
1461 <dyn AstConv<'_>>::create_substs_for_generic_args(
1468 &mut CreateCtorSubstsContext {
1471 path_segs: &path_segs,
1472 infer_args_for_err: &infer_args_for_err,
1477 assert!(!substs.has_escaping_bound_vars());
1478 assert!(!ty.has_escaping_bound_vars());
1480 // First, store the "user substs" for later.
1481 self.write_user_type_annotation_from_substs(hir_id, def_id, substs, user_self_ty);
1483 self.add_required_obligations(span, def_id, &substs);
1485 // Substitute the values for the type parameters into the type of
1486 // the referenced item.
1487 let ty_substituted = self.instantiate_type_scheme(span, &substs, ty);
1489 if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty {
1490 // In the case of `Foo<T>::method` and `<Foo<T>>::method`, if `method`
1491 // is inherent, there is no `Self` parameter; instead, the impl needs
1492 // type parameters, which we can infer by unifying the provided `Self`
1493 // with the substituted impl type.
1494 // This also occurs for an enum variant on a type alias.
1495 let ty = tcx.type_of(impl_def_id);
1497 let impl_ty = self.instantiate_type_scheme(span, &substs, ty);
1498 match self.at(&self.misc(span), self.param_env).eq(impl_ty, self_ty) {
1499 Ok(ok) => self.register_infer_ok_obligations(ok),
1501 self.tcx.sess.delay_span_bug(
1504 "instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?",
1513 debug!("instantiate_value_path: type of {:?} is {:?}", hir_id, ty_substituted);
1514 self.write_substs(hir_id, substs);
1516 (ty_substituted, res)
1519 /// Add all the obligations that are required, substituting and normalized appropriately.
1520 #[tracing::instrument(level = "debug", skip(self, span, def_id, substs))]
1521 fn add_required_obligations(&self, span: Span, def_id: DefId, substs: &SubstsRef<'tcx>) {
1522 let (bounds, spans) = self.instantiate_bounds(span, def_id, &substs);
1524 for (i, mut obligation) in traits::predicates_for_generics(
1525 traits::ObligationCause::new(span, self.body_id, traits::ItemObligation(def_id)),
1531 // This makes the error point at the bound, but we want to point at the argument
1532 if let Some(span) = spans.get(i) {
1533 obligation.cause.make_mut().code = traits::BindingObligation(def_id, *span);
1535 self.register_predicate(obligation);
1539 /// Resolves `typ` by a single level if `typ` is a type variable.
1540 /// If no resolution is possible, then an error is reported.
1541 /// Numeric inference variables may be left unresolved.
1542 pub fn structurally_resolved_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
1543 let ty = self.resolve_vars_with_obligations(ty);
1544 if !ty.is_ty_var() {
1547 if !self.is_tainted_by_errors() {
1548 self.emit_inference_failure_err((**self).body_id, sp, ty.into(), vec![], E0282)
1549 .note("type must be known at this point")
1552 let err = self.tcx.ty_error();
1553 self.demand_suptype(sp, err, ty);
1558 pub(in super::super) fn with_breakable_ctxt<F: FnOnce() -> R, R>(
1561 ctxt: BreakableCtxt<'tcx>,
1563 ) -> (BreakableCtxt<'tcx>, R) {
1566 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
1567 index = enclosing_breakables.stack.len();
1568 enclosing_breakables.by_id.insert(id, index);
1569 enclosing_breakables.stack.push(ctxt);
1573 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
1574 debug_assert!(enclosing_breakables.stack.len() == index + 1);
1575 enclosing_breakables.by_id.remove(&id).expect("missing breakable context");
1576 enclosing_breakables.stack.pop().expect("missing breakable context")
1581 /// Instantiate a QueryResponse in a probe context, without a
1582 /// good ObligationCause.
1583 pub(in super::super) fn probe_instantiate_query_response(
1586 original_values: &OriginalQueryValues<'tcx>,
1587 query_result: &Canonical<'tcx, QueryResponse<'tcx, Ty<'tcx>>>,
1588 ) -> InferResult<'tcx, Ty<'tcx>> {
1589 self.instantiate_query_response_and_region_obligations(
1590 &traits::ObligationCause::misc(span, self.body_id),
1597 /// Returns `true` if an expression is contained inside the LHS of an assignment expression.
1598 pub(in super::super) fn expr_in_place(&self, mut expr_id: hir::HirId) -> bool {
1599 let mut contained_in_place = false;
1601 while let hir::Node::Expr(parent_expr) =
1602 self.tcx.hir().get(self.tcx.hir().get_parent_node(expr_id))
1604 match &parent_expr.kind {
1605 hir::ExprKind::Assign(lhs, ..) | hir::ExprKind::AssignOp(_, lhs, ..) => {
1606 if lhs.hir_id == expr_id {
1607 contained_in_place = true;
1613 expr_id = parent_expr.hir_id;