1
Fork 0

Remove glob imports for ObligationCauseCode

This commit is contained in:
Michael Goulet 2024-05-09 20:05:59 -04:00
parent 04c049498d
commit 4bde8a8f4b
24 changed files with 279 additions and 178 deletions

View file

@ -2012,9 +2012,9 @@ pub(super) fn check_type_bounds<'tcx>(
); );
let mk_cause = |span: Span| { let mk_cause = |span: Span| {
let code = if span.is_dummy() { let code = if span.is_dummy() {
traits::ItemObligation(trait_ty.def_id) ObligationCauseCode::ItemObligation(trait_ty.def_id)
} else { } else {
traits::BindingObligation(trait_ty.def_id, span) ObligationCauseCode::BindingObligation(trait_ty.def_id, span)
}; };
ObligationCause::new(impl_ty_span, impl_ty_def_id, code) ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
}; };
@ -2251,7 +2251,8 @@ fn try_report_async_mismatch<'tcx>(
}; };
for error in errors { for error in errors {
if let traits::BindingObligation(def_id, _) = *error.root_obligation.cause.code() if let ObligationCauseCode::BindingObligation(def_id, _) =
*error.root_obligation.cause.code()
&& def_id == async_future_def_id && def_id == async_future_def_id
&& let Some(proj) = error.root_obligation.predicate.to_opt_poly_projection_pred() && let Some(proj) = error.root_obligation.predicate.to_opt_poly_projection_pred()
&& let Some(proj) = proj.no_bound_vars() && let Some(proj) = proj.no_bound_vars()

View file

@ -5,6 +5,7 @@ use rustc_data_structures::fx::FxHashSet;
use rustc_errors::{codes::*, struct_span_code_err, ErrorGuaranteed}; use rustc_errors::{codes::*, struct_span_code_err, ErrorGuaranteed};
use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::outlives::env::OutlivesEnvironment;
use rustc_infer::infer::{RegionResolutionError, TyCtxtInferExt}; use rustc_infer::infer::{RegionResolutionError, TyCtxtInferExt};
use rustc_infer::traits::ObligationCauseCode;
use rustc_middle::ty::util::CheckRegions; use rustc_middle::ty::util::CheckRegions;
use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::GenericArgsRef;
use rustc_middle::ty::{self, TyCtxt}; use rustc_middle::ty::{self, TyCtxt};
@ -139,7 +140,7 @@ fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>(
for (pred, span) in tcx.predicates_of(drop_impl_def_id).instantiate_identity(tcx) { for (pred, span) in tcx.predicates_of(drop_impl_def_id).instantiate_identity(tcx) {
let normalize_cause = traits::ObligationCause::misc(span, adt_def_id); let normalize_cause = traits::ObligationCause::misc(span, adt_def_id);
let pred = ocx.normalize(&normalize_cause, param_env, pred); let pred = ocx.normalize(&normalize_cause, param_env, pred);
let cause = traits::ObligationCause::new(span, adt_def_id, traits::DropImpl); let cause = traits::ObligationCause::new(span, adt_def_id, ObligationCauseCode::DropImpl);
ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, pred)); ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, pred));
} }

View file

