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::rvalue_scopes;
8 use crate::check::{BreakableCtxt, Diverges, Expectation, FnCtxt, LocalTy};
10 use rustc_data_structures::captures::Captures;
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_errors::{Applicability, Diagnostic, ErrorGuaranteed, MultiSpan};
14 use rustc_hir::def::{CtorOf, DefKind, Res};
15 use rustc_hir::def_id::DefId;
16 use rustc_hir::lang_items::LangItem;
17 use rustc_hir::{ExprKind, GenericArg, Node, QPath};
18 use rustc_infer::infer::canonical::{Canonical, OriginalQueryValues, QueryResponse};
19 use rustc_infer::infer::error_reporting::TypeAnnotationNeeded::E0282;
20 use rustc_infer::infer::{InferOk, InferResult};
21 use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability};
22 use rustc_middle::ty::fold::TypeFoldable;
23 use rustc_middle::ty::visit::TypeVisitable;
24 use rustc_middle::ty::{
25 self, AdtKind, CanonicalUserType, DefIdTree, EarlyBinder, GenericParamDefKind, ToPolyTraitRef,
26 ToPredicate, Ty, UserType,
28 use rustc_middle::ty::{GenericArgKind, InternalSubsts, SubstsRef, UserSelfTy, UserSubsts};
29 use rustc_session::lint;
30 use rustc_span::def_id::LocalDefId;
31 use rustc_span::hygiene::DesugaringKind;
32 use rustc_span::symbol::{kw, sym, Ident};
33 use rustc_span::{Span, DUMMY_SP};
34 use rustc_trait_selection::infer::InferCtxtExt as _;
35 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
36 use rustc_trait_selection::traits::{
37 self, ObligationCause, ObligationCauseCode, TraitEngine, TraitEngineExt,
40 use std::collections::hash_map::Entry;
43 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
44 /// Produces warning on the given node, if the current point in the
45 /// function is unreachable, and there hasn't been another warning.
46 pub(in super::super) fn warn_if_unreachable(&self, id: hir::HirId, span: Span, kind: &str) {
47 // FIXME: Combine these two 'if' expressions into one once
48 // let chains are implemented
49 if let Diverges::Always { span: orig_span, custom_note } = self.diverges.get() {
50 // If span arose from a desugaring of `if` or `while`, then it is the condition itself,
51 // which diverges, that we are about to lint on. This gives suboptimal diagnostics.
52 // Instead, stop here so that the `if`- or `while`-expression's block is linted instead.
53 if !span.is_desugaring(DesugaringKind::CondTemporary)
54 && !span.is_desugaring(DesugaringKind::Async)
55 && !orig_span.is_desugaring(DesugaringKind::Await)
57 self.diverges.set(Diverges::WarnedAlways);
59 debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind);
61 self.tcx().struct_span_lint_hir(lint::builtin::UNREACHABLE_CODE, id, span, |lint| {
62 let msg = format!("unreachable {}", kind);
64 .span_label(span, &msg)
68 .unwrap_or("any code following this expression is unreachable"),
76 /// Resolves type and const variables in `ty` if possible. Unlike the infcx
77 /// version (resolve_vars_if_possible), this version will
78 /// also select obligations if it seems useful, in an effort
79 /// to get more type information.
80 pub(in super::super) fn resolve_vars_with_obligations(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
81 self.resolve_vars_with_obligations_and_mutate_fulfillment(ty, |_| {})
84 #[instrument(skip(self, mutate_fulfillment_errors), level = "debug", ret)]
85 pub(in super::super) fn resolve_vars_with_obligations_and_mutate_fulfillment(
88 mutate_fulfillment_errors: impl Fn(&mut Vec<traits::FulfillmentError<'tcx>>),
90 // No Infer()? Nothing needs doing.
91 if !ty.has_infer_types_or_consts() {
92 debug!("no inference var, nothing needs doing");
96 // If `ty` is a type variable, see whether we already know what it is.
97 ty = self.resolve_vars_if_possible(ty);
98 if !ty.has_infer_types_or_consts() {
103 // If not, try resolving pending obligations as much as
104 // possible. This can help substantially when there are
105 // indirect dependencies that don't seem worth tracking
107 self.select_obligations_where_possible(false, mutate_fulfillment_errors);
108 self.resolve_vars_if_possible(ty)
111 pub(in super::super) fn record_deferred_call_resolution(
113 closure_def_id: LocalDefId,
114 r: DeferredCallResolution<'tcx>,
116 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
117 deferred_call_resolutions.entry(closure_def_id).or_default().push(r);
120 pub(in super::super) fn remove_deferred_call_resolutions(
122 closure_def_id: LocalDefId,
123 ) -> Vec<DeferredCallResolution<'tcx>> {
124 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
125 deferred_call_resolutions.remove(&closure_def_id).unwrap_or_default()
128 pub fn tag(&self) -> String {
129 format!("{:p}", self)
132 pub fn local_ty(&self, span: Span, nid: hir::HirId) -> LocalTy<'tcx> {
133 self.locals.borrow().get(&nid).cloned().unwrap_or_else(|| {
134 span_bug!(span, "no type for local variable {}", self.tcx.hir().node_to_string(nid))
139 pub fn write_ty(&self, id: hir::HirId, ty: Ty<'tcx>) {
140 debug!("write_ty({:?}, {:?}) in fcx {}", id, self.resolve_vars_if_possible(ty), self.tag());
141 self.typeck_results.borrow_mut().node_types_mut().insert(id, ty);
143 if ty.references_error() {
144 self.has_errors.set(true);
145 self.set_tainted_by_errors();
149 pub fn write_field_index(&self, hir_id: hir::HirId, index: usize) {
150 self.typeck_results.borrow_mut().field_indices_mut().insert(hir_id, index);
153 #[instrument(level = "debug", skip(self))]
154 pub(in super::super) fn write_resolution(
157 r: Result<(DefKind, DefId), ErrorGuaranteed>,
159 self.typeck_results.borrow_mut().type_dependent_defs_mut().insert(hir_id, r);
162 #[instrument(level = "debug", skip(self))]
163 pub fn write_method_call(&self, hir_id: hir::HirId, method: MethodCallee<'tcx>) {
164 self.write_resolution(hir_id, Ok((DefKind::AssocFn, method.def_id)));
165 self.write_substs(hir_id, method.substs);
167 // When the method is confirmed, the `method.substs` includes
168 // parameters from not just the method, but also the impl of
169 // the method -- in particular, the `Self` type will be fully
170 // resolved. However, those are not something that the "user
171 // specified" -- i.e., those types come from the inferred type
172 // of the receiver, not something the user wrote. So when we
173 // create the user-substs, we want to replace those earlier
174 // types with just the types that the user actually wrote --
175 // that is, those that appear on the *method itself*.
177 // As an example, if the user wrote something like
178 // `foo.bar::<u32>(...)` -- the `Self` type here will be the
179 // type of `foo` (possibly adjusted), but we don't want to
180 // include that. We want just the `[_, u32]` part.
181 if !method.substs.is_empty() {
182 let method_generics = self.tcx.generics_of(method.def_id);
183 if !method_generics.params.is_empty() {
184 let user_type_annotation = self.probe(|_| {
185 let user_substs = UserSubsts {
186 substs: InternalSubsts::for_item(self.tcx, method.def_id, |param, _| {
187 let i = param.index as usize;
188 if i < method_generics.parent_count {
189 self.var_for_def(DUMMY_SP, param)
194 user_self_ty: None, // not relevant here
197 self.canonicalize_user_type_annotation(UserType::TypeOf(
203 debug!("write_method_call: user_type_annotation={:?}", user_type_annotation);
204 self.write_user_type_annotation(hir_id, user_type_annotation);
209 pub fn write_substs(&self, node_id: hir::HirId, substs: SubstsRef<'tcx>) {
210 if !substs.is_empty() {
211 debug!("write_substs({:?}, {:?}) in fcx {}", node_id, substs, self.tag());
213 self.typeck_results.borrow_mut().node_substs_mut().insert(node_id, substs);
217 /// Given the substs that we just converted from the HIR, try to
218 /// canonicalize them and store them as user-given substitutions
219 /// (i.e., substitutions that must be respected by the NLL check).
221 /// This should be invoked **before any unifications have
222 /// occurred**, so that annotations like `Vec<_>` are preserved
224 #[instrument(skip(self), level = "debug")]
225 pub fn write_user_type_annotation_from_substs(
229 substs: SubstsRef<'tcx>,
230 user_self_ty: Option<UserSelfTy<'tcx>>,
232 debug!("fcx {}", self.tag());
234 if Self::can_contain_user_lifetime_bounds((substs, user_self_ty)) {
235 let canonicalized = self.canonicalize_user_type_annotation(UserType::TypeOf(
237 UserSubsts { substs, user_self_ty },
239 debug!(?canonicalized);
240 self.write_user_type_annotation(hir_id, canonicalized);
244 #[instrument(skip(self), level = "debug")]
245 pub fn write_user_type_annotation(
248 canonical_user_type_annotation: CanonicalUserType<'tcx>,
250 debug!("fcx {}", self.tag());
252 if !canonical_user_type_annotation.is_identity() {
255 .user_provided_types_mut()
256 .insert(hir_id, canonical_user_type_annotation);
258 debug!("skipping identity substs");
262 #[instrument(skip(self, expr), level = "debug")]
263 pub fn apply_adjustments(&self, expr: &hir::Expr<'_>, adj: Vec<Adjustment<'tcx>>) {
264 debug!("expr = {:#?}", expr);
271 if let Adjust::NeverToAny = a.kind {
272 if a.target.is_ty_var() {
273 self.diverging_type_vars.borrow_mut().insert(a.target);
274 debug!("apply_adjustments: adding `{:?}` as diverging type var", a.target);
279 let autoborrow_mut = adj.iter().any(|adj| {
283 kind: Adjust::Borrow(AutoBorrow::Ref(_, AutoBorrowMutability::Mut { .. })),
289 match self.typeck_results.borrow_mut().adjustments_mut().entry(expr.hir_id) {
290 Entry::Vacant(entry) => {
293 Entry::Occupied(mut entry) => {
294 debug!(" - composing on top of {:?}", entry.get());
295 match (&entry.get()[..], &adj[..]) {
296 // Applying any adjustment on top of a NeverToAny
297 // is a valid NeverToAny adjustment, because it can't
299 (&[Adjustment { kind: Adjust::NeverToAny, .. }], _) => return,
302 Adjustment { kind: Adjust::Deref(_), .. },
303 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), .. },
306 Adjustment { kind: Adjust::Deref(_), .. },
307 .., // Any following adjustments are allowed.
310 // A reborrow has no effect before a dereference.
312 // FIXME: currently we never try to compose autoderefs
313 // and ReifyFnPointer/UnsafeFnPointer, but we could.
315 self.tcx.sess.delay_span_bug(
318 "while adjusting {:?}, can't compose {:?} and {:?}",
326 *entry.get_mut() = adj;
330 // If there is an mutable auto-borrow, it is equivalent to `&mut <expr>`.
331 // In this case implicit use of `Deref` and `Index` within `<expr>` should
332 // instead be `DerefMut` and `IndexMut`, so fix those up.
334 self.convert_place_derefs_to_mutable(expr);
338 /// Basically whenever we are converting from a type scheme into
339 /// the fn body space, we always want to normalize associated
340 /// types as well. This function combines the two.
341 fn instantiate_type_scheme<T>(&self, span: Span, substs: SubstsRef<'tcx>, value: T) -> T
343 T: TypeFoldable<'tcx>,
345 debug!("instantiate_type_scheme(value={:?}, substs={:?})", value, substs);
346 let value = EarlyBinder(value).subst(self.tcx, substs);
347 let result = self.normalize_associated_types_in(span, value);
348 debug!("instantiate_type_scheme = {:?}", result);
352 /// As `instantiate_type_scheme`, but for the bounds found in a
353 /// generic type scheme.
354 pub(in super::super) fn instantiate_bounds(
358 substs: SubstsRef<'tcx>,
359 ) -> (ty::InstantiatedPredicates<'tcx>, Vec<Span>) {
360 let bounds = self.tcx.predicates_of(def_id);
361 let spans: Vec<Span> = bounds.predicates.iter().map(|(_, span)| *span).collect();
362 let result = bounds.instantiate(self.tcx, substs);
363 let result = self.normalize_associated_types_in(span, result);
365 "instantiate_bounds(bounds={:?}, substs={:?}) = {:?}, {:?}",
366 bounds, substs, result, spans,
371 pub(in super::super) fn normalize_associated_types_in<T>(&self, span: Span, value: T) -> T
373 T: TypeFoldable<'tcx>,
375 self.inh.normalize_associated_types_in(span, self.body_id, self.param_env, value)
378 pub(in super::super) fn normalize_associated_types_in_as_infer_ok<T>(
382 ) -> InferOk<'tcx, T>
384 T: TypeFoldable<'tcx>,
386 self.inh.partially_normalize_associated_types_in(
387 ObligationCause::misc(span, self.body_id),
393 pub(in super::super) fn normalize_op_associated_types_in_as_infer_ok<T>(
397 opt_input_expr: Option<&hir::Expr<'_>>,
398 ) -> InferOk<'tcx, T>
400 T: TypeFoldable<'tcx>,
402 self.inh.partially_normalize_associated_types_in(
403 ObligationCause::new(
407 rhs_span: opt_input_expr.map(|expr| expr.span),
408 is_lit: opt_input_expr
409 .map_or(false, |expr| matches!(expr.kind, ExprKind::Lit(_))),
418 pub fn require_type_meets(
422 code: traits::ObligationCauseCode<'tcx>,
425 self.register_bound(ty, def_id, traits::ObligationCause::new(span, self.body_id, code));
428 pub fn require_type_is_sized(
432 code: traits::ObligationCauseCode<'tcx>,
434 if !ty.references_error() {
435 let lang_item = self.tcx.require_lang_item(LangItem::Sized, None);
436 self.require_type_meets(ty, span, code, lang_item);
440 pub fn require_type_is_sized_deferred(
444 code: traits::ObligationCauseCode<'tcx>,
446 if !ty.references_error() {
447 self.deferred_sized_obligations.borrow_mut().push((ty, span, code));
451 pub fn register_bound(
455 cause: traits::ObligationCause<'tcx>,
457 if !ty.references_error() {
458 self.fulfillment_cx.borrow_mut().register_bound(
468 pub fn to_ty(&self, ast_t: &hir::Ty<'_>) -> Ty<'tcx> {
469 let t = <dyn AstConv<'_>>::ast_ty_to_ty(self, ast_t);
470 self.register_wf_obligation(t.into(), ast_t.span, traits::WellFormed(None));
474 pub fn to_ty_saving_user_provided_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
475 let ty = self.to_ty(ast_ty);
476 debug!("to_ty_saving_user_provided_ty: ty={:?}", ty);
478 if Self::can_contain_user_lifetime_bounds(ty) {
479 let c_ty = self.canonicalize_response(UserType::Ty(ty));
480 debug!("to_ty_saving_user_provided_ty: c_ty={:?}", c_ty);
481 self.typeck_results.borrow_mut().user_provided_types_mut().insert(ast_ty.hir_id, c_ty);
487 pub fn array_length_to_const(&self, length: &hir::ArrayLen) -> ty::Const<'tcx> {
489 &hir::ArrayLen::Infer(_, span) => self.ct_infer(self.tcx.types.usize, None, span),
490 hir::ArrayLen::Body(anon_const) => {
491 let const_def_id = self.tcx.hir().local_def_id(anon_const.hir_id);
492 let span = self.tcx.hir().span(anon_const.hir_id);
493 let c = ty::Const::from_anon_const(self.tcx, const_def_id);
494 self.register_wf_obligation(c.into(), span, ObligationCauseCode::WellFormed(None));
495 self.normalize_associated_types_in(span, c)
500 pub fn const_arg_to_const(
502 ast_c: &hir::AnonConst,
504 ) -> ty::Const<'tcx> {
505 let const_def = ty::WithOptConstParam {
506 did: self.tcx.hir().local_def_id(ast_c.hir_id),
507 const_param_did: Some(param_def_id),
509 let c = ty::Const::from_opt_const_arg_anon_const(self.tcx, const_def);
510 self.register_wf_obligation(
512 self.tcx.hir().span(ast_c.hir_id),
513 ObligationCauseCode::WellFormed(None),
518 // If the type given by the user has free regions, save it for later, since
519 // NLL would like to enforce those. Also pass in types that involve
520 // projections, since those can resolve to `'static` bounds (modulo #54940,
521 // which hopefully will be fixed by the time you see this comment, dear
522 // reader, although I have my doubts). Also pass in types with inference
523 // types, because they may be repeated. Other sorts of things are already
524 // sufficiently enforced with erased regions. =)
525 fn can_contain_user_lifetime_bounds<T>(t: T) -> bool
527 T: TypeVisitable<'tcx>,
529 t.has_free_regions() || t.has_projections() || t.has_infer_types()
532 pub fn node_ty(&self, id: hir::HirId) -> Ty<'tcx> {
533 match self.typeck_results.borrow().node_types().get(id) {
535 None if self.is_tainted_by_errors() => self.tcx.ty_error(),
538 "no type for node {}: {} in fcx {}",
540 self.tcx.hir().node_to_string(id),
547 pub fn node_ty_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
548 match self.typeck_results.borrow().node_types().get(id) {
550 None if self.is_tainted_by_errors() => Some(self.tcx.ty_error()),
555 /// Registers an obligation for checking later, during regionck, that `arg` is well-formed.
556 pub fn register_wf_obligation(
558 arg: ty::GenericArg<'tcx>,
560 code: traits::ObligationCauseCode<'tcx>,
562 // WF obligations never themselves fail, so no real need to give a detailed cause:
563 let cause = traits::ObligationCause::new(span, self.body_id, code);
564 self.register_predicate(traits::Obligation::new(
567 ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(self.tcx),
571 /// Registers obligations that all `substs` are well-formed.
572 pub fn add_wf_bounds(&self, substs: SubstsRef<'tcx>, expr: &hir::Expr<'_>) {
573 for arg in substs.iter().filter(|arg| {
574 matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
576 self.register_wf_obligation(arg, expr.span, traits::WellFormed(None));
580 // FIXME(arielb1): use this instead of field.ty everywhere
581 // Only for fields! Returns <none> for methods>
582 // Indifferent to privacy flags
586 field: &'tcx ty::FieldDef,
587 substs: SubstsRef<'tcx>,
589 self.normalize_associated_types_in(span, field.ty(self.tcx, substs))
592 pub(in super::super) fn resolve_rvalue_scopes(&self, def_id: DefId) {
593 let scope_tree = self.tcx.region_scope_tree(def_id);
594 let rvalue_scopes = { rvalue_scopes::resolve_rvalue_scopes(self, &scope_tree, def_id) };
595 let mut typeck_results = self.inh.typeck_results.borrow_mut();
596 typeck_results.rvalue_scopes = rvalue_scopes;
599 pub(in super::super) fn resolve_generator_interiors(&self, def_id: DefId) {
600 let mut generators = self.deferred_generator_interiors.borrow_mut();
601 for (body_id, interior, kind) in generators.drain(..) {
602 self.select_obligations_where_possible(false, |_| {});
603 crate::check::generator_interior::resolve_interior(
604 self, def_id, body_id, interior, kind,
609 #[instrument(skip(self), level = "debug")]
610 pub(in super::super) fn select_all_obligations_or_error(&self) {
611 let mut errors = self.fulfillment_cx.borrow_mut().select_all_or_error(&self);
613 if !errors.is_empty() {
614 self.adjust_fulfillment_errors_for_expr_obligation(&mut errors);
615 self.report_fulfillment_errors(&errors, self.inh.body_id, false);
619 /// Select as many obligations as we can at present.
620 pub(in super::super) fn select_obligations_where_possible(
622 fallback_has_occurred: bool,
623 mutate_fulfillment_errors: impl Fn(&mut Vec<traits::FulfillmentError<'tcx>>),
625 let mut result = self.fulfillment_cx.borrow_mut().select_where_possible(self);
626 if !result.is_empty() {
627 mutate_fulfillment_errors(&mut result);
628 self.adjust_fulfillment_errors_for_expr_obligation(&mut result);
629 self.report_fulfillment_errors(&result, self.inh.body_id, fallback_has_occurred);
633 /// For the overloaded place expressions (`*x`, `x[3]`), the trait
634 /// returns a type of `&T`, but the actual type we assign to the
635 /// *expression* is `T`. So this function just peels off the return
636 /// type by one layer to yield `T`.
637 pub(in super::super) fn make_overloaded_place_return_type(
639 method: MethodCallee<'tcx>,
640 ) -> ty::TypeAndMut<'tcx> {
641 // extract method return type, which will be &T;
642 let ret_ty = method.sig.output();
644 // method returns &T, but the type as visible to user is T, so deref
645 ret_ty.builtin_deref(true).unwrap()
648 #[instrument(skip(self), level = "debug")]
649 fn self_type_matches_expected_vid(
651 trait_ref: ty::PolyTraitRef<'tcx>,
652 expected_vid: ty::TyVid,
654 let self_ty = self.shallow_resolve(trait_ref.skip_binder().self_ty());
657 match *self_ty.kind() {
658 ty::Infer(ty::TyVar(found_vid)) => {
659 // FIXME: consider using `sub_root_var` here so we
660 // can see through subtyping.
661 let found_vid = self.root_var(found_vid);
662 debug!("self_type_matches_expected_vid - found_vid={:?}", found_vid);
663 expected_vid == found_vid
669 #[instrument(skip(self), level = "debug")]
670 pub(in super::super) fn obligations_for_self_ty<'b>(
673 ) -> impl Iterator<Item = (ty::PolyTraitRef<'tcx>, traits::PredicateObligation<'tcx>)>
676 // FIXME: consider using `sub_root_var` here so we
677 // can see through subtyping.
678 let ty_var_root = self.root_var(self_ty);
679 trace!("pending_obligations = {:#?}", self.fulfillment_cx.borrow().pending_obligations());
683 .pending_obligations()
685 .filter_map(move |obligation| {
686 let bound_predicate = obligation.predicate.kind();
687 match bound_predicate.skip_binder() {
688 ty::PredicateKind::Projection(data) => Some((
689 bound_predicate.rebind(data).required_poly_trait_ref(self.tcx),
692 ty::PredicateKind::Trait(data) => {
693 Some((bound_predicate.rebind(data).to_poly_trait_ref(), obligation))
695 ty::PredicateKind::Subtype(..) => None,
696 ty::PredicateKind::Coerce(..) => None,
697 ty::PredicateKind::RegionOutlives(..) => None,
698 ty::PredicateKind::TypeOutlives(..) => None,
699 ty::PredicateKind::WellFormed(..) => None,
700 ty::PredicateKind::ObjectSafe(..) => None,
701 ty::PredicateKind::ConstEvaluatable(..) => None,
702 ty::PredicateKind::ConstEquate(..) => None,
703 // N.B., this predicate is created by breaking down a
704 // `ClosureType: FnFoo()` predicate, where
705 // `ClosureType` represents some `Closure`. It can't
706 // possibly be referring to the current closure,
707 // because we haven't produced the `Closure` for
708 // this closure yet; this is exactly why the other
709 // code is looking for a self type of an unresolved
710 // inference variable.
711 ty::PredicateKind::ClosureKind(..) => None,
712 ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
715 .filter(move |(tr, _)| self.self_type_matches_expected_vid(*tr, ty_var_root))
718 pub(in super::super) fn type_var_is_sized(&self, self_ty: ty::TyVid) -> bool {
719 self.obligations_for_self_ty(self_ty)
720 .any(|(tr, _)| Some(tr.def_id()) == self.tcx.lang_items().sized_trait())
723 pub(in super::super) fn err_args(&self, len: usize) -> Vec<Ty<'tcx>> {
724 vec![self.tcx.ty_error(); len]
727 /// Unifies the output type with the expected type early, for more coercions
728 /// and forward type information on the input expressions.
729 #[instrument(skip(self, call_span), level = "debug")]
730 pub(in super::super) fn expected_inputs_for_expected_output(
733 expected_ret: Expectation<'tcx>,
734 formal_ret: Ty<'tcx>,
735 formal_args: &[Ty<'tcx>],
736 ) -> Option<Vec<Ty<'tcx>>> {
737 let formal_ret = self.resolve_vars_with_obligations(formal_ret);
738 let ret_ty = expected_ret.only_has_type(self)?;
740 // HACK(oli-obk): This is a hack to keep RPIT and TAIT in sync wrt their behaviour.
741 // Without it, the inference
742 // variable will get instantiated with the opaque type. The inference variable often
743 // has various helpful obligations registered for it that help closures figure out their
744 // signature. If we infer the inference var to the opaque type, the closure won't be able
745 // to find those obligations anymore, and it can't necessarily find them from the opaque
746 // type itself. We could be more powerful with inference if we *combined* the obligations
747 // so that we got both the obligations from the opaque type and the ones from the inference
748 // variable. That will accept more code than we do right now, so we need to carefully consider
750 // Note: this check is pessimistic, as the inference type could be matched with something other
751 // than the opaque type, but then we need a new `TypeRelation` just for this specific case and
752 // can't re-use `sup` below.
753 // See src/test/ui/impl-trait/hidden-type-is-opaque.rs and
754 // src/test/ui/impl-trait/hidden-type-is-opaque-2.rs for examples that hit this path.
755 if formal_ret.has_infer_types() {
756 for ty in ret_ty.walk() {
757 if let ty::subst::GenericArgKind::Type(ty) = ty.unpack()
758 && let ty::Opaque(def_id, _) = *ty.kind()
759 && let Some(def_id) = def_id.as_local()
760 && self.opaque_type_origin(def_id, DUMMY_SP).is_some() {
766 let expect_args = self
767 .fudge_inference_if_ok(|| {
768 // Attempt to apply a subtyping relationship between the formal
769 // return type (likely containing type variables if the function
770 // is polymorphic) and the expected return type.
771 // No argument expectations are produced if unification fails.
772 let origin = self.misc(call_span);
773 let ures = self.at(&origin, self.param_env).sup(ret_ty, formal_ret);
775 // FIXME(#27336) can't use ? here, Try::from_error doesn't default
776 // to identity so the resulting type is not constrained.
779 // Process any obligations locally as much as
780 // we can. We don't care if some things turn
781 // out unconstrained or ambiguous, as we're
782 // just trying to get hints here.
783 let errors = self.save_and_restore_in_snapshot_flag(|_| {
784 let mut fulfill = <dyn TraitEngine<'_>>::new(self.tcx);
785 for obligation in ok.obligations {
786 fulfill.register_predicate_obligation(self, obligation);
788 fulfill.select_where_possible(self)
791 if !errors.is_empty() {
795 Err(_) => return Err(()),
798 // Record all the argument types, with the substitutions
799 // produced from the above subtyping unification.
800 Ok(Some(formal_args.iter().map(|&ty| self.resolve_vars_if_possible(ty)).collect()))
802 .unwrap_or_default();
803 debug!(?formal_args, ?formal_ret, ?expect_args, ?expected_ret);
807 pub(in super::super) fn resolve_lang_item_path(
809 lang_item: hir::LangItem,
812 expr_hir_id: Option<hir::HirId>,
813 ) -> (Res, Ty<'tcx>) {
814 let def_id = self.tcx.require_lang_item(lang_item, Some(span));
815 let def_kind = self.tcx.def_kind(def_id);
817 let item_ty = if let DefKind::Variant = def_kind {
818 self.tcx.bound_type_of(self.tcx.parent(def_id))
820 self.tcx.bound_type_of(def_id)
822 let substs = self.fresh_substs_for_item(span, def_id);
823 let ty = item_ty.subst(self.tcx, substs);
825 self.write_resolution(hir_id, Ok((def_kind, def_id)));
827 let code = match lang_item {
828 hir::LangItem::IntoFutureIntoFuture => {
829 Some(ObligationCauseCode::AwaitableExpr(expr_hir_id))
831 hir::LangItem::IteratorNext | hir::LangItem::IntoIterIntoIter => {
832 Some(ObligationCauseCode::ForLoopIterator)
834 hir::LangItem::TryTraitFromOutput
835 | hir::LangItem::TryTraitFromResidual
836 | hir::LangItem::TryTraitBranch => Some(ObligationCauseCode::QuestionMark),
839 if let Some(code) = code {
840 self.add_required_obligations_with_code(span, def_id, substs, move |_, _| code.clone());
842 self.add_required_obligations_for_hir(span, def_id, substs, hir_id);
845 (Res::Def(def_kind, def_id), ty)
848 /// Resolves an associated value path into a base type and associated constant, or method
849 /// resolution. The newly resolved definition is written into `type_dependent_defs`.
850 pub fn resolve_ty_and_res_fully_qualified_call(
852 qpath: &'tcx QPath<'tcx>,
855 ) -> (Res, Option<Ty<'tcx>>, &'tcx [hir::PathSegment<'tcx>]) {
857 "resolve_ty_and_res_fully_qualified_call: qpath={:?} hir_id={:?} span={:?}",
860 let (ty, qself, item_segment) = match *qpath {
861 QPath::Resolved(ref opt_qself, ref path) => {
864 opt_qself.as_ref().map(|qself| self.to_ty(qself)),
868 QPath::TypeRelative(ref qself, ref segment) => {
869 // Don't use `self.to_ty`, since this will register a WF obligation.
870 // If we're trying to call a non-existent method on a trait
871 // (e.g. `MyTrait::missing_method`), then resolution will
872 // give us a `QPath::TypeRelative` with a trait object as
873 // `qself`. In that case, we want to avoid registering a WF obligation
874 // for `dyn MyTrait`, since we don't actually need the trait
875 // to be object-safe.
876 // We manually call `register_wf_obligation` in the success path
878 (<dyn AstConv<'_>>::ast_ty_to_ty_in_path(self, qself), qself, segment)
880 QPath::LangItem(..) => {
881 bug!("`resolve_ty_and_res_fully_qualified_call` called on `LangItem`")
884 if let Some(&cached_result) = self.typeck_results.borrow().type_dependent_defs().get(hir_id)
886 self.register_wf_obligation(ty.into(), qself.span, traits::WellFormed(None));
887 // Return directly on cache hit. This is useful to avoid doubly reporting
888 // errors with default match binding modes. See #44614.
889 let def = cached_result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id));
890 return (def, Some(ty), slice::from_ref(&**item_segment));
892 let item_name = item_segment.ident;
894 .resolve_fully_qualified_call(span, item_name, ty, qself.span, hir_id)
896 let result = match error {
897 method::MethodError::PrivateMatch(kind, def_id, _) => Ok((kind, def_id)),
898 _ => Err(ErrorGuaranteed::unchecked_claim_error_was_emitted()),
901 // If we have a path like `MyTrait::missing_method`, then don't register
902 // a WF obligation for `dyn MyTrait` when method lookup fails. Otherwise,
903 // register a WF obligation so that we can detect any additional
904 // errors in the self type.
905 if !(matches!(error, method::MethodError::NoMatch(_)) && ty.is_trait()) {
906 self.register_wf_obligation(ty.into(), qself.span, traits::WellFormed(None));
908 if item_name.name != kw::Empty {
909 if let Some(mut e) = self.report_method_error(
913 SelfSource::QPath(qself),
924 self.register_wf_obligation(ty.into(), qself.span, traits::WellFormed(None));
927 // Write back the new resolution.
928 self.write_resolution(hir_id, result);
930 result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
932 slice::from_ref(&**item_segment),
936 /// Given a function `Node`, return its `FnDecl` if it exists, or `None` otherwise.
937 pub(in super::super) fn get_node_fn_decl(
940 ) -> Option<(&'tcx hir::FnDecl<'tcx>, Ident, bool)> {
942 Node::Item(&hir::Item { ident, kind: hir::ItemKind::Fn(ref sig, ..), .. }) => {
943 // This is less than ideal, it will not suggest a return type span on any
944 // method called `main`, regardless of whether it is actually the entry point,
945 // but it will still present it as the reason for the expected type.
946 Some((&sig.decl, ident, ident.name != sym::main))
948 Node::TraitItem(&hir::TraitItem {
950 kind: hir::TraitItemKind::Fn(ref sig, ..),
952 }) => Some((&sig.decl, ident, true)),
953 Node::ImplItem(&hir::ImplItem {
955 kind: hir::ImplItemKind::Fn(ref sig, ..),
957 }) => Some((&sig.decl, ident, false)),
962 /// Given a `HirId`, return the `FnDecl` of the method it is enclosed by and whether a
963 /// suggestion can be made, `None` otherwise.
964 pub fn get_fn_decl(&self, blk_id: hir::HirId) -> Option<(&'tcx hir::FnDecl<'tcx>, bool)> {
965 // Get enclosing Fn, if it is a function or a trait method, unless there's a `loop` or
966 // `while` before reaching it, as block tail returns are not available in them.
967 self.tcx.hir().get_return_block(blk_id).and_then(|blk_id| {
968 let parent = self.tcx.hir().get(blk_id);
969 self.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main))
973 pub(in super::super) fn note_internal_mutation_in_method(
975 err: &mut Diagnostic,
976 expr: &hir::Expr<'_>,
980 if found != self.tcx.types.unit {
983 if let ExprKind::MethodCall(path_segment, rcvr, ..) = expr.kind {
987 .expr_ty_adjusted_opt(rcvr)
988 .map_or(true, |ty| expected.peel_refs() != ty.peel_refs())
992 let mut sp = MultiSpan::from_span(path_segment.ident.span);
994 path_segment.ident.span,
996 "this call modifies {} in-place",
998 ExprKind::Path(QPath::Resolved(
1000 hir::Path { segments: [segment], .. },
1001 )) => format!("`{}`", segment.ident),
1002 _ => "its receiver".to_string(),
1008 "you probably want to use this value after calling the method...",
1012 &format!("method `{}` modifies its receiver in-place", path_segment.ident),
1014 err.note(&format!("...instead of the `()` output of method `{}`", path_segment.ident));
1018 pub(in super::super) fn note_need_for_fn_pointer(
1020 err: &mut Diagnostic,
1024 let (sig, did, substs) = match (&expected.kind(), &found.kind()) {
1025 (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => {
1026 let sig1 = self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1);
1027 let sig2 = self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2);
1032 "different `fn` items always have unique types, even if their signatures are \
1035 (sig1, *did1, substs1)
1037 (ty::FnDef(did, substs), ty::FnPtr(sig2)) => {
1038 let sig1 = self.tcx.bound_fn_sig(*did).subst(self.tcx, substs);
1042 (sig1, *did, substs)
1046 err.help(&format!("change the expected type to be function pointer `{}`", sig));
1048 "if the expected type is due to type inference, cast the expected `fn` to a function \
1049 pointer: `{} as {}`",
1050 self.tcx.def_path_str_with_substs(did, substs),
1055 // Instantiates the given path, which must refer to an item with the given
1056 // number of type parameters and type.
1057 #[instrument(skip(self, span), level = "debug")]
1058 pub fn instantiate_value_path(
1060 segments: &[hir::PathSegment<'_>],
1061 self_ty: Option<Ty<'tcx>>,
1065 ) -> (Ty<'tcx>, Res) {
1068 let path_segs = match res {
1069 Res::Local(_) | Res::SelfCtor(_) => vec![],
1070 Res::Def(kind, def_id) => <dyn AstConv<'_>>::def_ids_for_value_path_segments(
1071 self, segments, self_ty, kind, def_id,
1073 _ => bug!("instantiate_value_path on {:?}", res),
1076 let mut user_self_ty = None;
1077 let mut is_alias_variant_ctor = false;
1079 Res::Def(DefKind::Ctor(CtorOf::Variant, _), _)
1080 if let Some(self_ty) = self_ty =>
1082 let adt_def = self_ty.ty_adt_def().unwrap();
1083 user_self_ty = Some(UserSelfTy { impl_def_id: adt_def.did(), self_ty });
1084 is_alias_variant_ctor = true;
1086 Res::Def(DefKind::AssocFn | DefKind::AssocConst, def_id) => {
1087 let assoc_item = tcx.associated_item(def_id);
1088 let container = assoc_item.container;
1089 let container_id = assoc_item.container_id(tcx);
1090 debug!(?def_id, ?container, ?container_id);
1092 ty::TraitContainer => {
1093 callee::check_legal_trait_for_method_call(tcx, span, None, span, container_id)
1095 ty::ImplContainer => {
1096 if segments.len() == 1 {
1097 // `<T>::assoc` will end up here, and so
1098 // can `T::assoc`. It this came from an
1099 // inherent impl, we need to record the
1100 // `T` for posterity (see `UserSelfTy` for
1102 let self_ty = self_ty.expect("UFCS sugared assoc missing Self");
1103 user_self_ty = Some(UserSelfTy { impl_def_id: container_id, self_ty });
1111 // Now that we have categorized what space the parameters for each
1112 // segment belong to, let's sort out the parameters that the user
1113 // provided (if any) into their appropriate spaces. We'll also report
1114 // errors if type parameters are provided in an inappropriate place.
1116 let generic_segs: FxHashSet<_> = path_segs.iter().map(|PathSeg(_, index)| index).collect();
1117 let generics_has_err = <dyn AstConv<'_>>::prohibit_generics(
1119 segments.iter().enumerate().filter_map(|(index, seg)| {
1120 if !generic_segs.contains(&index) || is_alias_variant_ctor {
1129 if let Res::Local(hid) = res {
1130 let ty = self.local_ty(span, hid).decl_ty;
1131 let ty = self.normalize_associated_types_in(span, ty);
1132 self.write_ty(hir_id, ty);
1136 if generics_has_err {
1137 // Don't try to infer type parameters when prohibited generic arguments were given.
1138 user_self_ty = None;
1141 // Now we have to compare the types that the user *actually*
1142 // provided against the types that were *expected*. If the user
1143 // did not provide any types, then we want to substitute inference
1144 // variables. If the user provided some types, we may still need
1145 // to add defaults. If the user provided *too many* types, that's
1148 let mut infer_args_for_err = FxHashSet::default();
1150 let mut explicit_late_bound = ExplicitLateBound::No;
1151 for &PathSeg(def_id, index) in &path_segs {
1152 let seg = &segments[index];
1153 let generics = tcx.generics_of(def_id);
1155 // Argument-position `impl Trait` is treated as a normal generic
1156 // parameter internally, but we don't allow users to specify the
1157 // parameter's value explicitly, so we have to do some error-
1159 let arg_count = <dyn AstConv<'_>>::check_generic_arg_count_for_call(
1168 if let ExplicitLateBound::Yes = arg_count.explicit_late_bound {
1169 explicit_late_bound = ExplicitLateBound::Yes;
1172 if let Err(GenericArgCountMismatch { reported: Some(_), .. }) = arg_count.correct {
1173 infer_args_for_err.insert(index);
1174 self.set_tainted_by_errors(); // See issue #53251.
1178 let has_self = path_segs
1180 .map(|PathSeg(def_id, _)| tcx.generics_of(*def_id).has_self)
1183 let (res, self_ctor_substs) = if let Res::SelfCtor(impl_def_id) = res {
1184 let ty = self.normalize_ty(span, tcx.at(span).type_of(impl_def_id));
1186 ty::Adt(adt_def, substs) if adt_def.has_ctor() => {
1187 let variant = adt_def.non_enum_variant();
1188 let ctor_def_id = variant.ctor_def_id.unwrap();
1190 Res::Def(DefKind::Ctor(CtorOf::Struct, variant.ctor_kind), ctor_def_id),
1195 let mut err = tcx.sess.struct_span_err(
1197 "the `Self` constructor can only be used with tuple or unit structs",
1199 if let Some(adt_def) = ty.ty_adt_def() {
1200 match adt_def.adt_kind() {
1202 err.help("did you mean to use one of the enum's variants?");
1204 AdtKind::Struct | AdtKind::Union => {
1205 err.span_suggestion(
1207 "use curly brackets",
1208 "Self { /* fields */ }",
1209 Applicability::HasPlaceholders,
1216 return (tcx.ty_error(), res);
1222 let def_id = res.def_id();
1224 // The things we are substituting into the type should not contain
1225 // escaping late-bound regions, and nor should the base type scheme.
1226 let ty = tcx.type_of(def_id);
1228 let arg_count = GenericArgCountResult {
1229 explicit_late_bound,
1230 correct: if infer_args_for_err.is_empty() {
1233 Err(GenericArgCountMismatch::default())
1237 struct CreateCtorSubstsContext<'a, 'tcx> {
1238 fcx: &'a FnCtxt<'a, 'tcx>,
1240 path_segs: &'a [PathSeg],
1241 infer_args_for_err: &'a FxHashSet<usize>,
1242 segments: &'a [hir::PathSegment<'a>],
1244 impl<'tcx, 'a> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for CreateCtorSubstsContext<'a, 'tcx> {
1248 ) -> (Option<&'a hir::GenericArgs<'a>>, bool) {
1249 if let Some(&PathSeg(_, index)) =
1250 self.path_segs.iter().find(|&PathSeg(did, _)| *did == def_id)
1252 // If we've encountered an `impl Trait`-related error, we're just
1253 // going to infer the arguments for better error messages.
1254 if !self.infer_args_for_err.contains(&index) {
1255 // Check whether the user has provided generic arguments.
1256 if let Some(ref data) = self.segments[index].args {
1257 return (Some(data), self.segments[index].infer_args);
1260 return (None, self.segments[index].infer_args);
1268 param: &ty::GenericParamDef,
1269 arg: &GenericArg<'_>,
1270 ) -> ty::GenericArg<'tcx> {
1271 match (¶m.kind, arg) {
1272 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
1273 <dyn AstConv<'_>>::ast_region_to_region(self.fcx, lt, Some(param)).into()
1275 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
1276 self.fcx.to_ty(ty).into()
1278 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => {
1279 self.fcx.const_arg_to_const(&ct.value, param.def_id).into()
1281 (GenericParamDefKind::Type { .. }, GenericArg::Infer(inf)) => {
1282 self.fcx.ty_infer(Some(param), inf.span).into()
1284 (GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
1285 let tcx = self.fcx.tcx();
1286 self.fcx.ct_infer(tcx.type_of(param.def_id), Some(param), inf.span).into()
1288 _ => unreachable!(),
1294 substs: Option<&[ty::GenericArg<'tcx>]>,
1295 param: &ty::GenericParamDef,
1297 ) -> ty::GenericArg<'tcx> {
1298 let tcx = self.fcx.tcx();
1300 GenericParamDefKind::Lifetime => {
1301 self.fcx.re_infer(Some(param), self.span).unwrap().into()
1303 GenericParamDefKind::Type { has_default, .. } => {
1304 if !infer_args && has_default {
1305 // If we have a default, then we it doesn't matter that we're not
1306 // inferring the type arguments: we provide the default where any
1308 let default = tcx.bound_type_of(param.def_id);
1310 .normalize_ty(self.span, default.subst(tcx, substs.unwrap()))
1313 // If no type arguments were provided, we have to infer them.
1314 // This case also occurs as a result of some malformed input, e.g.
1315 // a lifetime argument being given instead of a type parameter.
1316 // Using inference instead of `Error` gives better error messages.
1317 self.fcx.var_for_def(self.span, param)
1320 GenericParamDefKind::Const { has_default } => {
1321 if !infer_args && has_default {
1322 tcx.bound_const_param_default(param.def_id)
1323 .subst(tcx, substs.unwrap())
1326 self.fcx.var_for_def(self.span, param)
1333 let substs = self_ctor_substs.unwrap_or_else(|| {
1334 <dyn AstConv<'_>>::create_substs_for_generic_args(
1341 &mut CreateCtorSubstsContext {
1344 path_segs: &path_segs,
1345 infer_args_for_err: &infer_args_for_err,
1350 assert!(!substs.has_escaping_bound_vars());
1351 assert!(!ty.has_escaping_bound_vars());
1353 // First, store the "user substs" for later.
1354 self.write_user_type_annotation_from_substs(hir_id, def_id, substs, user_self_ty);
1356 self.add_required_obligations_for_hir(span, def_id, &substs, hir_id);
1358 // Substitute the values for the type parameters into the type of
1359 // the referenced item.
1360 let ty_substituted = self.instantiate_type_scheme(span, &substs, ty);
1362 if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty {
1363 // In the case of `Foo<T>::method` and `<Foo<T>>::method`, if `method`
1364 // is inherent, there is no `Self` parameter; instead, the impl needs
1365 // type parameters, which we can infer by unifying the provided `Self`
1366 // with the substituted impl type.
1367 // This also occurs for an enum variant on a type alias.
1368 let ty = tcx.type_of(impl_def_id);
1370 let impl_ty = self.instantiate_type_scheme(span, &substs, ty);
1371 match self.at(&self.misc(span), self.param_env).eq(impl_ty, self_ty) {
1372 Ok(ok) => self.register_infer_ok_obligations(ok),
1374 self.tcx.sess.delay_span_bug(
1377 "instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?",
1386 debug!("instantiate_value_path: type of {:?} is {:?}", hir_id, ty_substituted);
1387 self.write_substs(hir_id, substs);
1389 (ty_substituted, res)
1392 /// Add all the obligations that are required, substituting and normalized appropriately.
1393 pub(crate) fn add_required_obligations_for_hir(
1397 substs: SubstsRef<'tcx>,
1400 self.add_required_obligations_with_code(span, def_id, substs, |idx, span| {
1401 if span.is_dummy() {
1402 ObligationCauseCode::ExprItemObligation(def_id, hir_id, idx)
1404 ObligationCauseCode::ExprBindingObligation(def_id, span, hir_id, idx)
1409 #[instrument(level = "debug", skip(self, code, span, substs))]
1410 fn add_required_obligations_with_code(
1414 substs: SubstsRef<'tcx>,
1415 code: impl Fn(usize, Span) -> ObligationCauseCode<'tcx>,
1417 let param_env = self.param_env;
1419 let remap = match self.tcx.def_kind(def_id) {
1420 // Associated consts have `Self: ~const Trait` bounds that should be satisfiable when
1421 // `Self: Trait` is satisfied because it does not matter whether the impl is `const`.
1422 // Therefore we have to remap the param env here to be non-const.
1423 hir::def::DefKind::AssocConst => true,
1424 hir::def::DefKind::AssocFn
1425 if self.tcx.def_kind(self.tcx.parent(def_id)) == hir::def::DefKind::Trait =>
1427 // N.B.: All callsites to this function involve checking a path expression.
1429 // When instantiating a trait method as a function item, it does not actually matter whether
1430 // the trait is `const` or not, or whether `where T: ~const Tr` needs to be satisfied as
1431 // `const`. If we were to introduce instantiating trait methods as `const fn`s, we would
1432 // check that after this, either via a bound `where F: ~const FnOnce` or when coercing to a
1433 // `const fn` pointer.
1435 // FIXME(fee1-dead) FIXME(const_trait_impl): update this doc when trait methods can satisfy
1436 // `~const FnOnce` or can be coerced to `const fn` pointer.
1441 let (bounds, _) = self.instantiate_bounds(span, def_id, &substs);
1443 for mut obligation in traits::predicates_for_generics(
1444 |idx, predicate_span| {
1445 traits::ObligationCause::new(span, self.body_id, code(idx, predicate_span))
1451 obligation = obligation.without_const(self.tcx);
1453 self.register_predicate(obligation);
1457 /// Resolves `typ` by a single level if `typ` is a type variable.
1458 /// If no resolution is possible, then an error is reported.
1459 /// Numeric inference variables may be left unresolved.
1460 pub fn structurally_resolved_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
1461 let ty = self.resolve_vars_with_obligations(ty);
1462 if !ty.is_ty_var() {
1465 if !self.is_tainted_by_errors() {
1466 self.emit_inference_failure_err((**self).body_id, sp, ty.into(), E0282, true)
1469 let err = self.tcx.ty_error();
1470 self.demand_suptype(sp, err, ty);
1475 pub(in super::super) fn with_breakable_ctxt<F: FnOnce() -> R, R>(
1478 ctxt: BreakableCtxt<'tcx>,
1480 ) -> (BreakableCtxt<'tcx>, R) {
1483 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
1484 index = enclosing_breakables.stack.len();
1485 enclosing_breakables.by_id.insert(id, index);
1486 enclosing_breakables.stack.push(ctxt);
1490 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
1491 debug_assert!(enclosing_breakables.stack.len() == index + 1);
1492 enclosing_breakables.by_id.remove(&id).expect("missing breakable context");
1493 enclosing_breakables.stack.pop().expect("missing breakable context")
1498 /// Instantiate a QueryResponse in a probe context, without a
1499 /// good ObligationCause.
1500 pub(in super::super) fn probe_instantiate_query_response(
1503 original_values: &OriginalQueryValues<'tcx>,
1504 query_result: &Canonical<'tcx, QueryResponse<'tcx, Ty<'tcx>>>,
1505 ) -> InferResult<'tcx, Ty<'tcx>> {
1506 self.instantiate_query_response_and_region_obligations(
1507 &traits::ObligationCause::misc(span, self.body_id),
1514 /// Returns `true` if an expression is contained inside the LHS of an assignment expression.
1515 pub(in super::super) fn expr_in_place(&self, mut expr_id: hir::HirId) -> bool {
1516 let mut contained_in_place = false;
1518 while let hir::Node::Expr(parent_expr) =
1519 self.tcx.hir().get(self.tcx.hir().get_parent_node(expr_id))
1521 match &parent_expr.kind {
1522 hir::ExprKind::Assign(lhs, ..) | hir::ExprKind::AssignOp(_, lhs, ..) => {
1523 if lhs.hir_id == expr_id {
1524 contained_in_place = true;
1530 expr_id = parent_expr.hir_id;