Auto merge of #124952 - compiler-errors:no-error, r=lcnr

Rename some `FulfillmentErrorCode`/`ObligationCauseCode` variants to be less redundant

1. Rename some `FulfillmentErrorCode` variants.
2. Always use `ObligationCauseCode::` to prefix a code, rather than using a glob import and naming them through `traits::`.
3. Rename some `ObligationCauseCode` variants -- I wasn't particularly thorough with thinking of a new names for these, so could workshop them if necessary.
4. Misc stuff from renaming.

r? lcnr
This commit is contained in:
bors 2024-05-10 18:11:02 +00:00
commit 2cce088584
48 changed files with 432 additions and 393 deletions

View File

@ -1344,7 +1344,7 @@ fn explain_captures(
Applicability::MaybeIncorrect,
);
for error in errors {
if let FulfillmentErrorCode::SelectionError(
if let FulfillmentErrorCode::Select(
SelectionError::Unimplemented,
) = error.code
&& let ty::PredicateKind::Clause(ty::ClauseKind::Trait(

View File

@ -1283,7 +1283,7 @@ fn suggest_make_local_mut(&self, err: &mut Diag<'_>, local: Local, name: Symbol)
}
// The type doesn't implement Clone because of unmet obligations.
for error in errors {
if let traits::FulfillmentErrorCode::SelectionError(
if let traits::FulfillmentErrorCode::Select(
traits::SelectionError::Unimplemented,
) = error.code
&& let ty::PredicateKind::Clause(ty::ClauseKind::Trait(

View File

@ -2059,7 +2059,7 @@ pub(crate) fn best_blame_constraint(
// We currently do not store the `DefId` in the `ConstraintCategory`
// for performances reasons. The error reporting code used by NLL only
// uses the span, so this doesn't cause any problems at the moment.
Some(ObligationCauseCode::BindingObligation(
Some(ObligationCauseCode::SpannedWhereClause(
CRATE_DEF_ID.to_def_id(),
predicate_span,
))
@ -2067,7 +2067,7 @@ pub(crate) fn best_blame_constraint(
None
}
})
.unwrap_or_else(|| ObligationCauseCode::MiscObligation);
.unwrap_or_else(|| ObligationCauseCode::Misc);
// Classify each of the constraints along the path.
let mut categorized_path: Vec<BlameConstraint<'tcx>> = path

View File

@ -738,7 +738,7 @@ fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location
let cause = ObligationCause::new(
terminator.source_info.span,
self.body.source.def_id().expect_local(),
ObligationCauseCode::ItemObligation(callee),
ObligationCauseCode::WhereClause(callee),
);
let normalized_predicates = ocx.normalize(&cause, param_env, predicates);
ocx.register_obligations(traits::predicates_for_generics(

View File

@ -175,7 +175,7 @@ fn compare_method_predicate_entailment<'tcx>(
let cause = ObligationCause::new(
impl_m_span,
impl_m_def_id,
ObligationCauseCode::CompareImplItemObligation {
ObligationCauseCode::CompareImplItem {
impl_item_def_id: impl_m_def_id,
trait_item_def_id: trait_m.def_id,
kind: impl_m.kind,
@ -236,7 +236,7 @@ fn compare_method_predicate_entailment<'tcx>(
let cause = ObligationCause::new(
span,
impl_m_def_id,
ObligationCauseCode::CompareImplItemObligation {
ObligationCauseCode::CompareImplItem {
impl_item_def_id: impl_m_def_id,
trait_item_def_id: trait_m.def_id,
kind: impl_m.kind,
@ -464,7 +464,7 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
let cause = ObligationCause::new(
return_span,
impl_m_def_id,
ObligationCauseCode::CompareImplItemObligation {
ObligationCauseCode::CompareImplItem {
impl_item_def_id: impl_m_def_id,
trait_item_def_id: trait_m.def_id,
kind: impl_m.kind,
@ -819,7 +819,7 @@ fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
ObligationCause::new(
self.span,
self.body_id,
ObligationCauseCode::BindingObligation(proj.def_id, pred_span),
ObligationCauseCode::SpannedWhereClause(proj.def_id, pred_span),
),
self.param_env,
pred,
@ -1752,7 +1752,7 @@ fn compare_const_predicate_entailment<'tcx>(
let impl_ty = tcx.type_of(impl_ct_def_id).instantiate_identity();
let trait_ty = tcx.type_of(trait_ct.def_id).instantiate(tcx, trait_to_impl_args);
let code = ObligationCauseCode::CompareImplItemObligation {
let code = ObligationCauseCode::CompareImplItem {
impl_item_def_id: impl_ct_def_id,
trait_item_def_id: trait_ct.def_id,
kind: impl_ct.kind,
@ -1924,7 +1924,7 @@ fn compare_type_predicate_entailment<'tcx>(
let cause = ObligationCause::new(
span,
impl_ty_def_id,
ObligationCauseCode::CompareImplItemObligation {
ObligationCauseCode::CompareImplItem {
impl_item_def_id: impl_ty.def_id.expect_local(),
trait_item_def_id: trait_ty.def_id,
kind: impl_ty.kind,
@ -2012,9 +2012,9 @@ pub(super) fn check_type_bounds<'tcx>(
);
let mk_cause = |span: Span| {
let code = if span.is_dummy() {
traits::ItemObligation(trait_ty.def_id)
ObligationCauseCode::WhereClause(trait_ty.def_id)
} else {
traits::BindingObligation(trait_ty.def_id, span)
ObligationCauseCode::SpannedWhereClause(trait_ty.def_id, span)
};
ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
};
@ -2251,7 +2251,8 @@ fn try_report_async_mismatch<'tcx>(
};
for error in errors {
if let traits::BindingObligation(def_id, _) = *error.root_obligation.cause.code()
if let ObligationCauseCode::SpannedWhereClause(def_id, _) =
*error.root_obligation.cause.code()
&& def_id == async_future_def_id
&& let Some(proj) = error.root_obligation.predicate.to_opt_poly_projection_pred()
&& let Some(proj) = proj.no_bound_vars()

View File

@ -5,6 +5,7 @@
use rustc_errors::{codes::*, struct_span_code_err, ErrorGuaranteed};
use rustc_infer::infer::outlives::env::OutlivesEnvironment;
use rustc_infer::infer::{RegionResolutionError, TyCtxtInferExt};
use rustc_infer::traits::ObligationCauseCode;
use rustc_middle::ty::util::CheckRegions;
use rustc_middle::ty::GenericArgsRef;
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) {
let normalize_cause = traits::ObligationCause::misc(span, adt_def_id);
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));
}

View File

@ -1136,7 +1136,7 @@ fn check_type_defn<'tcx>(
traits::ObligationCause::new(
hir_ty.span,
wfcx.body_def_id,
traits::FieldSized {
ObligationCauseCode::FieldSized {
adt_kind: match &item.kind {
ItemKind::Struct(..) => AdtKind::Struct,
ItemKind::Union(..) => AdtKind::Union,
@ -1161,7 +1161,7 @@ fn check_type_defn<'tcx>(
let cause = traits::ObligationCause::new(
tcx.def_span(discr_def_id),
wfcx.body_def_id,
traits::MiscObligation,
ObligationCauseCode::Misc,
);
wfcx.register_obligation(traits::Obligation::new(
tcx,
@ -1278,7 +1278,11 @@ fn check_item_type(
wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
if forbid_unsized {
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,
item_ty,
tcx.require_lang_item(LangItem::Sized, None),
@ -1293,7 +1297,11 @@ fn check_item_type(
if should_check_for_sync {
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,
item_ty,
tcx.require_lang_item(LangItem::Sync, Some(ty_span)),
@ -1542,7 +1550,7 @@ fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
let cause = traits::ObligationCause::new(
sp,
wfcx.body_def_id,
traits::ItemObligation(def_id.to_def_id()),
ObligationCauseCode::WhereClause(def_id.to_def_id()),
);
traits::Obligation::new(tcx, cause, wfcx.param_env, pred)
});
@ -1982,7 +1990,11 @@ fn check_false_global_bounds(&mut self) {
let obligation = traits::Obligation::new(
tcx,
traits::ObligationCause::new(span, self.body_def_id, traits::TrivialBound),
traits::ObligationCause::new(
span,
self.body_def_id,
ObligationCauseCode::TrivialBound,
),
empty_env,
pred,
);

View File

@ -212,7 +212,7 @@ fn get_impl_args(
traits::ObligationCause::new(
impl1_span,
impl1_def_id,
traits::ObligationCauseCode::BindingObligation(impl2_node.def_id(), span),
traits::ObligationCauseCode::SpannedWhereClause(impl2_node.def_id(), span),
)
},
);

View File

@ -9,6 +9,7 @@
use rustc_hir::def::{self, CtorKind, Namespace, Res};
use rustc_hir::def_id::DefId;
use rustc_hir_analysis::autoderef::Autoderef;
use rustc_infer::traits::ObligationCauseCode;
use rustc_infer::{
infer,
traits::{self, Obligation, ObligationCause},
@ -117,7 +118,11 @@ pub fn check_call(
};
// 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
}
@ -524,9 +529,9 @@ fn confirm_builtin_call(
self.register_bound(
ty,
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 {
self.dcx().emit_err(errors::RustCallIncorrectArgs { span: sp });
}

View File

@ -14,7 +14,6 @@
use rustc_span::def_id::LocalDefId;
use rustc_span::symbol::sym;
use rustc_target::spec::abi::Abi;
use rustc_trait_selection::traits;
use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode};
/// 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(
param_ty.into(),
param.span,
traits::WellFormed(Some(WellFormedLoc::Param {
ObligationCauseCode::WellFormed(Some(WellFormedLoc::Param {
function: fn_def_id,
param_idx: idx,
})),
@ -101,7 +100,7 @@ pub(super) fn check_fn<'a, 'tcx>(
param.pat.span,
// ty.span == binding_span iff this is a closure parameter with no type ascription,
// 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()) {
None
} else {
@ -121,10 +120,18 @@ pub(super) fn check_fn<'a, 'tcx>(
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.
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);

View File

@ -8,6 +8,7 @@
use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes};
use rustc_infer::infer::{InferOk, InferResult};
use rustc_infer::traits::ObligationCauseCode;
use rustc_macros::{TypeFoldable, TypeVisitable};
use rustc_middle::ty::visit::{TypeVisitable, TypeVisitableExt};
use rustc_middle::ty::GenericArgs;
@ -119,7 +120,11 @@ pub fn check_expr_closure(
hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)
| hir::CoroutineKind::Coroutine(_) => {
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
}
// HACK(-Ztrait-solver=next): In the *old* trait solver, we must eagerly
@ -128,7 +133,11 @@ pub fn check_expr_closure(
// not a problem.
hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _) => {
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(
tcx,

View File

@ -573,7 +573,7 @@ pub(crate) fn check_expr_path(
self.require_type_is_sized_deferred(
input,
span,
traits::SizedArgumentType(None),
ObligationCauseCode::SizedArgumentType(None),
);
}
}
@ -591,7 +591,7 @@ pub(crate) fn check_expr_path(
self.require_type_is_sized_deferred(
output,
call.map_or(expr.span, |e| e.span),
traits::SizedCallReturnType,
ObligationCauseCode::SizedCallReturnType,
);
}
@ -1249,7 +1249,7 @@ fn check_expr_assign(
}
});
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() {
Ty::new_error(self.tcx, guar)
@ -1471,7 +1471,7 @@ fn check_expr_const_block(
crate::GatherLocalsVisitor::new(&fcx).visit_body(body);
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);
ty
}
@ -1517,7 +1517,7 @@ fn check_expr_repeat(
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
}
@ -1607,7 +1607,11 @@ fn check_expr_tuple(
if let Err(guar) = tuple.error_reported() {
Ty::new_error(self.tcx, guar)
} else {
self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized);
self.require_type_is_sized(
tuple,
expr.span,
ObligationCauseCode::TupleInitializerSized,
);
tuple
}
}
@ -1646,7 +1650,7 @@ fn check_expr_struct(
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
}
@ -3079,14 +3083,12 @@ fn find_and_report_unsatisfied_index_impl(
polarity: ty::PredicatePolarity::Positive,
}),
|derived| {
traits::ImplDerivedObligation(Box::new(
traits::ImplDerivedObligationCause {
derived,
impl_or_alias_def_id: impl_def_id,
impl_def_predicate_index: Some(idx),
span,
},
))
ObligationCauseCode::ImplDerived(Box::new(traits::ImplDerivedCause {
derived,
impl_or_alias_def_id: impl_def_id,
impl_def_predicate_index: Some(idx),
span,
}))
},
)
},
@ -3177,7 +3179,7 @@ fn check_expr_yield(
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 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() {
self.dcx()
@ -3348,7 +3350,7 @@ fn check_offset_of(
let field_ty = self.field_ty(expr.span, field, args);
// 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::Misc);
if field.vis.is_accessible_from(sub_def_scope, self.tcx) {
self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
@ -3376,7 +3378,7 @@ fn check_offset_of(
let field_ty = self.field_ty(expr.span, field, args);
// 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::Misc);
if field.vis.is_accessible_from(def_scope, self.tcx) {
self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
@ -3397,7 +3399,7 @@ fn check_offset_of(
&& field.name == sym::integer(index)
{
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::Misc);
}
if let Some(&field_ty) = tys.get(index) {
field_indices.push((FIRST_VARIANT, index.into()));

View File

@ -409,7 +409,7 @@ pub fn register_bound(
pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> LoweredTy<'tcx> {
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)
}
@ -520,7 +520,7 @@ pub fn add_wf_bounds(&self, args: GenericArgsRef<'tcx>, expr: &hir::Expr<'_>) {
for arg in args.iter().filter(|arg| {
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));
}
}
@ -772,7 +772,11 @@ pub fn resolve_ty_and_res_fully_qualified_call(
};
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
// errors with default match binding modes. See #44614.
let def = cached_result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id));
@ -811,7 +815,7 @@ pub fn resolve_ty_and_res_fully_qualified_call(
self.register_wf_obligation(
ty.raw.into(),
qself.span,
traits::WellFormed(None),
ObligationCauseCode::WellFormed(None),
);
}
@ -845,7 +849,11 @@ pub fn resolve_ty_and_res_fully_qualified_call(
});
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.
@ -1402,9 +1410,9 @@ pub(crate) fn add_required_obligations_for_hir(
) {
self.add_required_obligations_with_code(span, def_id, args, |idx, span| {
if span.is_dummy() {
ObligationCauseCode::ExprItemObligation(def_id, hir_id, idx)
ObligationCauseCode::WhereClauseInExpr(def_id, hir_id, idx)
} else {
ObligationCauseCode::ExprBindingObligation(def_id, span, hir_id, idx)
ObligationCauseCode::SpannedWhereClauseInExpr(def_id, span, hir_id, idx)
}
})
}

View File

@ -14,8 +14,8 @@ pub fn adjust_fulfillment_error_for_expr_obligation(
&self,
error: &mut traits::FulfillmentError<'tcx>,
) -> bool {
let (traits::ExprItemObligation(def_id, hir_id, idx)
| traits::ExprBindingObligation(def_id, _, hir_id, idx)) =
let (ObligationCauseCode::WhereClauseInExpr(def_id, hir_id, idx)
| ObligationCauseCode::SpannedWhereClauseInExpr(def_id, _, hir_id, idx)) =
*error.obligation.cause.code().peel_derives()
else {
return false;
@ -167,7 +167,7 @@ pub fn adjust_fulfillment_error_for_expr_obligation(
// the method's turbofish segments but still use `FunctionArgumentObligation`
// elsewhere. Hopefully this doesn't break something.
error.obligation.cause.map_code(|parent_code| {
ObligationCauseCode::FunctionArgumentObligation {
ObligationCauseCode::FunctionArg {
arg_hir_id: receiver.hir_id,
call_hir_id: hir_id,
parent_code,
@ -360,12 +360,9 @@ fn closure_span_overlaps_error(
error: &traits::FulfillmentError<'tcx>,
span: Span,
) -> bool {
if let traits::FulfillmentErrorCode::SelectionError(
traits::SelectionError::SignatureMismatch(box traits::SignatureMismatchData {
expected_trait_ref,
..
}),
) = error.code
if let traits::FulfillmentErrorCode::Select(traits::SelectionError::SignatureMismatch(
box traits::SignatureMismatchData { expected_trait_ref, .. },
)) = error.code
&& let ty::Closure(def_id, _) | ty::Coroutine(def_id, ..) =
expected_trait_ref.self_ty().kind()
&& span.overlaps(self.tcx.def_span(*def_id))
@ -459,12 +456,10 @@ fn blame_specific_arg_if_possible(
self.blame_specific_expr_if_possible(error, arg_expr)
}
error.obligation.cause.map_code(|parent_code| {
ObligationCauseCode::FunctionArgumentObligation {
arg_hir_id: arg.hir_id,
call_hir_id,
parent_code,
}
error.obligation.cause.map_code(|parent_code| ObligationCauseCode::FunctionArg {
arg_hir_id: arg.hir_id,
call_hir_id,
parent_code,
});
return true;
} else if args_referencing_param.len() > 0 {
@ -517,12 +512,12 @@ fn blame_specific_expr_if_possible_for_obligation_cause_code(
expr: &'tcx hir::Expr<'tcx>,
) -> Result<&'tcx hir::Expr<'tcx>, &'tcx hir::Expr<'tcx>> {
match obligation_cause_code {
traits::ObligationCauseCode::ExprBindingObligation(_, _, _, _) => {
traits::ObligationCauseCode::SpannedWhereClauseInExpr(_, _, _, _) => {
// This is the "root"; we assume that the `expr` is already pointing here.
// Therefore, we return `Ok` so that this `expr` can be refined further.
Ok(expr)
}
traits::ObligationCauseCode::ImplDerivedObligation(impl_derived) => self
traits::ObligationCauseCode::ImplDerived(impl_derived) => self
.blame_specific_expr_if_possible_for_derived_predicate_obligation(
impl_derived,
expr,
@ -560,7 +555,7 @@ fn blame_specific_expr_if_possible_for_obligation_cause_code(
/// only a partial success - but it cannot be refined even further.
fn blame_specific_expr_if_possible_for_derived_predicate_obligation(
&self,
obligation: &traits::ImplDerivedObligationCause<'tcx>,
obligation: &traits::ImplDerivedCause<'tcx>,
expr: &'tcx hir::Expr<'tcx>,
) -> Result<&'tcx hir::Expr<'tcx>, &'tcx hir::Expr<'tcx>> {
// First, we attempt to refine the `expr` for our span using the parent obligation.

View File

@ -33,7 +33,6 @@
use rustc_infer::infer::error_reporting::{FailureCode, ObligationCauseExt};
use rustc_infer::infer::TypeTrace;
use rustc_infer::infer::{DefineOpaqueTypes, InferOk};
use rustc_middle::traits::ObligationCauseCode::ExprBindingObligation;
use rustc_middle::ty::adjustment::AllowTwoPhase;
use rustc_middle::ty::visit::TypeVisitableExt;
use rustc_middle::ty::{self, IsSuggestable, Ty, TyCtxt};
@ -203,7 +202,11 @@ pub(in super::super) fn check_argument_types(
// All the input types from the fn signature must outlive the call
// so as to validate implied bounds.
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::Misc,
);
}
let mut err_code = E0061;
@ -2010,7 +2013,8 @@ pub(super) fn collect_unused_stmts_for_coerce_return_ty(
for (span, code) in errors_causecode {
self.dcx().try_steal_modify_and_emit_err(span, StashKey::MaybeForgetReturn, |err| {
if let Some(fn_sig) = self.body_fn_sig()
&& let ExprBindingObligation(_, _, binding_hir_id, ..) = code
&& let ObligationCauseCode::SpannedWhereClauseInExpr(_, _, binding_hir_id, ..) =
code
&& !fn_sig.output().is_unit()
{
let mut block_num = 0;
@ -2099,7 +2103,7 @@ pub(super) fn adjust_fulfillment_errors_for_expr_obligation(
//
// This is because due to normalization, we often register duplicate
// obligations with misc obligations that are basically impossible to
// line back up with a useful ExprBindingObligation.
// line back up with a useful SpannedWhereClauseInExpr.
for error in not_adjusted {
for (span, predicate, cause) in &remap_cause {
if *predicate == error.obligation.predicate

View File

@ -154,7 +154,7 @@ pub fn cause(&self, span: Span, code: ObligationCauseCode<'tcx>) -> ObligationCa
}
pub fn misc(&self, span: Span) -> ObligationCause<'tcx> {
self.cause(span, ObligationCauseCode::MiscObligation)
self.cause(span, ObligationCauseCode::Misc)
}
pub fn sess(&self) -> &Session {

View File

@ -1700,7 +1700,7 @@ pub(crate) fn note_type_is_not_clone(
}
}
for error in errors {
if let traits::FulfillmentErrorCode::SelectionError(
if let traits::FulfillmentErrorCode::Select(
traits::SelectionError::Unimplemented,
) = error.code
&& let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =

View File

@ -2,11 +2,11 @@
use rustc_hir as hir;
use rustc_hir::intravisit::{self, Visitor};
use rustc_hir::{HirId, PatKind};
use rustc_infer::traits::ObligationCauseCode;
use rustc_middle::ty::Ty;
use rustc_middle::ty::UserType;
use rustc_span::def_id::LocalDefId;
use rustc_span::Span;
use rustc_trait_selection::traits;
/// 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
@ -146,7 +146,7 @@ fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
p.span,
// ty_span == ident.span iff this is a closure parameter with no type
// ascription, or if it's an implicit `self` parameter
traits::SizedArgumentType(
ObligationCauseCode::SizedArgumentType(
if ty_span == ident.span
&& self.fcx.tcx.is_closure_like(self.fcx.body_id.into())
{
@ -159,7 +159,11 @@ fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
}
} else {
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::hir_ty_lowering::HirTyLowerer;
use rustc_infer::traits::{ObligationCauseCode, ObligationInspector, WellFormedLoc};
use rustc_middle::query::Providers;
use rustc_middle::traits;
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_session::config;
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)));
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).
GatherLocalsVisitor::new(&fcx).visit_body(body);

View File

@ -565,9 +565,9 @@ fn add_obligations(
for obligation in traits::predicates_for_generics(
|idx, span| {
let code = if span.is_dummy() {
ObligationCauseCode::ExprItemObligation(def_id, self.call_expr.hir_id, idx)
ObligationCauseCode::WhereClauseInExpr(def_id, self.call_expr.hir_id, idx)
} else {
ObligationCauseCode::ExprBindingObligation(
ObligationCauseCode::SpannedWhereClauseInExpr(
def_id,
span,
self.call_expr.hir_id,
@ -589,7 +589,7 @@ fn add_obligations(
// the function type must also be well-formed (this is not
// implied by the args being well-formed because of inherent
// 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::error_reporting::TypeAnnotationNeeded::E0282;
use rustc_infer::infer::DefineOpaqueTypes;
use rustc_infer::infer::{self, InferOk, TyCtxtInferExt};
use rustc_infer::traits::ObligationCauseCode;
use rustc_middle::middle::stability;
use rustc_middle::query::Providers;
use rustc_middle::ty::fast_reject::{simplify_type, TreatParams};
@ -1401,9 +1402,13 @@ fn consider_probe(
ocx.register_obligations(traits::predicates_for_generics(
|idx, span| {
let code = if span.is_dummy() {
traits::ExprItemObligation(impl_def_id, self.scope_expr_id, idx)
ObligationCauseCode::WhereClauseInExpr(
impl_def_id,
self.scope_expr_id,
idx,
)
} else {
traits::ExprBindingObligation(
ObligationCauseCode::SpannedWhereClauseInExpr(
impl_def_id,
span,
self.scope_expr_id,

View File

@ -146,7 +146,7 @@ fn is_iterator_predicate(predicate: ty::Predicate<'_>, tcx: TyCtxt<'_>) -> bool
return false;
};
let trait_ref = ty::TraitRef::new(self.tcx, into_iterator_trait, [ty]);
let cause = ObligationCause::new(span, self.body_id, ObligationCauseCode::MiscObligation);
let cause = ObligationCause::new(span, self.body_id, ObligationCauseCode::Misc);
let obligation = Obligation::new(self.tcx, cause, self.param_env, trait_ref);
if !self.predicate_must_hold_modulo_regions(&obligation) {
return false;
@ -826,12 +826,12 @@ pub fn report_no_match_method_error(
// Extract the predicate span and parent def id of the cause,
// if we have one.
let (item_def_id, cause_span) = match cause.as_ref().map(|cause| cause.code()) {
Some(ObligationCauseCode::ImplDerivedObligation(data)) => {
Some(ObligationCauseCode::ImplDerived(data)) => {
(data.impl_or_alias_def_id, data.span)
}
Some(
ObligationCauseCode::ExprBindingObligation(def_id, span, _, _)
| ObligationCauseCode::BindingObligation(def_id, span),
ObligationCauseCode::SpannedWhereClauseInExpr(def_id, span, _, _)
| ObligationCauseCode::SpannedWhereClause(def_id, span),
) => (*def_id, *span),
_ => continue,
};

View File

@ -19,7 +19,7 @@
use rustc_span::Span;
use rustc_trait_selection::infer::InferCtxtExt;
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::*;
impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
@ -884,7 +884,7 @@ fn lookup_op_method(
let input_types = opt_rhs_ty.as_slice();
let cause = self.cause(
span,
traits::BinOp {
ObligationCauseCode::BinOp {
lhs_hir_id: lhs_expr.hir_id,
rhs_hir_id: opt_rhs_expr.map(|expr| expr.hir_id),
rhs_span: opt_rhs_expr.map(|expr| expr.span),

View File

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

View File

@ -883,8 +883,8 @@ fn note_error_origin(
err.help("...or use `match` instead of `let...else`");
}
_ => {
if let ObligationCauseCode::BindingObligation(_, span)
| ObligationCauseCode::ExprBindingObligation(_, span, ..) =
if let ObligationCauseCode::SpannedWhereClause(_, span)
| ObligationCauseCode::SpannedWhereClauseInExpr(_, span, ..) =
cause.code().peel_derives()
&& let TypeError::RegionsPlaceholderMismatch = terr
{
@ -2012,7 +2012,6 @@ pub fn type_error_additional_suggestions(
trace: &TypeTrace<'tcx>,
terr: TypeError<'tcx>,
) -> Vec<TypeErrorAdditionalDiags> {
use crate::traits::ObligationCauseCode::{BlockTailExpression, MatchExpressionArm};
let mut suggestions = Vec::new();
let span = trace.cause.span();
let values = self.resolve_vars_if_possible(trace.values);
@ -2079,8 +2078,11 @@ pub fn type_error_additional_suggestions(
}
}
let code = trace.cause.code();
if let &(MatchExpressionArm(box MatchExpressionArmCause { source, .. })
| BlockTailExpression(.., source)) = code
if let &(ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
source,
..
})
| ObligationCauseCode::BlockTailExpression(.., source)) = code
&& let hir::MatchSource::TryDesugar(_) = source
&& let Some((expected_ty, found_ty, _)) = self.values_str(trace.values)
{
@ -2773,19 +2775,17 @@ pub enum FailureCode {
#[extension(pub trait ObligationCauseExt<'tcx>)]
impl<'tcx> ObligationCause<'tcx> {
fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode {
use self::FailureCode::*;
use crate::traits::ObligationCauseCode::*;
match self.code() {
IfExpressionWithNoElse => Error0317,
MainFunctionType => Error0580,
CompareImplItemObligation { .. }
| MatchExpressionArm(_)
| IfExpression { .. }
| LetElse
| StartFunctionType
| LangFunctionType(_)
| IntrinsicType
| MethodReceiver => Error0308,
ObligationCauseCode::IfExpressionWithNoElse => FailureCode::Error0317,
ObligationCauseCode::MainFunctionType => FailureCode::Error0580,
ObligationCauseCode::CompareImplItem { .. }
| ObligationCauseCode::MatchExpressionArm(_)
| ObligationCauseCode::IfExpression { .. }
| ObligationCauseCode::LetElse
| ObligationCauseCode::StartFunctionType
| ObligationCauseCode::LangFunctionType(_)
| ObligationCauseCode::IntrinsicType
| ObligationCauseCode::MethodReceiver => FailureCode::Error0308,
// In the case where we have no more specific thing to
// say, also take a look at the error code, maybe we can
@ -2794,10 +2794,10 @@ fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode {
TypeError::CyclicTy(ty)
if ty.is_closure() || ty.is_coroutine() || ty.is_coroutine_closure() =>
{
Error0644
FailureCode::Error0644
}
TypeError::IntrinsicCast => Error0308,
_ => Error0308,
TypeError::IntrinsicCast => FailureCode::Error0308,
_ => FailureCode::Error0308,
},
}
}
@ -2807,36 +2807,51 @@ fn as_failure_code_diag(
span: Span,
subdiags: Vec<TypeErrorAdditionalDiags>,
) -> ObligationCauseFailureCode {
use crate::traits::ObligationCauseCode::*;
match self.code() {
CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => {
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn, .. } => {
ObligationCauseFailureCode::MethodCompat { span, subdiags }
}
CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => {
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type, .. } => {
ObligationCauseFailureCode::TypeCompat { span, subdiags }
}
CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => {
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Const, .. } => {
ObligationCauseFailureCode::ConstCompat { span, subdiags }
}
BlockTailExpression(.., hir::MatchSource::TryDesugar(_)) => {
ObligationCauseCode::BlockTailExpression(.., hir::MatchSource::TryDesugar(_)) => {
ObligationCauseFailureCode::TryCompat { span, subdiags }
}
MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => match source {
ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
source, ..
}) => match source {
hir::MatchSource::TryDesugar(_) => {
ObligationCauseFailureCode::TryCompat { span, subdiags }
}
_ => ObligationCauseFailureCode::MatchCompat { span, subdiags },
},
IfExpression { .. } => ObligationCauseFailureCode::IfElseDifferent { span, subdiags },
IfExpressionWithNoElse => ObligationCauseFailureCode::NoElse { span },
LetElse => ObligationCauseFailureCode::NoDiverge { span, subdiags },
MainFunctionType => ObligationCauseFailureCode::FnMainCorrectType { span },
StartFunctionType => ObligationCauseFailureCode::FnStartCorrectType { span, subdiags },
&LangFunctionType(lang_item_name) => {
ObligationCauseCode::IfExpression { .. } => {
ObligationCauseFailureCode::IfElseDifferent { span, subdiags }
}
ObligationCauseCode::IfExpressionWithNoElse => {
ObligationCauseFailureCode::NoElse { span }
}
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 }
}
IntrinsicType => ObligationCauseFailureCode::IntrinsicCorrectType { span, subdiags },
MethodReceiver => ObligationCauseFailureCode::MethodCorrectType { span, subdiags },
ObligationCauseCode::IntrinsicType => {
ObligationCauseFailureCode::IntrinsicCorrectType { span, subdiags }
}
ObligationCauseCode::MethodReceiver => {
ObligationCauseFailureCode::MethodCorrectType { span, subdiags }
}
// In the case where we have no more specific thing to
// say, also take a look at the error code, maybe we can
@ -2856,22 +2871,21 @@ fn as_failure_code_diag(
}
fn as_requirement_str(&self) -> &'static str {
use crate::traits::ObligationCauseCode::*;
match self.code() {
CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => {
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn, .. } => {
"method type is compatible with trait"
}
CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => {
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type, .. } => {
"associated type is compatible with trait"
}
CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => {
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Const, .. } => {
"const is compatible with trait"
}
MainFunctionType => "`main` function has the correct type",
StartFunctionType => "`#[start]` function has the correct type",
LangFunctionType(_) => "lang item function has the correct type",
IntrinsicType => "intrinsic has the correct type",
MethodReceiver => "method receiver has the correct type",
ObligationCauseCode::MainFunctionType => "`main` function has the correct type",
ObligationCauseCode::StartFunctionType => "`#[start]` function has the correct type",
ObligationCauseCode::LangFunctionType(_) => "lang item function has the correct type",
ObligationCauseCode::IntrinsicType => "intrinsic has the correct type",
ObligationCauseCode::MethodReceiver => "method receiver has the correct type",
_ => "types are compatible",
}
}
@ -2882,16 +2896,17 @@ fn as_requirement_str(&self) -> &'static str {
impl IntoDiagArg for ObligationCauseAsDiagArg<'_> {
fn into_diag_arg(self) -> rustc_errors::DiagArgValue {
use crate::traits::ObligationCauseCode::*;
let kind = match self.0.code() {
CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => "method_compat",
CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => "type_compat",
CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => "const_compat",
MainFunctionType => "fn_main_correct_type",
StartFunctionType => "fn_start_correct_type",
LangFunctionType(_) => "fn_lang_correct_type",
IntrinsicType => "intrinsic_correct_type",
MethodReceiver => "method_correct_type",
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn, .. } => "method_compat",
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type, .. } => "type_compat",
ObligationCauseCode::CompareImplItem { 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",
}
.into();

View File

@ -32,14 +32,14 @@ pub(super) fn try_report_mismatched_static_lifetime(&self) -> Option<ErrorGuaran
// If we added a "points at argument expression" obligation, we remove it here, we care
// about the original obligation only.
let code = match cause.code() {
ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => &*parent_code,
ObligationCauseCode::FunctionArg { parent_code, .. } => &*parent_code,
code => code,
};
let ObligationCauseCode::MatchImpl(parent, impl_def_id) = code else {
return None;
};
let (ObligationCauseCode::BindingObligation(_, binding_span)
| ObligationCauseCode::ExprBindingObligation(_, binding_span, ..)) = *parent.code()
let (ObligationCauseCode::SpannedWhereClause(_, binding_span)
| ObligationCauseCode::SpannedWhereClauseInExpr(_, binding_span, ..)) = *parent.code()
else {
return None;
};

View File

@ -240,8 +240,8 @@ fn report_trait_placeholder_mismatch(
let span = cause.span();
let (leading_ellipsis, satisfy_span, where_span, dup_span, def_id) =
if let ObligationCauseCode::ItemObligation(def_id)
| ObligationCauseCode::ExprItemObligation(def_id, ..) = *cause.code()
if let ObligationCauseCode::WhereClause(def_id)
| ObligationCauseCode::WhereClauseInExpr(def_id, ..) = *cause.code()
{
(
true,

View File

@ -214,8 +214,8 @@ pub(super) fn try_report_static_impl_trait(&self) -> Option<ErrorGuaranteed> {
_ => cause.code(),
}
&& let (
&ObligationCauseCode::ItemObligation(item_def_id)
| &ObligationCauseCode::ExprItemObligation(item_def_id, ..),
&ObligationCauseCode::WhereClause(item_def_id)
| &ObligationCauseCode::WhereClauseInExpr(item_def_id, ..),
None,
) = (code, override_error_code)
{

View File

@ -4,13 +4,13 @@
use crate::infer::error_reporting::nice_region_error::NiceRegionError;
use crate::infer::lexical_region_resolve::RegionResolutionError;
use crate::infer::{Subtype, ValuePairs};
use crate::traits::ObligationCauseCode::CompareImplItemObligation;
use rustc_errors::ErrorGuaranteed;
use rustc_hir as hir;
use rustc_hir::def::Res;
use rustc_hir::def_id::DefId;
use rustc_hir::intravisit::Visitor;
use rustc_middle::hir::nested_filter;
use rustc_middle::traits::ObligationCauseCode;
use rustc_middle::ty::error::ExpectedFound;
use rustc_middle::ty::print::RegionHighlightMode;
use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitor};
@ -31,7 +31,8 @@ pub(super) fn try_report_impl_not_conforming_to_trait(&self) -> Option<ErrorGuar
_,
) = error.clone()
&& let (Subtype(sup_trace), Subtype(sub_trace)) = (&sup_origin, &sub_origin)
&& let CompareImplItemObligation { trait_item_def_id, .. } = sub_trace.cause.code()
&& let ObligationCauseCode::CompareImplItem { trait_item_def_id, .. } =
sub_trace.cause.code()
&& sub_trace.values == sup_trace.values
&& let ValuePairs::PolySigs(ExpectedFound { expected, found }) = sub_trace.values
{

View File

@ -357,13 +357,13 @@ pub(super) fn report_placeholder_failure(
infer::Subtype(box ref trace)
if matches!(
&trace.cause.code().peel_derives(),
ObligationCauseCode::BindingObligation(..)
| ObligationCauseCode::ExprBindingObligation(..)
ObligationCauseCode::SpannedWhereClause(..)
| ObligationCauseCode::SpannedWhereClauseInExpr(..)
) =>
{
// Hack to get around the borrow checker because trace.cause has an `Rc`.
if let ObligationCauseCode::BindingObligation(_, span)
| ObligationCauseCode::ExprBindingObligation(_, span, ..) =
if let ObligationCauseCode::SpannedWhereClause(_, span)
| ObligationCauseCode::SpannedWhereClauseInExpr(_, span, ..) =
&trace.cause.code().peel_derives()
{
let span = *span;
@ -371,7 +371,7 @@ pub(super) fn report_placeholder_failure(
.with_span_note(span, "the lifetime requirement is introduced here")
} else {
unreachable!(
"control flow ensures we have a `BindingObligation` or `ExprBindingObligation` here..."
"control flow ensures we have a `BindingObligation` or `SpannedWhereClauseInExpr` here..."
)
}
}

View File

@ -629,8 +629,7 @@ fn expected_projection(
| hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
)
);
let impl_comparison =
matches!(cause_code, ObligationCauseCode::CompareImplItemObligation { .. });
let impl_comparison = matches!(cause_code, ObligationCauseCode::CompareImplItem { .. });
let assoc = tcx.associated_item(proj_ty.def_id);
if impl_comparison {
// We do not want to suggest calling functions when the reason of the

View File

@ -167,7 +167,7 @@ pub(super) fn suggest_await_on_expect_found(
exp_span, exp_found.expected, exp_found.found,
);
if let ObligationCauseCode::CompareImplItemObligation { .. } = cause.code() {
if let ObligationCauseCode::CompareImplItem { .. } = cause.code() {
return;
}

View File

@ -1876,7 +1876,7 @@ pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default:
SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
}
traits::ObligationCauseCode::CompareImplItemObligation {
traits::ObligationCauseCode::CompareImplItem {
impl_item_def_id,
trait_item_def_id,
kind: _,

View File

@ -103,8 +103,8 @@ pub fn register_region_obligation_with_cause(
cause.span,
sup_type,
match cause.code().peel_derives() {
ObligationCauseCode::BindingObligation(_, span)
| ObligationCauseCode::ExprBindingObligation(_, span, ..) => Some(*span),
ObligationCauseCode::SpannedWhereClause(_, span)
| ObligationCauseCode::SpannedWhereClauseInExpr(_, span, ..) => Some(*span),
_ => None,
},
)

View File

@ -105,7 +105,7 @@ pub fn flip_polarity(&self, tcx: TyCtxt<'tcx>) -> Option<PredicateObligation<'tc
impl<'tcx> PolyTraitObligation<'tcx> {
pub fn derived_cause(
&self,
variant: impl FnOnce(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
variant: impl FnOnce(DerivedCause<'tcx>) -> ObligationCauseCode<'tcx>,
) -> ObligationCause<'tcx> {
self.cause.clone().derived_cause(self.predicate, variant)
}
@ -138,10 +138,10 @@ pub enum FulfillmentErrorCode<'tcx> {
/// Inherently impossible to fulfill; this trait is implemented if and only
/// if it is already implemented.
Cycle(Vec<PredicateObligation<'tcx>>),
SelectionError(SelectionError<'tcx>),
ProjectionError(MismatchedProjectionTypes<'tcx>),
SubtypeError(ExpectedFound<Ty<'tcx>>, TypeError<'tcx>), // always comes from a SubtypePredicate
ConstEquateError(ExpectedFound<Const<'tcx>>, TypeError<'tcx>),
Select(SelectionError<'tcx>),
Project(MismatchedProjectionTypes<'tcx>),
Subtype(ExpectedFound<Ty<'tcx>>, TypeError<'tcx>), // always comes from a SubtypePredicate
ConstEquate(ExpectedFound<Const<'tcx>>, TypeError<'tcx>),
Ambiguity {
/// Overflow is only `Some(suggest_recursion_limit)` when using the next generation
/// trait solver `-Znext-solver`. With the old solver overflow is eagerly handled by
@ -209,10 +209,10 @@ pub fn new(
pub fn is_true_error(&self) -> bool {
match self.code {
FulfillmentErrorCode::SelectionError(_)
| FulfillmentErrorCode::ProjectionError(_)
| FulfillmentErrorCode::SubtypeError(_, _)
| FulfillmentErrorCode::ConstEquateError(_, _) => true,
FulfillmentErrorCode::Select(_)
| FulfillmentErrorCode::Project(_)
| FulfillmentErrorCode::Subtype(_, _)
| FulfillmentErrorCode::ConstEquate(_, _) => true,
FulfillmentErrorCode::Cycle(_) | FulfillmentErrorCode::Ambiguity { overflow: _ } => {
false
}

View File

@ -39,12 +39,12 @@ impl<'tcx> fmt::Debug for traits::FulfillmentErrorCode<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use traits::FulfillmentErrorCode::*;
match *self {
SelectionError(ref e) => write!(f, "{e:?}"),
ProjectionError(ref e) => write!(f, "{e:?}"),
SubtypeError(ref a, ref b) => {
Select(ref e) => write!(f, "{e:?}"),
Project(ref e) => write!(f, "{e:?}"),
Subtype(ref a, ref b) => {
write!(f, "CodeSubtypeError({a:?}, {b:?})")
}
ConstEquateError(ref a, ref b) => {
ConstEquate(ref a, ref b) => {
write!(f, "CodeConstEquateError({a:?}, {b:?})")
}
Ambiguity { overflow: None } => write!(f, "Ambiguity"),

View File

@ -1,7 +1,7 @@
use smallvec::smallvec;
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_middle::ty::{self, ToPredicate, Ty, TyCtxt};
use rustc_span::symbol::Ident;
@ -129,7 +129,7 @@ fn child_with_derived_cause(
index: usize,
) -> Self {
let cause = self.cause.clone().derived_cause(parent_trait_pred, |derived| {
traits::ImplDerivedObligation(Box::new(traits::ImplDerivedObligationCause {
ObligationCauseCode::ImplDerived(Box::new(traits::ImplDerivedCause {
derived,
impl_or_alias_def_id: parent_trait_pred.def_id(),
impl_def_predicate_index: Some(index),

View File

@ -150,11 +150,8 @@ fn suggest_question_mark<'tcx>(
let ocx = ObligationCtxt::new(&infcx);
let body_def_id = cx.tcx.hir().body_owner_def_id(body_id);
let cause = ObligationCause::new(
span,
body_def_id,
rustc_infer::traits::ObligationCauseCode::MiscObligation,
);
let cause =
ObligationCause::new(span, body_def_id, rustc_infer::traits::ObligationCauseCode::Misc);
ocx.register_bound(
cause,

View File

@ -33,8 +33,6 @@
pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache};
pub use self::ObligationCauseCode::*;
/// Depending on the stage of compilation, we want projection to be
/// more or less conservative.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable, Encodable, Decodable)]
@ -129,7 +127,7 @@ pub fn new(
}
pub fn misc(span: Span, body_id: LocalDefId) -> ObligationCause<'tcx> {
ObligationCause::new(span, body_id, MiscObligation)
ObligationCause::new(span, body_id, ObligationCauseCode::Misc)
}
#[inline(always)]
@ -167,7 +165,7 @@ pub fn map_code(
pub fn derived_cause(
mut self,
parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
variant: impl FnOnce(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
variant: impl FnOnce(DerivedCause<'tcx>) -> ObligationCauseCode<'tcx>,
) -> ObligationCause<'tcx> {
/*!
* Creates a cause for obligations that are derived from
@ -182,15 +180,14 @@ pub fn derived_cause(
// NOTE(flaper87): As of now, it keeps track of the whole error
// chain. Ideally, we should have a way to configure this either
// by using -Z verbose-internals or just a CLI argument.
self.code =
variant(DerivedObligationCause { parent_trait_pred, parent_code: self.code }).into();
self.code = variant(DerivedCause { parent_trait_pred, parent_code: self.code }).into();
self
}
pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
match self.code() {
MatchImpl(cause, _) => cause.to_constraint_category(),
AscribeUserTypeProvePredicate(predicate_span) => {
ObligationCauseCode::MatchImpl(cause, _) => cause.to_constraint_category(),
ObligationCauseCode::AscribeUserTypeProvePredicate(predicate_span) => {
ConstraintCategory::Predicate(*predicate_span)
}
_ => ConstraintCategory::BoringNoLocation,
@ -209,7 +206,7 @@ pub struct UnifyReceiverContext<'tcx> {
#[derive(Clone, PartialEq, Eq, Default, HashStable)]
#[derive(TypeVisitable, TypeFoldable, TyEncodable, TyDecodable)]
pub struct InternedObligationCauseCode<'tcx> {
/// `None` for `ObligationCauseCode::MiscObligation` (a common case, occurs ~60% of
/// `None` for `ObligationCauseCode::Misc` (a common case, occurs ~60% of
/// the time). `Some` otherwise.
code: Option<Lrc<ObligationCauseCode<'tcx>>>,
}
@ -225,11 +222,7 @@ impl<'tcx> ObligationCauseCode<'tcx> {
#[inline(always)]
fn into(self) -> InternedObligationCauseCode<'tcx> {
InternedObligationCauseCode {
code: if let ObligationCauseCode::MiscObligation = self {
None
} else {
Some(Lrc::new(self))
},
code: if let ObligationCauseCode::Misc = self { None } else { Some(Lrc::new(self)) },
}
}
}
@ -238,7 +231,7 @@ impl<'tcx> std::ops::Deref for InternedObligationCauseCode<'tcx> {
type Target = ObligationCauseCode<'tcx>;
fn deref(&self) -> &Self::Target {
self.code.as_deref().unwrap_or(&ObligationCauseCode::MiscObligation)
self.code.as_deref().unwrap_or(&ObligationCauseCode::Misc)
}
}
@ -246,7 +239,7 @@ fn deref(&self) -> &Self::Target {
#[derive(TypeVisitable, TypeFoldable)]
pub enum ObligationCauseCode<'tcx> {
/// Not well classified or should be obvious from the span.
MiscObligation,
Misc,
/// A slice or array is WF only if `T: Sized`.
SliceOrArrayElem,
@ -256,20 +249,20 @@ pub enum ObligationCauseCode<'tcx> {
/// Must satisfy all of the where-clause predicates of the
/// given item.
ItemObligation(DefId),
WhereClause(DefId),
/// Like `ItemObligation`, but carries the span of the
/// Like `WhereClause`, but carries the span of the
/// predicate when it can be identified.
BindingObligation(DefId, Span),
SpannedWhereClause(DefId, Span),
/// Like `ItemObligation`, but carries the `HirId` of the
/// Like `WhereClause`, but carries the `HirId` of the
/// expression that caused the obligation, and the `usize`
/// indicates exactly which predicate it is in the list of
/// instantiated predicates.
ExprItemObligation(DefId, HirId, usize),
WhereClauseInExpr(DefId, HirId, usize),
/// Combines `ExprItemObligation` and `BindingObligation`.
ExprBindingObligation(DefId, Span, HirId, usize),
/// Combines `SpannedWhereClause` and `WhereClauseInExpr`.
SpannedWhereClauseInExpr(DefId, Span, HirId, usize),
/// A type like `&'a T` is WF only if `T: 'a`.
ReferenceOutlivesReferent(Ty<'tcx>),
@ -333,16 +326,18 @@ pub enum ObligationCauseCode<'tcx> {
/// Derived obligation (i.e. theoretical `where` clause) on a built-in
/// implementation like `Copy` or `Sized`.
BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
BuiltinDerived(DerivedCause<'tcx>),
/// Derived obligation (i.e. `where` clause) on an user-provided impl
/// or a trait alias.
ImplDerivedObligation(Box<ImplDerivedObligationCause<'tcx>>),
ImplDerived(Box<ImplDerivedCause<'tcx>>),
/// Derived obligation for WF goals.
WellFormedDerivedObligation(DerivedObligationCause<'tcx>),
WellFormedDerived(DerivedCause<'tcx>),
FunctionArgumentObligation {
/// Derived obligation refined to point at a specific argument in
/// a call or method expression.
FunctionArg {
/// The node of the relevant argument in the function call.
arg_hir_id: HirId,
/// The node of the function call.
@ -353,7 +348,7 @@ pub enum ObligationCauseCode<'tcx> {
/// Error derived when checking an impl item is compatible with
/// its corresponding trait item's definition
CompareImplItemObligation {
CompareImplItem {
impl_item_def_id: LocalDefId,
trait_item_def_id: DefId,
kind: ty::AssocKind,
@ -432,8 +427,8 @@ pub enum ObligationCauseCode<'tcx> {
/// then it will be used to perform HIR-based wf checking
/// after an error occurs, in order to generate a more precise error span.
/// This is purely for diagnostic purposes - it is always
/// correct to use `MiscObligation` instead, or to specify
/// `WellFormed(None)`
/// correct to use `Misc` instead, or to specify
/// `WellFormed(None)`.
WellFormed(Option<WellFormedLoc>),
/// From `match_impl`. The cause for us having to match an impl, and the DefId we are matching against.
@ -501,8 +496,8 @@ pub enum WellFormedLoc {
#[derive(Clone, Debug, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
#[derive(TypeVisitable, TypeFoldable)]
pub struct ImplDerivedObligationCause<'tcx> {
pub derived: DerivedObligationCause<'tcx>,
pub struct ImplDerivedCause<'tcx> {
pub derived: DerivedCause<'tcx>,
/// The `DefId` of the `impl` that gave rise to the `derived` obligation.
/// If the `derived` obligation arose from a trait alias, which conceptually has a synthetic impl,
/// then this will be the `DefId` of that trait alias. Care should therefore be taken to handle
@ -540,10 +535,10 @@ pub fn peel_derives_with_predicate(&self) -> (&Self, Option<ty::PolyTraitPredica
pub fn parent(&self) -> Option<(&Self, Option<ty::PolyTraitPredicate<'tcx>>)> {
match self {
FunctionArgumentObligation { parent_code, .. } => Some((parent_code, None)),
BuiltinDerivedObligation(derived)
| WellFormedDerivedObligation(derived)
| ImplDerivedObligation(box ImplDerivedObligationCause { derived, .. }) => {
ObligationCauseCode::FunctionArg { parent_code, .. } => Some((parent_code, None)),
ObligationCauseCode::BuiltinDerived(derived)
| ObligationCauseCode::WellFormedDerived(derived)
| ObligationCauseCode::ImplDerived(box ImplDerivedCause { derived, .. }) => {
Some((&derived.parent_code, Some(derived.parent_trait_pred)))
}
_ => None,
@ -552,7 +547,7 @@ pub fn parent(&self) -> Option<(&Self, Option<ty::PolyTraitPredicate<'tcx>>)> {
pub fn peel_match_impls(&self) -> &Self {
match self {
MatchImpl(cause, _) => cause.code(),
ObligationCauseCode::MatchImpl(cause, _) => cause.code(),
_ => self,
}
}
@ -598,7 +593,7 @@ pub struct IfExpressionCause<'tcx> {
#[derive(Clone, Debug, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
#[derive(TypeVisitable, TypeFoldable)]
pub struct DerivedObligationCause<'tcx> {
pub struct DerivedCause<'tcx> {
/// The trait predicate of the parent obligation that led to the
/// current obligation. Note that only trait obligations lead to
/// derived obligations, so we just store the trait predicate here

View File

@ -7,7 +7,7 @@
use rustc_infer::traits::solve::{CandidateSource, GoalSource, MaybeCause};
use rustc_infer::traits::{
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::{self, TyCtxt};
@ -203,39 +203,35 @@ fn fulfillment_error_for_no_solution<'tcx>(
let code = match obligation.predicate.kind().skip_binder() {
ty::PredicateKind::Clause(ty::ClauseKind::Projection(_)) => {
FulfillmentErrorCode::ProjectionError(
FulfillmentErrorCode::Project(
// FIXME: This could be a `Sorts` if the term is a type
MismatchedProjectionTypes { err: TypeError::Mismatch },
)
}
ty::PredicateKind::NormalizesTo(..) => {
FulfillmentErrorCode::ProjectionError(MismatchedProjectionTypes {
err: TypeError::Mismatch,
})
FulfillmentErrorCode::Project(MismatchedProjectionTypes { err: TypeError::Mismatch })
}
ty::PredicateKind::AliasRelate(_, _, _) => {
FulfillmentErrorCode::ProjectionError(MismatchedProjectionTypes {
err: TypeError::Mismatch,
})
FulfillmentErrorCode::Project(MismatchedProjectionTypes { err: TypeError::Mismatch })
}
ty::PredicateKind::Subtype(pred) => {
let (a, b) = infcx.enter_forall_and_leak_universe(
obligation.predicate.kind().rebind((pred.a, pred.b)),
);
let expected_found = ExpectedFound::new(true, a, b);
FulfillmentErrorCode::SubtypeError(expected_found, TypeError::Sorts(expected_found))
FulfillmentErrorCode::Subtype(expected_found, TypeError::Sorts(expected_found))
}
ty::PredicateKind::Coerce(pred) => {
let (a, b) = infcx.enter_forall_and_leak_universe(
obligation.predicate.kind().rebind((pred.a, pred.b)),
);
let expected_found = ExpectedFound::new(false, a, b);
FulfillmentErrorCode::SubtypeError(expected_found, TypeError::Sorts(expected_found))
FulfillmentErrorCode::Subtype(expected_found, TypeError::Sorts(expected_found))
}
ty::PredicateKind::Clause(_)
| ty::PredicateKind::ObjectSafe(_)
| ty::PredicateKind::Ambiguous => {
FulfillmentErrorCode::SelectionError(SelectionError::Unimplemented)
FulfillmentErrorCode::Select(SelectionError::Unimplemented)
}
ty::PredicateKind::ConstEquate(..) => {
bug!("unexpected goal: {obligation:?}")
@ -429,7 +425,7 @@ fn derive_cause<'tcx>(
tcx.predicates_of(impl_def_id).instantiate_identity(tcx).iter().nth(idx)
{
cause = cause.derived_cause(parent_trait_pred, |derived| {
traits::ImplDerivedObligation(Box::new(traits::ImplDerivedObligationCause {
ObligationCauseCode::ImplDerived(Box::new(traits::ImplDerivedCause {
derived,
impl_or_alias_def_id: impl_def_id,
impl_def_predicate_index: Some(idx),
@ -439,7 +435,7 @@ fn derive_cause<'tcx>(
}
}
ProbeKind::TraitCandidate { source: CandidateSource::BuiltinImpl(..), result: _ } => {
cause = cause.derived_cause(parent_trait_pred, traits::BuiltinDerivedObligation);
cause = cause.derived_cause(parent_trait_pred, ObligationCauseCode::BuiltinDerived);
}
_ => {}
};

View File

@ -127,9 +127,9 @@ fn on_unimplemented_note(
flags.push((sym::ItemContext, enclosure));
match obligation.cause.code() {
ObligationCauseCode::BuiltinDerivedObligation(..)
| ObligationCauseCode::ImplDerivedObligation(..)
| ObligationCauseCode::WellFormedDerivedObligation(..) => {}
ObligationCauseCode::BuiltinDerived(..)
| ObligationCauseCode::ImplDerived(..)
| ObligationCauseCode::WellFormedDerived(..) => {}
_ => {
// this is a "direct", user-specified, rather than derived,
// obligation.

View File

@ -7,7 +7,7 @@
use crate::errors;
use crate::infer::InferCtxt;
use crate::traits::{ImplDerivedObligationCause, NormalizeExt, ObligationCtxt};
use crate::traits::{ImplDerivedCause, NormalizeExt, ObligationCtxt};
use hir::def::CtorOf;
use rustc_data_structures::fx::FxHashSet;
@ -455,8 +455,7 @@ fn suggest_dereferences(
trait_pred: ty::PolyTraitPredicate<'tcx>,
) -> bool {
let mut code = obligation.cause.code();
if let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, call_hir_id, .. } =
code
if let ObligationCauseCode::FunctionArg { arg_hir_id, call_hir_id, .. } = code
&& let Some(typeck_results) = &self.typeck_results
&& let hir::Node::Expr(expr) = self.tcx.hir_node(*arg_hir_id)
&& let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
@ -846,7 +845,7 @@ fn suggest_fn_call(
.collect::<Vec<_>>()
.join(", ");
if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArg { .. })
&& obligation.cause.span.can_be_used_for_suggestions()
{
// When the obligation error has been ensured to have been caused by
@ -980,8 +979,7 @@ fn suggest_add_clone_to_arg(
};
let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false };
let ty::Param(param) = inner_ty.kind() else { return false };
let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } =
obligation.cause.code()
let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
else {
return false;
};
@ -1204,9 +1202,9 @@ fn suggest_add_reference_to_arg(
let span = obligation.cause.span;
let code = match obligation.cause.code() {
ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => parent_code,
c @ ObligationCauseCode::ItemObligation(_)
| c @ ObligationCauseCode::ExprItemObligation(..) => c,
ObligationCauseCode::FunctionArg { parent_code, .. } => parent_code,
c @ ObligationCauseCode::WhereClause(_)
| c @ ObligationCauseCode::WhereClauseInExpr(..) => c,
c if matches!(
span.ctxt().outer_expn_data().kind,
ExpnKind::Desugaring(DesugaringKind::ForLoop)
@ -1262,8 +1260,8 @@ fn suggest_add_reference_to_arg(
let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
let (ref_inner_ty_satisfies_pred, ref_inner_ty_mut) =
if let ObligationCauseCode::ItemObligation(_)
| ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
if let ObligationCauseCode::WhereClause(_)
| ObligationCauseCode::WhereClauseInExpr(..) = obligation.cause.code()
&& let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
{
(
@ -1401,12 +1399,12 @@ fn suggest_add_reference_to_arg(
return false;
};
if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
if let ObligationCauseCode::ImplDerived(cause) = &*code {
try_borrowing(cause.derived.parent_trait_pred, &[])
} else if let ObligationCauseCode::BindingObligation(_, _)
| ObligationCauseCode::ItemObligation(_)
| ObligationCauseCode::ExprItemObligation(..)
| ObligationCauseCode::ExprBindingObligation(..) = code
} else if let ObligationCauseCode::SpannedWhereClause(_, _)
| ObligationCauseCode::WhereClause(_)
| ObligationCauseCode::WhereClauseInExpr(..)
| ObligationCauseCode::SpannedWhereClauseInExpr(..) = code
{
try_borrowing(poly_trait_pred, &never_suggest_borrow)
} else {
@ -1644,10 +1642,8 @@ fn suggest_change_mut(
err: &mut Diag<'_>,
trait_pred: ty::PolyTraitPredicate<'tcx>,
) {
let points_at_arg = matches!(
obligation.cause.code(),
ObligationCauseCode::FunctionArgumentObligation { .. },
);
let points_at_arg =
matches!(obligation.cause.code(), ObligationCauseCode::FunctionArg { .. },);
let span = obligation.cause.span;
if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
@ -1953,7 +1949,7 @@ fn note_conflicting_fn_args(
found: Ty<'tcx>,
param_env: ty::ParamEnv<'tcx>,
) {
let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = cause else {
let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = cause else {
return;
};
let ty::FnPtr(expected) = expected.kind() else {
@ -2104,10 +2100,10 @@ fn note_conflicting_closure_bounds(
cause: &ObligationCauseCode<'tcx>,
err: &mut Diag<'tcx>,
) {
// First, look for an `ExprBindingObligation`, which means we can get
// First, look for an `SpannedWhereClauseInExpr`, which means we can get
// the uninstantiated predicate list of the called function. And check
// that the predicate that we failed to satisfy is a `Fn`-like trait.
if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = cause
if let ObligationCauseCode::SpannedWhereClauseInExpr(def_id, _, _, idx) = cause
&& let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
&& let Some(pred) = predicates.predicates.get(*idx)
&& let ty::ClauseKind::Trait(trait_pred) = pred.kind().skip_binder()
@ -2261,10 +2257,10 @@ fn maybe_note_obligation_cause_for_async_await<G: EmissionGuarantee>(
while let Some(code) = next_code {
debug!(?code);
match code {
ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
ObligationCauseCode::FunctionArg { parent_code, .. } => {
next_code = Some(parent_code);
}
ObligationCauseCode::ImplDerivedObligation(cause) => {
ObligationCauseCode::ImplDerived(cause) => {
let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
debug!(
parent_trait_ref = ?cause.derived.parent_trait_pred,
@ -2293,8 +2289,8 @@ fn maybe_note_obligation_cause_for_async_await<G: EmissionGuarantee>(
next_code = Some(&cause.derived.parent_code);
}
ObligationCauseCode::WellFormedDerivedObligation(derived_obligation)
| ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
ObligationCauseCode::WellFormedDerived(derived_obligation)
| ObligationCauseCode::BuiltinDerived(derived_obligation) => {
let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
debug!(
parent_trait_ref = ?derived_obligation.parent_trait_pred,
@ -2719,7 +2715,7 @@ fn note_obligation_cause_code<G: EmissionGuarantee, T>(
| ObligationCauseCode::MethodReceiver
| ObligationCauseCode::ReturnNoExpression
| ObligationCauseCode::UnifyReceiver(..)
| ObligationCauseCode::MiscObligation
| ObligationCauseCode::Misc
| ObligationCauseCode::WellFormed(..)
| ObligationCauseCode::MatchImpl(..)
| ObligationCauseCode::ReturnValue(_)
@ -2748,13 +2744,12 @@ fn note_obligation_cause_code<G: EmissionGuarantee, T>(
ObligationCauseCode::TupleElem => {
err.note("only the last element of a tuple may have a dynamically sized type");
}
ObligationCauseCode::ItemObligation(_)
| ObligationCauseCode::ExprItemObligation(..) => {
ObligationCauseCode::WhereClause(_) | ObligationCauseCode::WhereClauseInExpr(..) => {
// We hold the `DefId` of the item introducing the obligation, but displaying it
// doesn't add user usable information. It always point at an associated item.
}
ObligationCauseCode::BindingObligation(item_def_id, span)
| ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..) => {
ObligationCauseCode::SpannedWhereClause(item_def_id, span)
| ObligationCauseCode::SpannedWhereClauseInExpr(item_def_id, span, ..) => {
let item_name = tcx.def_path_str(item_def_id);
let short_item_name = with_forced_trimmed_paths!(tcx.def_path_str(item_def_id));
let mut multispan = MultiSpan::from(span);
@ -3175,7 +3170,7 @@ fn note_obligation_cause_code<G: EmissionGuarantee, T>(
ObligationCauseCode::SharedStatic => {
err.note("shared static variables must have a type that implements `Sync`");
}
ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
ObligationCauseCode::BuiltinDerived(ref data) => {
let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
let ty = parent_trait_ref.skip_binder().self_ty();
if parent_trait_ref.references_error() {
@ -3190,8 +3185,7 @@ fn note_obligation_cause_code<G: EmissionGuarantee, T>(
let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
false
} else {
if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
{
if let ObligationCauseCode::BuiltinDerived(data) = &*data.parent_code {
let parent_trait_ref =
self.resolve_vars_if_possible(data.parent_trait_pred);
let nested_ty = parent_trait_ref.skip_binder().self_ty();
@ -3297,7 +3291,7 @@ fn note_obligation_cause_code<G: EmissionGuarantee, T>(
});
}
}
ObligationCauseCode::ImplDerivedObligation(ref data) => {
ObligationCauseCode::ImplDerived(ref data) => {
let mut parent_trait_pred =
self.resolve_vars_if_possible(data.derived.parent_trait_pred);
let parent_def_id = parent_trait_pred.def_id();
@ -3367,9 +3361,7 @@ fn note_obligation_cause_code<G: EmissionGuarantee, T>(
if is_auto_trait {
// We don't want to point at the ADT saying "required because it appears within
// the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
&*data.parent_code
{
while let ObligationCauseCode::BuiltinDerived(derived) = &*data.parent_code {
let child_trait_ref =
self.resolve_vars_if_possible(derived.parent_trait_pred);
let child_def_id = child_trait_ref.def_id();
@ -3381,7 +3373,7 @@ fn note_obligation_cause_code<G: EmissionGuarantee, T>(
parent_trait_pred = child_trait_ref;
}
}
while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
while let ObligationCauseCode::ImplDerived(child) = &*data.parent_code {
// Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
let child_trait_pred =
self.resolve_vars_if_possible(child.derived.parent_trait_pred);
@ -3422,7 +3414,7 @@ fn note_obligation_cause_code<G: EmissionGuarantee, T>(
)
});
}
ObligationCauseCode::WellFormedDerivedObligation(ref data) => {
ObligationCauseCode::WellFormedDerived(ref data) => {
let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
let parent_predicate = parent_trait_ref;
// #74711: avoid a stack overflow
@ -3458,11 +3450,8 @@ fn note_obligation_cause_code<G: EmissionGuarantee, T>(
format!("required by a bound on the type alias `{}`", tcx.item_name(def_id)),
);
}
ObligationCauseCode::FunctionArgumentObligation {
arg_hir_id,
call_hir_id,
ref parent_code,
..
ObligationCauseCode::FunctionArg {
arg_hir_id, call_hir_id, ref parent_code, ..
} => {
self.note_function_argument_obligation(
body_id,
@ -3485,7 +3474,7 @@ fn note_obligation_cause_code<G: EmissionGuarantee, T>(
)
});
}
ObligationCauseCode::CompareImplItemObligation { trait_item_def_id, kind, .. } => {
ObligationCauseCode::CompareImplItem { trait_item_def_id, kind, .. } => {
let item_name = tcx.item_name(trait_item_def_id);
let msg = format!(
"the requirement `{predicate}` appears on the `impl`'s {kind} \
@ -3694,7 +3683,7 @@ fn suggest_dereferencing_index(
err: &mut Diag<'_>,
trait_pred: ty::PolyTraitPredicate<'tcx>,
) {
if let ObligationCauseCode::ImplDerivedObligation(_) = obligation.cause.code()
if let ObligationCauseCode::ImplDerived(_) = obligation.cause.code()
&& self
.tcx
.is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
@ -3811,7 +3800,7 @@ fn note_function_argument_obligation<G: EmissionGuarantee>(
// to an associated type (as seen from `trait_pred`) in the predicate. Like in
// trait_pred `S: Sum<<Self as Iterator>::Item>` and predicate `i32: Sum<&()>`
let mut type_diffs = vec![];
if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = parent_code
if let ObligationCauseCode::SpannedWhereClauseInExpr(def_id, _, _, idx) = parent_code
&& let Some(node_args) = typeck_results.node_args_opt(call_hir_id)
&& let where_clauses =
self.tcx.predicates_of(def_id).instantiate(self.tcx, node_args)
@ -4320,8 +4309,8 @@ fn suggest_convert_to_slice(
) {
// We can only suggest the slice coersion for function and binary operation arguments,
// since the suggestion would make no sense in turbofish or call
let (ObligationCauseCode::BinOp { .. }
| ObligationCauseCode::FunctionArgumentObligation { .. }) = obligation.cause.code()
let (ObligationCauseCode::BinOp { .. } | ObligationCauseCode::FunctionArg { .. }) =
obligation.cause.code()
else {
return;
};
@ -4407,7 +4396,7 @@ fn explain_hrtb_projection(
return;
}
if let ObligationCauseCode::FunctionArgumentObligation {
if let ObligationCauseCode::FunctionArg {
call_hir_id,
arg_hir_id,
parent_code: _,
@ -4967,7 +4956,7 @@ fn point_at_assoc_type_restriction<G: EmissionGuarantee>(
trait_name: &str,
predicate: ty::Predicate<'_>,
generics: &hir::Generics<'_>,
data: &ImplDerivedObligationCause<'_>,
data: &ImplDerivedCause<'_>,
) {
let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() else {
return;

View File

@ -391,7 +391,7 @@ fn report_selection_error(
}
}
if let ObligationCauseCode::CompareImplItemObligation {
if let ObligationCauseCode::CompareImplItem {
impl_item_def_id,
trait_item_def_id,
kind: _,
@ -1017,7 +1017,7 @@ fn emit_specialized_closure_kind_error(
if let Some((_, Some(parent))) = obligation.cause.code().parent() {
// If we have a derived obligation, then the parent will be a `AsyncFn*` goal.
trait_ref = parent.to_poly_trait_ref();
} else if let &ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } =
} else if let &ObligationCauseCode::FunctionArg { arg_hir_id, .. } =
obligation.cause.code()
&& let Some(typeck_results) = &self.typeck_results
&& let ty::Closure(closure_def_id, _) | ty::CoroutineClosure(closure_def_id, _) =
@ -1104,8 +1104,7 @@ fn fn_arg_obligation(
&self,
obligation: &PredicateObligation<'tcx>,
) -> Result<(), ErrorGuaranteed> {
if let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } =
obligation.cause.code()
if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
&& let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id)
&& let arg = arg.peel_borrows()
&& let hir::ExprKind::Path(hir::QPath::Resolved(
@ -1504,13 +1503,12 @@ fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>) -> ErrorGuara
}
match error.code {
FulfillmentErrorCode::SelectionError(ref selection_error) => self
.report_selection_error(
error.obligation.clone(),
&error.root_obligation,
selection_error,
),
FulfillmentErrorCode::ProjectionError(ref e) => {
FulfillmentErrorCode::Select(ref selection_error) => self.report_selection_error(
error.obligation.clone(),
&error.root_obligation,
selection_error,
),
FulfillmentErrorCode::Project(ref e) => {
self.report_projection_error(&error.obligation, e)
}
FulfillmentErrorCode::Ambiguity { overflow: None } => {
@ -1519,7 +1517,7 @@ fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>) -> ErrorGuara
FulfillmentErrorCode::Ambiguity { overflow: Some(suggest_increasing_limit) } => {
self.report_overflow_no_abort(error.obligation.clone(), suggest_increasing_limit)
}
FulfillmentErrorCode::SubtypeError(ref expected_found, ref err) => self
FulfillmentErrorCode::Subtype(ref expected_found, ref err) => self
.report_mismatched_types(
&error.obligation.cause,
expected_found.expected,
@ -1527,7 +1525,7 @@ fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>) -> ErrorGuara
*err,
)
.emit(),
FulfillmentErrorCode::ConstEquateError(ref expected_found, ref err) => {
FulfillmentErrorCode::ConstEquate(ref expected_found, ref err) => {
let mut diag = self.report_mismatched_consts(
&error.obligation.cause,
expected_found.expected,
@ -1535,10 +1533,10 @@ fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>) -> ErrorGuara
*err,
);
let code = error.obligation.cause.code().peel_derives().peel_match_impls();
if let ObligationCauseCode::BindingObligation(..)
| ObligationCauseCode::ItemObligation(..)
| ObligationCauseCode::ExprBindingObligation(..)
| ObligationCauseCode::ExprItemObligation(..) = code
if let ObligationCauseCode::SpannedWhereClause(..)
| ObligationCauseCode::WhereClause(..)
| ObligationCauseCode::SpannedWhereClauseInExpr(..)
| ObligationCauseCode::WhereClauseInExpr(..) = code
{
self.note_obligation_cause_code(
error.obligation.cause.body_id,
@ -1612,10 +1610,10 @@ fn report_projection_error(
let is_normalized_term_expected = !matches!(
obligation.cause.code().peel_derives(),
ObligationCauseCode::ItemObligation(_)
| ObligationCauseCode::BindingObligation(_, _)
| ObligationCauseCode::ExprItemObligation(..)
| ObligationCauseCode::ExprBindingObligation(..)
ObligationCauseCode::WhereClause(_)
| ObligationCauseCode::SpannedWhereClause(_, _)
| ObligationCauseCode::WhereClauseInExpr(..)
| ObligationCauseCode::SpannedWhereClauseInExpr(..)
| ObligationCauseCode::Coercion { .. }
);
@ -2212,7 +2210,7 @@ fn get_parent_trait_ref(
code: &ObligationCauseCode<'tcx>,
) -> Option<(Ty<'tcx>, Option<Span>)> {
match code {
ObligationCauseCode::BuiltinDerivedObligation(data) => {
ObligationCauseCode::BuiltinDerived(data) => {
let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
match self.get_parent_trait_ref(&data.parent_code) {
Some(t) => Some(t),
@ -2224,7 +2222,7 @@ fn get_parent_trait_ref(
}
}
}
ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
ObligationCauseCode::FunctionArg { parent_code, .. } => {
self.get_parent_trait_ref(parent_code)
}
_ => None,
@ -2447,8 +2445,8 @@ fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>) -> Erro
}
}
if let ObligationCauseCode::ItemObligation(def_id)
| ObligationCauseCode::ExprItemObligation(def_id, ..) = *obligation.cause.code()
if let ObligationCauseCode::WhereClause(def_id)
| ObligationCauseCode::WhereClauseInExpr(def_id, ..) = *obligation.cause.code()
{
self.suggest_fully_qualified_path(&mut err, def_id, span, trait_ref.def_id());
}
@ -2883,8 +2881,8 @@ fn suggest_unsized_bound_if_applicable(
else {
return;
};
let (ObligationCauseCode::BindingObligation(item_def_id, span)
| ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..)) =
let (ObligationCauseCode::SpannedWhereClause(item_def_id, span)
| ObligationCauseCode::SpannedWhereClauseInExpr(item_def_id, span, ..)) =
*obligation.cause.code().peel_derives()
else {
return;
@ -3004,7 +3002,7 @@ fn is_recursive_obligation(
obligated_types: &mut Vec<Ty<'tcx>>,
cause_code: &ObligationCauseCode<'tcx>,
) -> bool {
if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
if let ObligationCauseCode::BuiltinDerived(ref data) = cause_code {
let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
let self_ty = parent_trait_ref.skip_binder().self_ty();
if obligated_types.iter().any(|ot| ot == &self_ty) {
@ -3181,8 +3179,8 @@ fn add_tuple_trait_message(
ObligationCauseCode::RustCall => {
err.primary_message("functions with the \"rust-call\" ABI must take a single non-self tuple argument");
}
ObligationCauseCode::BindingObligation(def_id, _)
| ObligationCauseCode::ItemObligation(def_id)
ObligationCauseCode::SpannedWhereClause(def_id, _)
| ObligationCauseCode::WhereClause(def_id)
if self.tcx.is_fn_trait(*def_id) =>
{
err.code(E0059);
@ -3571,7 +3569,7 @@ fn report_not_const_evaluatable_error(
match self.tcx.sess.source_map().span_to_snippet(const_span) {
Ok(snippet) => {
let code = format!("[(); {snippet}{cast}]:");
let def_id = if let ObligationCauseCode::CompareImplItemObligation {
let def_id = if let ObligationCauseCode::CompareImplItem {
trait_item_def_id,
..
} = obligation.cause.code()

View File

@ -411,7 +411,7 @@ fn process_obligation(
ty::PredicateKind::ObjectSafe(trait_def_id) => {
if !self.selcx.tcx().check_is_object_safe(trait_def_id) {
ProcessResult::Error(FulfillmentErrorCode::SelectionError(Unimplemented))
ProcessResult::Error(FulfillmentErrorCode::Select(Unimplemented))
} else {
ProcessResult::Changed(vec![])
}
@ -435,7 +435,7 @@ fn process_obligation(
ty,
) {
Ok(inf_ok) => ProcessResult::Changed(mk_pending(inf_ok.into_obligations())),
Err(_) => ProcessResult::Error(FulfillmentErrorCode::SelectionError(
Err(_) => ProcessResult::Error(FulfillmentErrorCode::Select(
SelectionError::Unimplemented,
)),
}
@ -493,10 +493,7 @@ fn process_obligation(
Ok(Err(err)) => {
let expected_found =
ExpectedFound::new(subtype.a_is_expected, subtype.a, subtype.b);
ProcessResult::Error(FulfillmentErrorCode::SubtypeError(
expected_found,
err,
))
ProcessResult::Error(FulfillmentErrorCode::Subtype(expected_found, err))
}
}
}
@ -516,10 +513,7 @@ fn process_obligation(
Ok(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)),
Ok(Err(err)) => {
let expected_found = ExpectedFound::new(false, coerce.a, coerce.b);
ProcessResult::Error(FulfillmentErrorCode::SubtypeError(
expected_found,
err,
))
ProcessResult::Error(FulfillmentErrorCode::Subtype(expected_found, err))
}
}
}
@ -542,7 +536,7 @@ fn process_obligation(
Err(
e @ NotConstEvaluatable::MentionsParam
| e @ NotConstEvaluatable::Error(_),
) => ProcessResult::Error(FulfillmentErrorCode::SelectionError(
) => ProcessResult::Error(FulfillmentErrorCode::Select(
SelectionError::NotConstEvaluatable(e),
)),
}
@ -638,7 +632,7 @@ fn process_obligation(
ProcessResult::Changed(mk_pending(inf_ok.into_obligations()))
}
Err(err) => {
ProcessResult::Error(FulfillmentErrorCode::ConstEquateError(
ProcessResult::Error(FulfillmentErrorCode::ConstEquate(
ExpectedFound::new(true, c1, c2),
err,
))
@ -646,13 +640,11 @@ fn process_obligation(
}
}
(Err(ErrorHandled::Reported(reported, _)), _)
| (_, Err(ErrorHandled::Reported(reported, _))) => {
ProcessResult::Error(FulfillmentErrorCode::SelectionError(
SelectionError::NotConstEvaluatable(NotConstEvaluatable::Error(
reported.into(),
)),
))
}
| (_, Err(ErrorHandled::Reported(reported, _))) => ProcessResult::Error(
FulfillmentErrorCode::Select(SelectionError::NotConstEvaluatable(
NotConstEvaluatable::Error(reported.into()),
)),
),
(Err(ErrorHandled::TooGeneric(_)), _)
| (_, Err(ErrorHandled::TooGeneric(_))) => {
if c1.has_non_region_infer() || c2.has_non_region_infer() {
@ -660,7 +652,7 @@ fn process_obligation(
} else {
// Two different constants using generic parameters ~> error.
let expected_found = ExpectedFound::new(true, c1, c2);
ProcessResult::Error(FulfillmentErrorCode::ConstEquateError(
ProcessResult::Error(FulfillmentErrorCode::ConstEquate(
expected_found,
TypeError::ConstMismatch(expected_found),
))
@ -741,7 +733,7 @@ fn process_trait_obligation(
Err(selection_err) => {
debug!("selecting trait at depth {} yielded Err", obligation.recursion_depth);
ProcessResult::Error(FulfillmentErrorCode::SelectionError(selection_err))
ProcessResult::Error(FulfillmentErrorCode::Select(selection_err))
}
}
}
@ -793,7 +785,7 @@ fn process_projection_obligation(
project_obligation.with(tcx, project_obligation.predicate),
])),
ProjectAndUnifyResult::MismatchedProjectionTypes(e) => {
ProcessResult::Error(FulfillmentErrorCode::ProjectionError(e))
ProcessResult::Error(FulfillmentErrorCode::Project(e))
}
}
}

View File

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

View File

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

View File

@ -13,9 +13,9 @@
use super::util::closure_trait_ref_and_return_type;
use super::wf;
use super::{
ImplDerivedObligation, ImplDerivedObligationCause, Normalized, Obligation, ObligationCause,
ObligationCauseCode, Overflow, PolyTraitObligation, PredicateObligation, Selection,
SelectionError, SelectionResult, TraitQueryMode,
ImplDerivedCause, Normalized, Obligation, ObligationCause, ObligationCauseCode, Overflow,
PolyTraitObligation, PredicateObligation, Selection, SelectionError, SelectionResult,
TraitQueryMode,
};
use crate::infer::{InferCtxt, InferOk, TypeFreshener};
@ -2771,7 +2771,7 @@ fn impl_or_trait_obligations(
cause.clone()
} else {
cause.clone().derived_cause(parent_trait_pred, |derived| {
ImplDerivedObligation(Box::new(ImplDerivedObligationCause {
ObligationCauseCode::ImplDerived(Box::new(ImplDerivedCause {
derived,
impl_or_alias_def_id: def_id,
impl_def_predicate_index: Some(index),

View File

@ -2,6 +2,7 @@
use crate::traits;
use rustc_hir as hir;
use rustc_hir::lang_items::LangItem;
use rustc_infer::traits::ObligationCauseCode;
use rustc_middle::ty::{
self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
};
@ -333,7 +334,7 @@ fn normalize(self, infcx: &InferCtxt<'tcx>) -> Vec<traits::PredicateObligation<'
return self.out;
}
let cause = self.cause(traits::WellFormed(None));
let cause = self.cause(ObligationCauseCode::WellFormed(None));
let param_env = self.param_env;
let mut obligations = Vec::with_capacity(self.out.len());
for mut obligation in self.out {
@ -381,7 +382,7 @@ fn compute_trait_pred(&mut self, trait_pred: ty::TraitPredicate<'tcx>, elaborate
if let Some(parent_trait_pred) = predicate.to_opt_poly_trait_pred() {
cause = cause.derived_cause(
parent_trait_pred,
traits::ObligationCauseCode::WellFormedDerivedObligation,
traits::ObligationCauseCode::WellFormedDerived,
);
}
extend_cause_with_original_assoc_item_obligation(tcx, item, &mut cause, predicate);
@ -485,7 +486,7 @@ fn compute_inherent_projection(&mut self, data: ty::AliasTy<'tcx>) {
&mut traits::SelectionContext::new(self.infcx),
self.param_env,
data,
self.cause(traits::WellFormed(None)),
self.cause(ObligationCauseCode::WellFormed(None)),
self.recursion_depth,
&mut self.out,
);
@ -498,7 +499,7 @@ fn compute_inherent_projection(&mut self, data: ty::AliasTy<'tcx>) {
fn compute_projection_args(&mut self, args: GenericArgsRef<'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 depth = self.recursion_depth;
@ -565,9 +566,9 @@ fn nominal_obligations(
iter::zip(predicates, origins.into_iter().rev())
.map(|((pred, span), origin_def_id)| {
let code = if span.is_dummy() {
traits::ItemObligation(origin_def_id)
ObligationCauseCode::WhereClause(origin_def_id)
} else {
traits::BindingObligation(origin_def_id, span)
ObligationCauseCode::SpannedWhereClause(origin_def_id, span)
};
let cause = self.cause(code);
traits::Obligation::with_depth(
@ -626,7 +627,7 @@ fn from_object_ty(
self.out.reserve(implicit_bounds.len());
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 =
ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
self.out.push(traits::Obligation::with_depth(
@ -644,7 +645,7 @@ fn from_object_ty(
impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
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());
let tcx = self.tcx();
@ -673,22 +674,22 @@ fn visit_ty(&mut self, t: <TyCtxt<'tcx> as ty::Interner>::Ty) -> Self::Result {
ty::Infer(ty::FloatVar(_)) => {}
ty::Slice(subty) => {
self.require_sized(subty, traits::SliceOrArrayElem);
self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
}
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`.
}
ty::Pat(subty, _) => {
self.require_sized(subty, traits::MiscObligation);
self.require_sized(subty, ObligationCauseCode::Misc);
}
ty::Tuple(tys) => {
if let Some((_last, rest)) = tys.split_last() {
for &elem in rest {
self.require_sized(elem, traits::TupleElem);
self.require_sized(elem, ObligationCauseCode::TupleElem);
}
}
}
@ -728,7 +729,7 @@ fn visit_ty(&mut self, t: <TyCtxt<'tcx> as ty::Interner>::Ty) -> Self::Result {
ty::Ref(r, rty, _) => {
// WfReference
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(
tcx,
cause,
@ -825,7 +826,7 @@ fn visit_ty(&mut self, t: <TyCtxt<'tcx> as ty::Interner>::Ty) -> Self::Result {
if let Some(principal) = data.principal_def_id() {
self.out.push(traits::Obligation::with_depth(
tcx,
self.cause(traits::WellFormed(None)),
self.cause(ObligationCauseCode::WellFormed(None)),
self.recursion_depth,
self.param_env,
ty::Binder::dummy(ty::PredicateKind::ObjectSafe(principal)),
@ -847,7 +848,7 @@ fn visit_ty(&mut self, t: <TyCtxt<'tcx> as ty::Interner>::Ty) -> Self::Result {
// See also the comment on `fn obligations`, describing "livelock"
// prevention, which happens before this can be reached.
ty::Infer(_) => {
let cause = self.cause(traits::WellFormed(None));
let cause = self.cause(ObligationCauseCode::WellFormed(None));
self.out.push(traits::Obligation::with_depth(
tcx,
cause,
@ -863,7 +864,7 @@ fn visit_ty(&mut self, t: <TyCtxt<'tcx> as ty::Interner>::Ty) -> Self::Result {
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();
match c.kind() {
@ -875,7 +876,7 @@ fn visit_const(&mut self, c: <TyCtxt<'tcx> as ty::Interner>::Const) -> Self::Res
let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
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(
tcx,
cause,
@ -886,7 +887,7 @@ fn visit_const(&mut self, c: <TyCtxt<'tcx> as ty::Interner>::Const) -> Self::Res
}
}
ty::ConstKind::Infer(_) => {
let cause = self.cause(traits::WellFormed(None));
let cause = self.cause(ObligationCauseCode::WellFormed(None));
self.out.push(traits::Obligation::with_depth(
tcx,
@ -909,7 +910,7 @@ fn visit_const(&mut self, c: <TyCtxt<'tcx> as ty::Interner>::Const) -> Self::Res
let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
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(
tcx,
cause,
@ -933,7 +934,7 @@ fn visit_const(&mut self, c: <TyCtxt<'tcx> as ty::Interner>::Const) -> Self::Res
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");
}
}