@ -1136,7 +1136,7 @@ fn check_type_defn<'tcx>(
traits::ObligationCause::new( traits::ObligationCause::new(
hir_ty.span, hir_ty.span,
wfcx.body_def_id, wfcx.body_def_id,
traits::FieldSized { ObligationCauseCode::FieldSized {
adt_kind: match &item.kind { adt_kind: match &item.kind {
ItemKind::Struct(..) => AdtKind::Struct, ItemKind::Struct(..) => AdtKind::Struct,
ItemKind::Union(..) => AdtKind::Union, ItemKind::Union(..) => AdtKind::Union,
@ -1161,7 +1161,7 @@ fn check_type_defn<'tcx>(
let cause = traits::ObligationCause::new( let cause = traits::ObligationCause::new(
tcx.def_span(discr_def_id), tcx.def_span(discr_def_id),
wfcx.body_def_id, wfcx.body_def_id,
traits::MiscObligation, ObligationCauseCode::MiscObligation,
); );
wfcx.register_obligation(traits::Obligation::new( wfcx.register_obligation(traits::Obligation::new(
tcx, tcx,
@ -1278,7 +1278,11 @@ fn check_item_type(
wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(item_id)), item_ty.into()); wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
if forbid_unsized { if forbid_unsized {
wfcx.register_bound( wfcx.register_bound(
traits::ObligationCause::new(ty_span, wfcx.body_def_id, traits::WellFormed(None)), traits::ObligationCause::new(
ty_span,
wfcx.body_def_id,
ObligationCauseCode::WellFormed(None),
),
wfcx.param_env, wfcx.param_env,
item_ty, item_ty,
tcx.require_lang_item(LangItem::Sized, None), tcx.require_lang_item(LangItem::Sized, None),
@ -1293,7 +1297,11 @@ fn check_item_type(
if should_check_for_sync { if should_check_for_sync {
wfcx.register_bound( wfcx.register_bound(
traits::ObligationCause::new(ty_span, wfcx.body_def_id, traits::SharedStatic), traits::ObligationCause::new(
ty_span,
wfcx.body_def_id,
ObligationCauseCode::SharedStatic,
),
wfcx.param_env, wfcx.param_env,
item_ty, item_ty,
tcx.require_lang_item(LangItem::Sync, Some(ty_span)), tcx.require_lang_item(LangItem::Sync, Some(ty_span)),
@ -1542,7 +1550,7 @@ fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id
let cause = traits::ObligationCause::new( let cause = traits::ObligationCause::new(
sp, sp,
wfcx.body_def_id, wfcx.body_def_id,
traits::ItemObligation(def_id.to_def_id()), ObligationCauseCode::ItemObligation(def_id.to_def_id()),
); );
traits::Obligation::new(tcx, cause, wfcx.param_env, pred) traits::Obligation::new(tcx, cause, wfcx.param_env, pred)
}); });
@ -1982,7 +1990,11 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
let obligation = traits::Obligation::new( let obligation = traits::Obligation::new(
tcx, tcx,
traits::ObligationCause::new(span, self.body_def_id, traits::TrivialBound), traits::ObligationCause::new(
span,
self.body_def_id,
ObligationCauseCode::TrivialBound,
),
empty_env, empty_env,
pred, pred,
); );

View file

@ -9,6 +9,7 @@ use rustc_hir as hir;
use rustc_hir::def::{self, CtorKind, Namespace, Res}; use rustc_hir::def::{self, CtorKind, Namespace, Res};
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
use rustc_hir_analysis::autoderef::Autoderef; use rustc_hir_analysis::autoderef::Autoderef;
use rustc_infer::traits::ObligationCauseCode;
use rustc_infer::{ use rustc_infer::{
infer, infer,
traits::{self, Obligation, ObligationCause}, traits::{self, Obligation, ObligationCause},
@ -117,7 +118,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}; };
// we must check that return type of called functions is WF: // we must check that return type of called functions is WF:
self.register_wf_obligation(output.into(), call_expr.span, traits::WellFormed(None)); self.register_wf_obligation(
output.into(),
call_expr.span,
ObligationCauseCode::WellFormed(None),
);
output output
} }
@ -524,9 +529,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self.register_bound( self.register_bound(
ty, ty,
self.tcx.require_lang_item(hir::LangItem::Tuple, Some(sp)), self.tcx.require_lang_item(hir::LangItem::Tuple, Some(sp)),
traits::ObligationCause::new(sp, self.body_id, traits::RustCall), traits::ObligationCause::new(sp, self.body_id, ObligationCauseCode::RustCall),
); );
self.require_type_is_sized(ty, sp, traits::RustCall); self.require_type_is_sized(ty, sp, ObligationCauseCode::RustCall);
} else { } else {
self.dcx().emit_err(errors::RustCallIncorrectArgs { span: sp }); self.dcx().emit_err(errors::RustCallIncorrectArgs { span: sp });
} }

View file

@ -14,7 +14,6 @@ use rustc_middle::ty::{self, Binder, Ty, TyCtxt};
use rustc_span::def_id::LocalDefId; use rustc_span::def_id::LocalDefId;
use rustc_span::symbol::sym; use rustc_span::symbol::sym;
use rustc_target::spec::abi::Abi; use rustc_target::spec::abi::Abi;
use rustc_trait_selection::traits;
use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode}; use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode};
/// Helper used for fns and closures. Does the grungy work of checking a function /// Helper used for fns and closures. Does the grungy work of checking a function
@ -76,7 +75,7 @@ pub(super) fn check_fn<'a, 'tcx>(
fcx.register_wf_obligation( fcx.register_wf_obligation(
param_ty.into(), param_ty.into(),
param.span, param.span,
traits::WellFormed(Some(WellFormedLoc::Param { ObligationCauseCode::WellFormed(Some(WellFormedLoc::Param {
function: fn_def_id, function: fn_def_id,
param_idx: idx, param_idx: idx,
})), })),
@ -101,7 +100,7 @@ pub(super) fn check_fn<'a, 'tcx>(
param.pat.span, param.pat.span,
// ty.span == binding_span iff this is a closure parameter with no type ascription, // ty.span == binding_span iff this is a closure parameter with no type ascription,
// or if it's an implicit `self` parameter // or if it's an implicit `self` parameter
traits::SizedArgumentType( ObligationCauseCode::SizedArgumentType(
if ty_span == Some(param.span) && tcx.is_closure_like(fn_def_id.into()) { if ty_span == Some(param.span) && tcx.is_closure_like(fn_def_id.into()) {
None None
} else { } else {
@ -121,10 +120,18 @@ pub(super) fn check_fn<'a, 'tcx>(
hir::FnRetTy::Return(ty) => ty.span, hir::FnRetTy::Return(ty) => ty.span,
}; };
fcx.require_type_is_sized(declared_ret_ty, return_or_body_span, traits::SizedReturnType); fcx.require_type_is_sized(
declared_ret_ty,
return_or_body_span,
ObligationCauseCode::SizedReturnType,
);
// We checked the root's signature during wfcheck, but not the child. // We checked the root's signature during wfcheck, but not the child.
if fcx.tcx.is_typeck_child(fn_def_id.to_def_id()) { if fcx.tcx.is_typeck_child(fn_def_id.to_def_id()) {
fcx.require_type_is_sized(declared_ret_ty, return_or_body_span, traits::WellFormed(None)); fcx.require_type_is_sized(
declared_ret_ty,
return_or_body_span,
ObligationCauseCode::WellFormed(None),
);
} }
fcx.is_whole_body.set(true); fcx.is_whole_body.set(true);

View file

@ -8,6 +8,7 @@ use rustc_hir::lang_items::LangItem;
use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer; use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes}; use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes};
use rustc_infer::infer::{InferOk, InferResult}; use rustc_infer::infer::{InferOk, InferResult};
use rustc_infer::traits::ObligationCauseCode;
use rustc_macros::{TypeFoldable, TypeVisitable}; use rustc_macros::{TypeFoldable, TypeVisitable};
use rustc_middle::ty::visit::{TypeVisitable, TypeVisitableExt}; use rustc_middle::ty::visit::{TypeVisitable, TypeVisitableExt};
use rustc_middle::ty::GenericArgs; use rustc_middle::ty::GenericArgs;
@ -119,7 +120,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _) hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)
| hir::CoroutineKind::Coroutine(_) => { | hir::CoroutineKind::Coroutine(_) => {
let yield_ty = self.next_ty_var(expr_span); let yield_ty = self.next_ty_var(expr_span);
self.require_type_is_sized(yield_ty, expr_span, traits::SizedYieldType); self.require_type_is_sized(
yield_ty,
expr_span,
ObligationCauseCode::SizedYieldType,
);
yield_ty yield_ty
} }
// HACK(-Ztrait-solver=next): In the *old* trait solver, we must eagerly // HACK(-Ztrait-solver=next): In the *old* trait solver, we must eagerly
@ -128,7 +133,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// not a problem. // not a problem.
hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _) => { hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _) => {
let yield_ty = self.next_ty_var(expr_span); let yield_ty = self.next_ty_var(expr_span);
self.require_type_is_sized(yield_ty, expr_span, traits::SizedYieldType); self.require_type_is_sized(
yield_ty,
expr_span,
ObligationCauseCode::SizedYieldType,
);
Ty::new_adt( Ty::new_adt(
tcx, tcx,

View file

@ -573,7 +573,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self.require_type_is_sized_deferred( self.require_type_is_sized_deferred(
input, input,
span, span,
traits::SizedArgumentType(None), ObligationCauseCode::SizedArgumentType(None),
); );
} }
} }
@ -591,7 +591,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self.require_type_is_sized_deferred( self.require_type_is_sized_deferred(
output, output,
call.map_or(expr.span, |e| e.span), call.map_or(expr.span, |e| e.span),
traits::SizedCallReturnType, ObligationCauseCode::SizedCallReturnType,
); );
} }
@ -1249,7 +1249,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} }
}); });
self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized); self.require_type_is_sized(lhs_ty, lhs.span, ObligationCauseCode::AssignmentLhsSized);
if let Err(guar) = (lhs_ty, rhs_ty).error_reported() { if let Err(guar) = (lhs_ty, rhs_ty).error_reported() {
Ty::new_error(self.tcx, guar) Ty::new_error(self.tcx, guar)
@ -1471,7 +1471,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
crate::GatherLocalsVisitor::new(&fcx).visit_body(body); crate::GatherLocalsVisitor::new(&fcx).visit_body(body);
let ty = fcx.check_expr_with_expectation(body.value, expected); let ty = fcx.check_expr_with_expectation(body.value, expected);
fcx.require_type_is_sized(ty, body.value.span, traits::ConstSized); fcx.require_type_is_sized(ty, body.value.span, ObligationCauseCode::ConstSized);
fcx.write_ty(block.hir_id, ty); fcx.write_ty(block.hir_id, ty);
ty ty
} }
@ -1517,7 +1517,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let ty = Ty::new_array_with_const_len(tcx, t, count); let ty = Ty::new_array_with_const_len(tcx, t, count);
self.register_wf_obligation(ty.into(), expr.span, traits::WellFormed(None)); self.register_wf_obligation(ty.into(), expr.span, ObligationCauseCode::WellFormed(None));
ty ty
} }
@ -1607,7 +1607,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if let Err(guar) = tuple.error_reported() { if let Err(guar) = tuple.error_reported() {
Ty::new_error(self.tcx, guar) Ty::new_error(self.tcx, guar)
} else { } else {
self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized); self.require_type_is_sized(
tuple,
expr.span,
ObligationCauseCode::TupleInitializerSized,
);
tuple tuple
} }
} }
@ -1646,7 +1650,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
base_expr, base_expr,
); );
self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized); self.require_type_is_sized(adt_ty, expr.span, ObligationCauseCode::StructInitializerSized);
adt_ty adt_ty
} }
@ -3079,7 +3083,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
polarity: ty::PredicatePolarity::Positive, polarity: ty::PredicatePolarity::Positive,
}), }),
|derived| { |derived| {
traits::ImplDerivedObligation(Box::new( ObligationCauseCode::ImplDerivedObligation(Box::new(
traits::ImplDerivedObligationCause { traits::ImplDerivedObligationCause {
derived, derived,
impl_or_alias_def_id: impl_def_id, impl_or_alias_def_id: impl_def_id,
@ -3177,7 +3181,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn check_expr_asm_operand(&self, expr: &'tcx hir::Expr<'tcx>, is_input: bool) { fn check_expr_asm_operand(&self, expr: &'tcx hir::Expr<'tcx>, is_input: bool) {
let needs = if is_input { Needs::None } else { Needs::MutPlace }; let needs = if is_input { Needs::None } else { Needs::MutPlace };
let ty = self.check_expr_with_needs(expr, needs); let ty = self.check_expr_with_needs(expr, needs);
self.require_type_is_sized(ty, expr.span, traits::InlineAsmSized); self.require_type_is_sized(ty, expr.span, ObligationCauseCode::InlineAsmSized);
if !is_input && !expr.is_syntactic_place_expr() { if !is_input && !expr.is_syntactic_place_expr() {
self.dcx() self.dcx()
@ -3348,7 +3352,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let field_ty = self.field_ty(expr.span, field, args); let field_ty = self.field_ty(expr.span, field, args);
// FIXME: DSTs with static alignment should be allowed // FIXME: DSTs with static alignment should be allowed
self.require_type_is_sized(field_ty, expr.span, traits::MiscObligation); self.require_type_is_sized(
field_ty,
expr.span,
ObligationCauseCode::MiscObligation,
);
if field.vis.is_accessible_from(sub_def_scope, self.tcx) { if field.vis.is_accessible_from(sub_def_scope, self.tcx) {
self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None); self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
@ -3376,7 +3384,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let field_ty = self.field_ty(expr.span, field, args); let field_ty = self.field_ty(expr.span, field, args);
// FIXME: DSTs with static alignment should be allowed // FIXME: DSTs with static alignment should be allowed
self.require_type_is_sized(field_ty, expr.span, traits::MiscObligation); self.require_type_is_sized(
field_ty,
expr.span,
ObligationCauseCode::MiscObligation,
);
if field.vis.is_accessible_from(def_scope, self.tcx) { if field.vis.is_accessible_from(def_scope, self.tcx) {
self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None); self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
@ -3397,7 +3409,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&& field.name == sym::integer(index) && field.name == sym::integer(index)
{ {
for ty in tys.iter().take(index + 1) { for ty in tys.iter().take(index + 1) {
self.require_type_is_sized(ty, expr.span, traits::MiscObligation); self.require_type_is_sized(
ty,
expr.span,
ObligationCauseCode::MiscObligation,
);
} }
if let Some(&field_ty) = tys.get(index) { if let Some(&field_ty) = tys.get(index) {
field_indices.push((FIRST_VARIANT, index.into())); field_indices.push((FIRST_VARIANT, index.into()));

View file

@ -409,7 +409,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> LoweredTy<'tcx> { pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> LoweredTy<'tcx> {
let ty = self.lowerer().lower_ty(hir_ty); let ty = self.lowerer().lower_ty(hir_ty);
self.register_wf_obligation(ty.into(), hir_ty.span, traits::WellFormed(None)); self.register_wf_obligation(ty.into(), hir_ty.span, ObligationCauseCode::WellFormed(None));
LoweredTy::from_raw(self, hir_ty.span, ty) LoweredTy::from_raw(self, hir_ty.span, ty)
} }
@ -520,7 +520,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
for arg in args.iter().filter(|arg| { for arg in args.iter().filter(|arg| {
matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..)) matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
}) { }) {
self.register_wf_obligation(arg, expr.span, traits::WellFormed(None)); self.register_wf_obligation(arg, expr.span, ObligationCauseCode::WellFormed(None));
} }
} }
@ -775,7 +775,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}; };
if let Some(&cached_result) = self.typeck_results.borrow().type_dependent_defs().get(hir_id) if let Some(&cached_result) = self.typeck_results.borrow().type_dependent_defs().get(hir_id)
{ {
self.register_wf_obligation(ty.raw.into(), qself.span, traits::WellFormed(None)); self.register_wf_obligation(
ty.raw.into(),
qself.span,
ObligationCauseCode::WellFormed(None),
);
// Return directly on cache hit. This is useful to avoid doubly reporting // Return directly on cache hit. This is useful to avoid doubly reporting
// errors with default match binding modes. See #44614. // errors with default match binding modes. See #44614.
let def = cached_result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)); let def = cached_result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id));
@ -814,7 +818,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self.register_wf_obligation( self.register_wf_obligation(
ty.raw.into(), ty.raw.into(),
qself.span, qself.span,
traits::WellFormed(None), ObligationCauseCode::WellFormed(None),
); );
} }
@ -848,7 +852,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}); });
if result.is_ok() { if result.is_ok() {
self.register_wf_obligation(ty.raw.into(), qself.span, traits::WellFormed(None)); self.register_wf_obligation(
ty.raw.into(),
qself.span,
ObligationCauseCode::WellFormed(None),
);
} }
// Write back the new resolution. // Write back the new resolution.

View file

@ -14,8 +14,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&self, &self,
error: &mut traits::FulfillmentError<'tcx>, error: &mut traits::FulfillmentError<'tcx>,
) -> bool { ) -> bool {
let (traits::ExprItemObligation(def_id, hir_id, idx) let (ObligationCauseCode::ExprItemObligation(def_id, hir_id, idx)
| traits::ExprBindingObligation(def_id, _, hir_id, idx)) = | ObligationCauseCode::ExprBindingObligation(def_id, _, hir_id, idx)) =
*error.obligation.cause.code().peel_derives() *error.obligation.cause.code().peel_derives()
else { else {
return false; return false;

View file

@ -203,7 +203,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// All the input types from the fn signature must outlive the call // All the input types from the fn signature must outlive the call
// so as to validate implied bounds. // so as to validate implied bounds.
for (&fn_input_ty, arg_expr) in iter::zip(formal_input_tys, provided_args) { for (&fn_input_ty, arg_expr) in iter::zip(formal_input_tys, provided_args) {
self.register_wf_obligation(fn_input_ty.into(), arg_expr.span, traits::MiscObligation); self.register_wf_obligation(
fn_input_ty.into(),
arg_expr.span,
ObligationCauseCode::MiscObligation,
);
} }
let mut err_code = E0061; let mut err_code = E0061;

View file

@ -2,11 +2,11 @@ use crate::FnCtxt;
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::intravisit::{self, Visitor};
use rustc_hir::{HirId, PatKind}; use rustc_hir::{HirId, PatKind};
use rustc_infer::traits::ObligationCauseCode;
use rustc_middle::ty::Ty; use rustc_middle::ty::Ty;
use rustc_middle::ty::UserType; use rustc_middle::ty::UserType;
use rustc_span::def_id::LocalDefId; use rustc_span::def_id::LocalDefId;
use rustc_span::Span; use rustc_span::Span;
use rustc_trait_selection::traits;
/// Provides context for checking patterns in declarations. More specifically this /// Provides context for checking patterns in declarations. More specifically this
/// allows us to infer array types if the pattern is irrefutable and allows us to infer /// allows us to infer array types if the pattern is irrefutable and allows us to infer
@ -146,7 +146,7 @@ impl<'a, 'tcx> Visitor<'tcx> for GatherLocalsVisitor<'a, 'tcx> {
p.span, p.span,
// ty_span == ident.span iff this is a closure parameter with no type // ty_span == ident.span iff this is a closure parameter with no type
// ascription, or if it's an implicit `self` parameter // ascription, or if it's an implicit `self` parameter
traits::SizedArgumentType( ObligationCauseCode::SizedArgumentType(
if ty_span == ident.span if ty_span == ident.span
&& self.fcx.tcx.is_closure_like(self.fcx.body_id.into()) && self.fcx.tcx.is_closure_like(self.fcx.body_id.into())
{ {
@ -159,7 +159,11 @@ impl<'a, 'tcx> Visitor<'tcx> for GatherLocalsVisitor<'a, 'tcx> {
} }
} else { } else {
if !self.fcx.tcx.features().unsized_locals { if !self.fcx.tcx.features().unsized_locals {
self.fcx.require_type_is_sized(var_ty, p.span, traits::VariableType(p.hir_id)); self.fcx.require_type_is_sized(
var_ty,
p.span,
ObligationCauseCode::VariableType(p.hir_id),
);
} }
} }

View file

@ -62,7 +62,6 @@ use rustc_hir_analysis::check::check_abi;
use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer; use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
use rustc_infer::traits::{ObligationCauseCode, ObligationInspector, WellFormedLoc}; use rustc_infer::traits::{ObligationCauseCode, ObligationInspector, WellFormedLoc};
use rustc_middle::query::Providers; use rustc_middle::query::Providers;
use rustc_middle::traits;
use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_session::config; use rustc_session::config;
use rustc_span::def_id::LocalDefId; use rustc_span::def_id::LocalDefId;
@ -170,7 +169,7 @@ fn typeck_with_fallback<'tcx>(
let wf_code = ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(def_id))); let wf_code = ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(def_id)));
fcx.register_wf_obligation(expected_type.into(), body.value.span, wf_code); fcx.register_wf_obligation(expected_type.into(), body.value.span, wf_code);
fcx.require_type_is_sized(expected_type, body.value.span, traits::ConstSized); fcx.require_type_is_sized(expected_type, body.value.span, ObligationCauseCode::ConstSized);
// Gather locals in statics (because of block expressions). // Gather locals in statics (because of block expressions).
GatherLocalsVisitor::new(&fcx).visit_body(body); GatherLocalsVisitor::new(&fcx).visit_body(body);

View file

@ -589,7 +589,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> {
// the function type must also be well-formed (this is not // the function type must also be well-formed (this is not
// implied by the args being well-formed because of inherent // implied by the args being well-formed because of inherent
// impls and late-bound regions - see issue #28609). // impls and late-bound regions - see issue #28609).
self.register_wf_obligation(fty.into(), self.span, traits::WellFormed(None)); self.register_wf_obligation(fty.into(), self.span, ObligationCauseCode::WellFormed(None));
} }
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////

View file

@ -15,6 +15,7 @@ use rustc_infer::infer::canonical::{Canonical, QueryResponse};
use rustc_infer::infer::error_reporting::TypeAnnotationNeeded::E0282; use rustc_infer::infer::error_reporting::TypeAnnotationNeeded::E0282;
use rustc_infer::infer::DefineOpaqueTypes; use rustc_infer::infer::DefineOpaqueTypes;
use rustc_infer::infer::{self, InferOk, TyCtxtInferExt}; use rustc_infer::infer::{self, InferOk, TyCtxtInferExt};
use rustc_infer::traits::ObligationCauseCode;
use rustc_middle::middle::stability; use rustc_middle::middle::stability;
use rustc_middle::query::Providers; use rustc_middle::query::Providers;
use rustc_middle::ty::fast_reject::{simplify_type, TreatParams}; use rustc_middle::ty::fast_reject::{simplify_type, TreatParams};
@ -1401,9 +1402,13 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
ocx.register_obligations(traits::predicates_for_generics( ocx.register_obligations(traits::predicates_for_generics(
|idx, span| { |idx, span| {
let code = if span.is_dummy() { let code = if span.is_dummy() {
traits::ExprItemObligation(impl_def_id, self.scope_expr_id, idx) ObligationCauseCode::ExprItemObligation(
impl_def_id,
self.scope_expr_id,
idx,
)
} else { } else {
traits::ExprBindingObligation( ObligationCauseCode::ExprBindingObligation(
impl_def_id, impl_def_id,
span, span,
self.scope_expr_id, self.scope_expr_id,

View file

@ -19,7 +19,7 @@ use rustc_span::symbol::{sym, Ident};
use rustc_span::Span; use rustc_span::Span;
use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::infer::InferCtxtExt;
use rustc_trait_selection::traits::error_reporting::suggestions::TypeErrCtxtExt as _; use rustc_trait_selection::traits::error_reporting::suggestions::TypeErrCtxtExt as _;
use rustc_trait_selection::traits::{self, FulfillmentError, ObligationCtxt}; use rustc_trait_selection::traits::{FulfillmentError, ObligationCtxt};
use rustc_type_ir::TyKind::*; use rustc_type_ir::TyKind::*;
impl<'a, 'tcx> FnCtxt<'a, 'tcx> { impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
@ -884,7 +884,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let input_types = opt_rhs_ty.as_slice(); let input_types = opt_rhs_ty.as_slice();
let cause = self.cause( let cause = self.cause(
span, span,
traits::BinOp { ObligationCauseCode::BinOp {
lhs_hir_id: lhs_expr.hir_id, lhs_hir_id: lhs_expr.hir_id,
rhs_hir_id: opt_rhs_expr.map(|expr| expr.hir_id), rhs_hir_id: opt_rhs_expr.map(|expr| expr.hir_id),
rhs_span: opt_rhs_expr.map(|expr| expr.span), rhs_span: opt_rhs_expr.map(|expr| expr.span),

View file

@ -18,7 +18,7 @@ use rustc_span::source_map::Spanned;
use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::symbol::{kw, sym, Ident};
use rustc_span::{BytePos, Span, DUMMY_SP}; use rustc_span::{BytePos, Span, DUMMY_SP};
use rustc_target::abi::FieldIdx; use rustc_target::abi::FieldIdx;
use rustc_trait_selection::traits::{ObligationCause, Pattern}; use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode};
use ty::VariantDef; use ty::VariantDef;
use std::cmp; use std::cmp;
@ -88,8 +88,11 @@ struct PatInfo<'tcx, 'a> {
impl<'tcx> FnCtxt<'_, 'tcx> { impl<'tcx> FnCtxt<'_, 'tcx> {
fn pattern_cause(&self, ti: TopInfo<'tcx>, cause_span: Span) -> ObligationCause<'tcx> { fn pattern_cause(&self, ti: TopInfo<'tcx>, cause_span: Span) -> ObligationCause<'tcx> {
let code = let code = ObligationCauseCode::Pattern {
Pattern { span: ti.span, root_ty: ti.expected, origin_expr: ti.origin_expr.is_some() }; span: ti.span,
root_ty: ti.expected,
origin_expr: ti.origin_expr.is_some(),
};
self.cause(cause_span, code) self.cause(cause_span, code)
} }

View file

@ -2773,19 +2773,17 @@ pub enum FailureCode {
#[extension(pub trait ObligationCauseExt<'tcx>)] #[extension(pub trait ObligationCauseExt<'tcx>)]
impl<'tcx> ObligationCause<'tcx> { impl<'tcx> ObligationCause<'tcx> {
fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode { fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode {
use self::FailureCode::*;
use crate::traits::ObligationCauseCode::*;
match self.code() { match self.code() {
IfExpressionWithNoElse => Error0317, ObligationCauseCode::IfExpressionWithNoElse => FailureCode::Error0317,
MainFunctionType => Error0580, ObligationCauseCode::MainFunctionType => FailureCode::Error0580,
CompareImplItemObligation { .. } ObligationCauseCode::CompareImplItemObligation { .. }
| MatchExpressionArm(_) | ObligationCauseCode::MatchExpressionArm(_)
| IfExpression { .. } | ObligationCauseCode::IfExpression { .. }
| LetElse | ObligationCauseCode::LetElse
| StartFunctionType | ObligationCauseCode::StartFunctionType
| LangFunctionType(_) | ObligationCauseCode::LangFunctionType(_)
| IntrinsicType | ObligationCauseCode::IntrinsicType
| MethodReceiver => Error0308, | ObligationCauseCode::MethodReceiver => FailureCode::Error0308,
// In the case where we have no more specific thing to // In the case where we have no more specific thing to
// say, also take a look at the error code, maybe we can // say, also take a look at the error code, maybe we can
@ -2794,10 +2792,10 @@ impl<'tcx> ObligationCause<'tcx> {
TypeError::CyclicTy(ty) TypeError::CyclicTy(ty)
if ty.is_closure() || ty.is_coroutine() || ty.is_coroutine_closure() => if ty.is_closure() || ty.is_coroutine() || ty.is_coroutine_closure() =>
{ {
Error0644 FailureCode::Error0644
} }
TypeError::IntrinsicCast => Error0308, TypeError::IntrinsicCast => FailureCode::Error0308,
_ => Error0308, _ => FailureCode::Error0308,
}, },
} }
} }
@ -2807,36 +2805,51 @@ impl<'tcx> ObligationCause<'tcx> {
span: Span, span: Span,
subdiags: Vec<TypeErrorAdditionalDiags>, subdiags: Vec<TypeErrorAdditionalDiags>,
) -> ObligationCauseFailureCode { ) -> ObligationCauseFailureCode {
use crate::traits::ObligationCauseCode::*;
match self.code() { match self.code() {
CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => { ObligationCauseCode::CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => {
ObligationCauseFailureCode::MethodCompat { span, subdiags } ObligationCauseFailureCode::MethodCompat { span, subdiags }
} }
CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => { ObligationCauseCode::CompareImplItemObligation {
ObligationCauseFailureCode::TypeCompat { span, subdiags } kind: ty::AssocKind::Type, ..
} } => ObligationCauseFailureCode::TypeCompat { span, subdiags },
CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => { ObligationCauseCode::CompareImplItemObligation {
ObligationCauseFailureCode::ConstCompat { span, subdiags } kind: ty::AssocKind::Const, ..
} } => ObligationCauseFailureCode::ConstCompat { span, subdiags },
BlockTailExpression(.., hir::MatchSource::TryDesugar(_)) => { ObligationCauseCode::BlockTailExpression(.., hir::MatchSource::TryDesugar(_)) => {
ObligationCauseFailureCode::TryCompat { span, subdiags } ObligationCauseFailureCode::TryCompat { span, subdiags }
} }
MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => match source { ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
source, ..
}) => match source {
hir::MatchSource::TryDesugar(_) => { hir::MatchSource::TryDesugar(_) => {
ObligationCauseFailureCode::TryCompat { span, subdiags } ObligationCauseFailureCode::TryCompat { span, subdiags }
} }
_ => ObligationCauseFailureCode::MatchCompat { span, subdiags }, _ => ObligationCauseFailureCode::MatchCompat { span, subdiags },
}, },
IfExpression { .. } => ObligationCauseFailureCode::IfElseDifferent { span, subdiags }, ObligationCauseCode::IfExpression { .. } => {
IfExpressionWithNoElse => ObligationCauseFailureCode::NoElse { span }, ObligationCauseFailureCode::IfElseDifferent { span, subdiags }
LetElse => ObligationCauseFailureCode::NoDiverge { span, subdiags }, }
MainFunctionType => ObligationCauseFailureCode::FnMainCorrectType { span }, ObligationCauseCode::IfExpressionWithNoElse => {
StartFunctionType => ObligationCauseFailureCode::FnStartCorrectType { span, subdiags }, ObligationCauseFailureCode::NoElse { span }
&LangFunctionType(lang_item_name) => { }
ObligationCauseCode::LetElse => {
ObligationCauseFailureCode::NoDiverge { span, subdiags }
}
ObligationCauseCode::MainFunctionType => {
ObligationCauseFailureCode::FnMainCorrectType { span }
}
ObligationCauseCode::StartFunctionType => {
ObligationCauseFailureCode::FnStartCorrectType { span, subdiags }
}
&ObligationCauseCode::LangFunctionType(lang_item_name) => {
ObligationCauseFailureCode::FnLangCorrectType { span, subdiags, lang_item_name } ObligationCauseFailureCode::FnLangCorrectType { span, subdiags, lang_item_name }
} }
IntrinsicType => ObligationCauseFailureCode::IntrinsicCorrectType { span, subdiags }, ObligationCauseCode::IntrinsicType => {
MethodReceiver => ObligationCauseFailureCode::MethodCorrectType { span, subdiags }, ObligationCauseFailureCode::IntrinsicCorrectType { span, subdiags }
}
ObligationCauseCode::MethodReceiver => {
ObligationCauseFailureCode::MethodCorrectType { span, subdiags }
}
// In the case where we have no more specific thing to // In the case where we have no more specific thing to
// say, also take a look at the error code, maybe we can // say, also take a look at the error code, maybe we can
@ -2856,22 +2869,21 @@ impl<'tcx> ObligationCause<'tcx> {
} }
fn as_requirement_str(&self) -> &'static str { fn as_requirement_str(&self) -> &'static str {
use crate::traits::ObligationCauseCode::*;
match self.code() { match self.code() {
CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => { ObligationCauseCode::CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => {
"method type is compatible with trait" "method type is compatible with trait"
} }
CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => { ObligationCauseCode::CompareImplItemObligation {
"associated type is compatible with trait" kind: ty::AssocKind::Type, ..
} } => "associated type is compatible with trait",
CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => { ObligationCauseCode::CompareImplItemObligation {
"const is compatible with trait" kind: ty::AssocKind::Const, ..
} } => "const is compatible with trait",
MainFunctionType => "`main` function has the correct type", ObligationCauseCode::MainFunctionType => "`main` function has the correct type",
StartFunctionType => "`#[start]` function has the correct type", ObligationCauseCode::StartFunctionType => "`#[start]` function has the correct type",
LangFunctionType(_) => "lang item function has the correct type", ObligationCauseCode::LangFunctionType(_) => "lang item function has the correct type",
IntrinsicType => "intrinsic has the correct type", ObligationCauseCode::IntrinsicType => "intrinsic has the correct type",
MethodReceiver => "method receiver has the correct type", ObligationCauseCode::MethodReceiver => "method receiver has the correct type",
_ => "types are compatible", _ => "types are compatible",
} }
} }
@ -2882,16 +2894,21 @@ pub struct ObligationCauseAsDiagArg<'tcx>(pub ObligationCause<'tcx>);
impl IntoDiagArg for ObligationCauseAsDiagArg<'_> { impl IntoDiagArg for ObligationCauseAsDiagArg<'_> {
fn into_diag_arg(self) -> rustc_errors::DiagArgValue { fn into_diag_arg(self) -> rustc_errors::DiagArgValue {
use crate::traits::ObligationCauseCode::*;
let kind = match self.0.code() { let kind = match self.0.code() {
CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => "method_compat", ObligationCauseCode::CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => {
CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => "type_compat", "method_compat"
CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => "const_compat", }
MainFunctionType => "fn_main_correct_type", ObligationCauseCode::CompareImplItemObligation {
StartFunctionType => "fn_start_correct_type", kind: ty::AssocKind::Type, ..
LangFunctionType(_) => "fn_lang_correct_type", } => "type_compat",
IntrinsicType => "intrinsic_correct_type", ObligationCauseCode::CompareImplItemObligation {
MethodReceiver => "method_correct_type", kind: ty::AssocKind::Const, ..
} => "const_compat",
ObligationCauseCode::MainFunctionType => "fn_main_correct_type",
ObligationCauseCode::StartFunctionType => "fn_start_correct_type",
ObligationCauseCode::LangFunctionType(_) => "fn_lang_correct_type",
ObligationCauseCode::IntrinsicType => "intrinsic_correct_type",
ObligationCauseCode::MethodReceiver => "method_correct_type",
_ => "other", _ => "other",
} }
.into(); .into();

View file

@ -1,7 +1,7 @@
use smallvec::smallvec; use smallvec::smallvec;
use crate::infer::outlives::components::{push_outlives_components, Component}; use crate::infer::outlives::components::{push_outlives_components, Component};
use crate::traits::{self, Obligation, PredicateObligation}; use crate::traits::{self, Obligation, ObligationCauseCode, PredicateObligation};
use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::fx::FxHashSet;
use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt}; use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt};
use rustc_span::symbol::Ident; use rustc_span::symbol::Ident;
@ -129,12 +129,14 @@ impl<'tcx> Elaboratable<'tcx> for PredicateObligation<'tcx> {
index: usize, index: usize,
) -> Self { ) -> Self {
let cause = self.cause.clone().derived_cause(parent_trait_pred, |derived| { let cause = self.cause.clone().derived_cause(parent_trait_pred, |derived| {
traits::ImplDerivedObligation(Box::new(traits::ImplDerivedObligationCause { ObligationCauseCode::ImplDerivedObligation(Box::new(
derived, traits::ImplDerivedObligationCause {
impl_or_alias_def_id: parent_trait_pred.def_id(), derived,
impl_def_predicate_index: Some(index), impl_or_alias_def_id: parent_trait_pred.def_id(),
span, impl_def_predicate_index: Some(index),
})) span,
},
))
}); });
Obligation { Obligation {
cause, cause,

View file

@ -33,8 +33,6 @@ use std::hash::{Hash, Hasher};
pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache}; pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache};
pub use self::ObligationCauseCode::*;
/// Depending on the stage of compilation, we want projection to be /// Depending on the stage of compilation, we want projection to be
/// more or less conservative. /// more or less conservative.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable, Encodable, Decodable)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable, Encodable, Decodable)]
@ -129,7 +127,7 @@ impl<'tcx> ObligationCause<'tcx> {
} }
pub fn misc(span: Span, body_id: LocalDefId) -> ObligationCause<'tcx> { pub fn misc(span: Span, body_id: LocalDefId) -> ObligationCause<'tcx> {
ObligationCause::new(span, body_id, MiscObligation) ObligationCause::new(span, body_id, ObligationCauseCode::MiscObligation)
} }
#[inline(always)] #[inline(always)]
@ -189,8 +187,8 @@ impl<'tcx> ObligationCause<'tcx> {
pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> { pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
match self.code() { match self.code() {
MatchImpl(cause, _) => cause.to_constraint_category(), ObligationCauseCode::MatchImpl(cause, _) => cause.to_constraint_category(),
AscribeUserTypeProvePredicate(predicate_span) => { ObligationCauseCode::AscribeUserTypeProvePredicate(predicate_span) => {
ConstraintCategory::Predicate(*predicate_span) ConstraintCategory::Predicate(*predicate_span)
} }
_ => ConstraintCategory::BoringNoLocation, _ => ConstraintCategory::BoringNoLocation,
@ -540,19 +538,22 @@ impl<'tcx> ObligationCauseCode<'tcx> {
pub fn parent(&self) -> Option<(&Self, Option<ty::PolyTraitPredicate<'tcx>>)> { pub fn parent(&self) -> Option<(&Self, Option<ty::PolyTraitPredicate<'tcx>>)> {
match self { match self {
FunctionArgumentObligation { parent_code, .. } => Some((parent_code, None)), ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
BuiltinDerivedObligation(derived) Some((parent_code, None))
| WellFormedDerivedObligation(derived)
| ImplDerivedObligation(box ImplDerivedObligationCause { derived, .. }) => {
Some((&derived.parent_code, Some(derived.parent_trait_pred)))
} }
ObligationCauseCode::BuiltinDerivedObligation(derived)
| ObligationCauseCode::WellFormedDerivedObligation(derived)
| ObligationCauseCode::ImplDerivedObligation(box ImplDerivedObligationCause {
derived,
..
}) => Some((&derived.parent_code, Some(derived.parent_trait_pred))),
_ => None, _ => None,
} }
} }
pub fn peel_match_impls(&self) -> &Self { pub fn peel_match_impls(&self) -> &Self {
match self { match self {
MatchImpl(cause, _) => cause.code(), ObligationCauseCode::MatchImpl(cause, _) => cause.code(),
_ => self, _ => self,
} }
} }

View file

@ -7,7 +7,7 @@ use rustc_infer::traits::solve::inspect::ProbeKind;
use rustc_infer::traits::solve::{CandidateSource, GoalSource, MaybeCause}; use rustc_infer::traits::solve::{CandidateSource, GoalSource, MaybeCause};
use rustc_infer::traits::{ use rustc_infer::traits::{
self, FulfillmentError, FulfillmentErrorCode, MismatchedProjectionTypes, Obligation, self, FulfillmentError, FulfillmentErrorCode, MismatchedProjectionTypes, Obligation,
ObligationCause, PredicateObligation, SelectionError, TraitEngine, ObligationCause, ObligationCauseCode, PredicateObligation, SelectionError, TraitEngine,
}; };
use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::error::{ExpectedFound, TypeError};
use rustc_middle::ty::{self, TyCtxt}; use rustc_middle::ty::{self, TyCtxt};
@ -425,17 +425,20 @@ fn derive_cause<'tcx>(
tcx.predicates_of(impl_def_id).instantiate_identity(tcx).iter().nth(idx) tcx.predicates_of(impl_def_id).instantiate_identity(tcx).iter().nth(idx)
{ {
cause = cause.derived_cause(parent_trait_pred, |derived| { cause = cause.derived_cause(parent_trait_pred, |derived| {
traits::ImplDerivedObligation(Box::new(traits::ImplDerivedObligationCause { ObligationCauseCode::ImplDerivedObligation(Box::new(
derived, traits::ImplDerivedObligationCause {
impl_or_alias_def_id: impl_def_id, derived,
impl_def_predicate_index: Some(idx), impl_or_alias_def_id: impl_def_id,
span, impl_def_predicate_index: Some(idx),
})) span,
},
))
}) })
} }
} }
ProbeKind::TraitCandidate { source: CandidateSource::BuiltinImpl(..), result: _ } => { ProbeKind::TraitCandidate { source: CandidateSource::BuiltinImpl(..), result: _ } => {
cause = cause.derived_cause(parent_trait_pred, traits::BuiltinDerivedObligation); cause = cause
.derived_cause(parent_trait_pred, ObligationCauseCode::BuiltinDerivedObligation);
} }
_ => {} _ => {}
}; };

View file

@ -13,6 +13,7 @@ use super::Selection;
use super::SelectionContext; use super::SelectionContext;
use super::SelectionError; use super::SelectionError;
use super::{Normalized, NormalizedTy, ProjectionCacheEntry, ProjectionCacheKey}; use super::{Normalized, NormalizedTy, ProjectionCacheEntry, ProjectionCacheKey};
use rustc_infer::traits::ObligationCauseCode;
use rustc_middle::traits::BuiltinImplSource; use rustc_middle::traits::BuiltinImplSource;
use rustc_middle::traits::ImplSource; use rustc_middle::traits::ImplSource;
use rustc_middle::traits::ImplSourceUserDefinedData; use rustc_middle::traits::ImplSourceUserDefinedData;
@ -573,9 +574,9 @@ pub fn normalize_inherent_projection<'a, 'b, 'tcx>(
// diagnostics which is not ideal. // diagnostics which is not ideal.
// Consider creating separate cause codes for this specific situation. // Consider creating separate cause codes for this specific situation.
if span.is_dummy() { if span.is_dummy() {
super::ItemObligation(alias_ty.def_id) ObligationCauseCode::ItemObligation(alias_ty.def_id)
} else { } else {
super::BindingObligation(alias_ty.def_id, span) ObligationCauseCode::BindingObligation(alias_ty.def_id, span)
}, },
); );
@ -2113,22 +2114,22 @@ fn assoc_ty_own_obligations<'cx, 'tcx>(
let nested_cause = if matches!( let nested_cause = if matches!(
obligation.cause.code(), obligation.cause.code(),
super::CompareImplItemObligation { .. } ObligationCauseCode::CompareImplItemObligation { .. }
| super::CheckAssociatedTypeBounds { .. } | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
| super::AscribeUserTypeProvePredicate(..) | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
) { ) {
obligation.cause.clone() obligation.cause.clone()
} else if span.is_dummy() { } else if span.is_dummy() {
ObligationCause::new( ObligationCause::new(
obligation.cause.span, obligation.cause.span,
obligation.cause.body_id, obligation.cause.body_id,
super::ItemObligation(obligation.predicate.def_id), ObligationCauseCode::ItemObligation(obligation.predicate.def_id),
) )
} else { } else {
ObligationCause::new( ObligationCause::new(
obligation.cause.span, obligation.cause.span,
obligation.cause.body_id, obligation.cause.body_id,
super::BindingObligation(obligation.predicate.def_id, span), ObligationCauseCode::BindingObligation(obligation.predicate.def_id, span),
) )
}; };
nested.push(Obligation::with_depth( nested.push(Obligation::with_depth(

View file

@ -11,6 +11,7 @@ use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_hir::lang_items::LangItem; use rustc_hir::lang_items::LangItem;
use rustc_infer::infer::HigherRankedType; use rustc_infer::infer::HigherRankedType;
use rustc_infer::infer::{DefineOpaqueTypes, InferOk}; use rustc_infer::infer::{DefineOpaqueTypes, InferOk};
use rustc_infer::traits::ObligationCauseCode;
use rustc_middle::traits::{BuiltinImplSource, SignatureMismatchData}; use rustc_middle::traits::{BuiltinImplSource, SignatureMismatchData};
use rustc_middle::ty::{ use rustc_middle::ty::{
self, GenericArgs, GenericArgsRef, GenericParamDefKind, ToPolyTraitRef, ToPredicate, self, GenericArgs, GenericArgsRef, GenericParamDefKind, ToPolyTraitRef, ToPredicate,
@ -25,10 +26,9 @@ use crate::traits::vtable::{
VtblSegment, VtblSegment,
}; };
use crate::traits::{ use crate::traits::{
BuiltinDerivedObligation, ImplDerivedObligation, ImplDerivedObligationCause, ImplSource, ImplDerivedObligationCause, ImplSource, ImplSourceUserDefinedData, Normalized, Obligation,
ImplSourceUserDefinedData, Normalized, Obligation, ObligationCause, PolyTraitObligation, ObligationCause, PolyTraitObligation, PredicateObligation, Selection, SelectionError,
PredicateObligation, Selection, SelectionError, SignatureMismatch, TraitNotObjectSafe, SignatureMismatch, TraitNotObjectSafe, TraitObligation, Unimplemented,
TraitObligation, Unimplemented,
}; };
use super::BuiltinImplConditions; use super::BuiltinImplConditions;
@ -275,7 +275,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation); bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation);
}; };
let cause = obligation.derived_cause(BuiltinDerivedObligation); let cause = obligation.derived_cause(ObligationCauseCode::BuiltinDerivedObligation);
self.collect_predicates_for_types( self.collect_predicates_for_types(
obligation.param_env, obligation.param_env,
cause, cause,
@ -435,7 +435,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
) -> Vec<PredicateObligation<'tcx>> { ) -> Vec<PredicateObligation<'tcx>> {
debug!(?nested, "vtable_auto_impl"); debug!(?nested, "vtable_auto_impl");
ensure_sufficient_stack(|| { ensure_sufficient_stack(|| {
let cause = obligation.derived_cause(BuiltinDerivedObligation); let cause = obligation.derived_cause(ObligationCauseCode::BuiltinDerivedObligation);
let poly_trait_ref = obligation.predicate.to_poly_trait_ref(); let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
let trait_ref = self.infcx.enter_forall_and_leak_universe(poly_trait_ref); let trait_ref = self.infcx.enter_forall_and_leak_universe(poly_trait_ref);
@ -723,7 +723,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
let mut nested = let mut nested =
self.equate_trait_refs(obligation.with(tcx, placeholder_predicate), trait_ref)?; self.equate_trait_refs(obligation.with(tcx, placeholder_predicate), trait_ref)?;
let cause = obligation.derived_cause(BuiltinDerivedObligation); let cause = obligation.derived_cause(ObligationCauseCode::BuiltinDerivedObligation);
// Confirm the `type Output: Sized;` bound that is present on `FnOnce` // Confirm the `type Output: Sized;` bound that is present on `FnOnce`
let output_ty = self.infcx.enter_forall_and_leak_universe(sig.output()); let output_ty = self.infcx.enter_forall_and_leak_universe(sig.output());
@ -1381,7 +1381,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
let self_ty = obligation.self_ty().map_bound(|ty| self.infcx.shallow_resolve(ty)); let self_ty = obligation.self_ty().map_bound(|ty| self.infcx.shallow_resolve(ty));
let mut nested = vec![]; let mut nested = vec![];
let cause = obligation.derived_cause(BuiltinDerivedObligation); let cause = obligation.derived_cause(ObligationCauseCode::BuiltinDerivedObligation);
// If we have a custom `impl const Drop`, then // If we have a custom `impl const Drop`, then
// first check it like a regular impl candidate. // first check it like a regular impl candidate.
@ -1396,7 +1396,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
debug!(?args, "impl args"); debug!(?args, "impl args");
let cause = obligation.derived_cause(|derived| { let cause = obligation.derived_cause(|derived| {
ImplDerivedObligation(Box::new(ImplDerivedObligationCause { ObligationCauseCode::ImplDerivedObligation(Box::new(ImplDerivedObligationCause {
derived, derived,
impl_or_alias_def_id: impl_def_id, impl_or_alias_def_id: impl_def_id,
impl_def_predicate_index: None, impl_def_predicate_index: None,

View file

@ -13,9 +13,9 @@ use super::util;
use super::util::closure_trait_ref_and_return_type; use super::util::closure_trait_ref_and_return_type;
use super::wf; use super::wf;
use super::{ use super::{
ImplDerivedObligation, ImplDerivedObligationCause, Normalized, Obligation, ObligationCause, ImplDerivedObligationCause, Normalized, Obligation, ObligationCause, ObligationCauseCode,
ObligationCauseCode, Overflow, PolyTraitObligation, PredicateObligation, Selection, Overflow, PolyTraitObligation, PredicateObligation, Selection, SelectionError, SelectionResult,
SelectionError, SelectionResult, TraitQueryMode, TraitQueryMode,
}; };
use crate::infer::{InferCtxt, InferOk, TypeFreshener}; use crate::infer::{InferCtxt, InferOk, TypeFreshener};
@ -2771,12 +2771,14 @@ impl<'tcx> SelectionContext<'_, 'tcx> {
cause.clone() cause.clone()
} else { } else {
cause.clone().derived_cause(parent_trait_pred, |derived| { cause.clone().derived_cause(parent_trait_pred, |derived| {
ImplDerivedObligation(Box::new(ImplDerivedObligationCause { ObligationCauseCode::ImplDerivedObligation(Box::new(
derived, ImplDerivedObligationCause {
impl_or_alias_def_id: def_id, derived,
impl_def_predicate_index: Some(index), impl_or_alias_def_id: def_id,
span, impl_def_predicate_index: Some(index),
})) span,
},
))
}) })
}; };
let clause = normalize_with_depth_to( let clause = normalize_with_depth_to(

View file

@ -2,6 +2,7 @@ use crate::infer::InferCtxt;
use crate::traits; use crate::traits;
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::lang_items::LangItem; use rustc_hir::lang_items::LangItem;
use rustc_infer::traits::ObligationCauseCode;
use rustc_middle::ty::{ use rustc_middle::ty::{
self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
}; };
@ -333,7 +334,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
return self.out; return self.out;
} }
let cause = self.cause(traits::WellFormed(None)); let cause = self.cause(ObligationCauseCode::WellFormed(None));
let param_env = self.param_env; let param_env = self.param_env;
let mut obligations = Vec::with_capacity(self.out.len()); let mut obligations = Vec::with_capacity(self.out.len());
for mut obligation in self.out { for mut obligation in self.out {
@ -485,7 +486,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
&mut traits::SelectionContext::new(self.infcx), &mut traits::SelectionContext::new(self.infcx),
self.param_env, self.param_env,
data, data,
self.cause(traits::WellFormed(None)), self.cause(ObligationCauseCode::WellFormed(None)),
self.recursion_depth, self.recursion_depth,
&mut self.out, &mut self.out,
); );
@ -498,7 +499,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
fn compute_projection_args(&mut self, args: GenericArgsRef<'tcx>) { fn compute_projection_args(&mut self, args: GenericArgsRef<'tcx>) {
let tcx = self.tcx(); let tcx = self.tcx();
let cause = self.cause(traits::WellFormed(None)); let cause = self.cause(ObligationCauseCode::WellFormed(None));
let param_env = self.param_env; let param_env = self.param_env;
let depth = self.recursion_depth; let depth = self.recursion_depth;
@ -565,9 +566,9 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
iter::zip(predicates, origins.into_iter().rev()) iter::zip(predicates, origins.into_iter().rev())
.map(|((pred, span), origin_def_id)| { .map(|((pred, span), origin_def_id)| {
let code = if span.is_dummy() { let code = if span.is_dummy() {
traits::ItemObligation(origin_def_id) ObligationCauseCode::ItemObligation(origin_def_id)
} else { } else {
traits::BindingObligation(origin_def_id, span) ObligationCauseCode::BindingObligation(origin_def_id, span)
}; };
let cause = self.cause(code); let cause = self.cause(code);
traits::Obligation::with_depth( traits::Obligation::with_depth(
@ -626,7 +627,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
self.out.reserve(implicit_bounds.len()); self.out.reserve(implicit_bounds.len());
for implicit_bound in implicit_bounds { for implicit_bound in implicit_bounds {
let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound)); let cause = self.cause(ObligationCauseCode::ObjectTypeBound(ty, explicit_bound));
let outlives = let outlives =
ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound)); ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
self.out.push(traits::Obligation::with_depth( self.out.push(traits::Obligation::with_depth(
@ -644,7 +645,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> { impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
type Result = (); type Result = ();
fn visit_ty(&mut self, t: <TyCtxt<'tcx> as ty::Interner>::Ty) -> Self::Result { fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
debug!("wf bounds for t={:?} t.kind={:#?}", t, t.kind()); debug!("wf bounds for t={:?} t.kind={:#?}", t, t.kind());
let tcx = self.tcx(); let tcx = self.tcx();
@ -673,22 +674,22 @@ impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
ty::Infer(ty::FloatVar(_)) => {} ty::Infer(ty::FloatVar(_)) => {}
ty::Slice(subty) => { ty::Slice(subty) => {
self.require_sized(subty, traits::SliceOrArrayElem); self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
} }
ty::Array(subty, _) => { ty::Array(subty, _) => {
self.require_sized(subty, traits::SliceOrArrayElem); self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
// Note that we handle the len is implicitly checked while walking `arg`. // Note that we handle the len is implicitly checked while walking `arg`.
} }
ty::Pat(subty, _) => { ty::Pat(subty, _) => {
self.require_sized(subty, traits::MiscObligation); self.require_sized(subty, ObligationCauseCode::MiscObligation);
} }
ty::Tuple(tys) => { ty::Tuple(tys) => {
if let Some((_last, rest)) = tys.split_last() { if let Some((_last, rest)) = tys.split_last() {
for &elem in rest { for &elem in rest {
self.require_sized(elem, traits::TupleElem); self.require_sized(elem, ObligationCauseCode::TupleElem);
} }
} }
} }
@ -728,7 +729,7 @@ impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
ty::Ref(r, rty, _) => { ty::Ref(r, rty, _) => {
// WfReference // WfReference
if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() { if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
let cause = self.cause(traits::ReferenceOutlivesReferent(t)); let cause = self.cause(ObligationCauseCode::ReferenceOutlivesReferent(t));
self.out.push(traits::Obligation::with_depth( self.out.push(traits::Obligation::with_depth(
tcx, tcx,
cause, cause,
@ -825,7 +826,7 @@ impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
if let Some(principal) = data.principal_def_id() { if let Some(principal) = data.principal_def_id() {
self.out.push(traits::Obligation::with_depth( self.out.push(traits::Obligation::with_depth(
tcx, tcx,
self.cause(traits::WellFormed(None)), self.cause(ObligationCauseCode::WellFormed(None)),
self.recursion_depth, self.recursion_depth,
self.param_env, self.param_env,
ty::Binder::dummy(ty::PredicateKind::ObjectSafe(principal)), ty::Binder::dummy(ty::PredicateKind::ObjectSafe(principal)),
@ -847,7 +848,7 @@ impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
// See also the comment on `fn obligations`, describing "livelock" // See also the comment on `fn obligations`, describing "livelock"
// prevention, which happens before this can be reached. // prevention, which happens before this can be reached.
ty::Infer(_) => { ty::Infer(_) => {
let cause = self.cause(traits::WellFormed(None)); let cause = self.cause(ObligationCauseCode::WellFormed(None));
self.out.push(traits::Obligation::with_depth( self.out.push(traits::Obligation::with_depth(
tcx, tcx,
cause, cause,
@ -863,7 +864,7 @@ impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
t.super_visit_with(self) t.super_visit_with(self)
} }
fn visit_const(&mut self, c: <TyCtxt<'tcx> as ty::Interner>::Const) -> Self::Result { fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
let tcx = self.tcx(); let tcx = self.tcx();
match c.kind() { match c.kind() {
@ -875,7 +876,7 @@ impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
let predicate = ty::Binder::dummy(ty::PredicateKind::Clause( let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
ty::ClauseKind::ConstEvaluatable(c), ty::ClauseKind::ConstEvaluatable(c),
)); ));
let cause = self.cause(traits::WellFormed(None)); let cause = self.cause(ObligationCauseCode::WellFormed(None));
self.out.push(traits::Obligation::with_depth( self.out.push(traits::Obligation::with_depth(
tcx, tcx,
cause, cause,
@ -886,7 +887,7 @@ impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
} }
} }
ty::ConstKind::Infer(_) => { ty::ConstKind::Infer(_) => {
let cause = self.cause(traits::WellFormed(None)); let cause = self.cause(ObligationCauseCode::WellFormed(None));
self.out.push(traits::Obligation::with_depth( self.out.push(traits::Obligation::with_depth(
tcx, tcx,
@ -909,7 +910,7 @@ impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
let predicate = ty::Binder::dummy(ty::PredicateKind::Clause( let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
ty::ClauseKind::ConstEvaluatable(c), ty::ClauseKind::ConstEvaluatable(c),
)); ));
let cause = self.cause(traits::WellFormed(None)); let cause = self.cause(ObligationCauseCode::WellFormed(None));
self.out.push(traits::Obligation::with_depth( self.out.push(traits::Obligation::with_depth(
tcx, tcx,
cause, cause,
@ -933,7 +934,7 @@ impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
c.super_visit_with(self) c.super_visit_with(self)
} }
fn visit_predicate(&mut self, _p: <TyCtxt<'tcx> as ty::Interner>::Predicate) -> Self::Result { fn visit_predicate(&mut self, _p: ty::Predicate<'tcx>) -> Self::Result {
bug!("predicate should not be checked for well-formedness"); bug!("predicate should not be checked for well-formedness");
} }
} }