Align Term methods with GenericArg methods

This commit is contained in:
Michael Goulet 2024-05-29 22:23:49 -04:00
parent 7c52d2db63
commit 273b990554
23 changed files with 46 additions and 36 deletions

View File

@ -263,7 +263,7 @@ fn push_debuginfo_type_name<'tcx>(
let ExistentialProjection { def_id: item_def_id, term, .. } = let ExistentialProjection { def_id: item_def_id, term, .. } =
tcx.instantiate_bound_regions_with_erased(bound); tcx.instantiate_bound_regions_with_erased(bound);
// FIXME(associated_const_equality): allow for consts here // FIXME(associated_const_equality): allow for consts here
(item_def_id, term.ty().unwrap()) (item_def_id, term.expect_type())
}) })
.collect(); .collect();

View File

@ -2281,7 +2281,7 @@ fn try_report_async_mismatch<'tcx>(
&& let Some(proj) = proj.no_bound_vars() && let Some(proj) = proj.no_bound_vars()
&& infcx.can_eq( && infcx.can_eq(
error.root_obligation.param_env, error.root_obligation.param_env,
proj.term.ty().unwrap(), proj.term.expect_type(),
impl_sig.output(), impl_sig.output(),
) )
{ {

View File

@ -267,7 +267,7 @@ fn report_mismatched_rpitit_signature<'tcx>(
.explicit_item_bounds(future_ty.def_id) .explicit_item_bounds(future_ty.def_id)
.iter_instantiated_copied(tcx, future_ty.args) .iter_instantiated_copied(tcx, future_ty.args)
.find_map(|(clause, _)| match clause.kind().no_bound_vars()? { .find_map(|(clause, _)| match clause.kind().no_bound_vars()? {
ty::ClauseKind::Projection(proj) => proj.term.ty(), ty::ClauseKind::Projection(proj) => proj.term.as_type(),
_ => None, _ => None,
}) })
else { else {

View File

@ -441,7 +441,9 @@ fn fn_sig_suggestion<'tcx>(
output = if let ty::Alias(_, alias_ty) = *output.kind() { output = if let ty::Alias(_, alias_ty) = *output.kind() {
tcx.explicit_item_super_predicates(alias_ty.def_id) tcx.explicit_item_super_predicates(alias_ty.def_id)
.iter_instantiated_copied(tcx, alias_ty.args) .iter_instantiated_copied(tcx, alias_ty.args)
.find_map(|(bound, _)| bound.as_projection_clause()?.no_bound_vars()?.term.ty()) .find_map(|(bound, _)| {
bound.as_projection_clause()?.no_bound_vars()?.term.as_type()
})
.unwrap_or_else(|| { .unwrap_or_else(|| {
span_bug!( span_bug!(
ident.span, ident.span,

View File

@ -485,7 +485,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}; };
// Since this is a return parameter type it is safe to unwrap. // Since this is a return parameter type it is safe to unwrap.
let ret_param_ty = projection.skip_binder().term.ty().unwrap(); let ret_param_ty = projection.skip_binder().term.expect_type();
let ret_param_ty = self.resolve_vars_if_possible(ret_param_ty); let ret_param_ty = self.resolve_vars_if_possible(ret_param_ty);
debug!(?ret_param_ty); debug!(?ret_param_ty);
@ -956,7 +956,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let output_ty = self.resolve_vars_if_possible(predicate.term); let output_ty = self.resolve_vars_if_possible(predicate.term);
debug!("deduce_future_output_from_projection: output_ty={:?}", output_ty); debug!("deduce_future_output_from_projection: output_ty={:?}", output_ty);
// This is a projection on a Fn trait so will always be a type. // This is a projection on a Fn trait so will always be a type.
Some(output_ty.ty().unwrap()) Some(output_ty.expect_type())
} }
/// Converts the types that the user supplied, in case that doing /// Converts the types that the user supplied, in case that doing

View File

@ -160,7 +160,7 @@ impl<'tcx> TypeckRootCtxt<'tcx> {
{ {
// If the projection predicate (Foo::Bar == X) has X as a non-TyVid, // If the projection predicate (Foo::Bar == X) has X as a non-TyVid,
// we need to make it into one. // we need to make it into one.
if let Some(vid) = predicate.term.ty().and_then(|ty| ty.ty_vid()) { if let Some(vid) = predicate.term.as_type().and_then(|ty| ty.ty_vid()) {
debug!("infer_var_info: {:?}.output = true", vid); debug!("infer_var_info: {:?}.output = true", vid);
infer_var_info.entry(vid).or_default().output = true; infer_var_info.entry(vid).or_default().output = true;
} }

View File

@ -425,7 +425,7 @@ impl<'tcx> InferCtxt<'tcx> {
ty::ClauseKind::Projection(projection_predicate) ty::ClauseKind::Projection(projection_predicate)
if projection_predicate.projection_term.def_id == item_def_id => if projection_predicate.projection_term.def_id == item_def_id =>
{ {
projection_predicate.term.ty() projection_predicate.term.as_type()
} }
_ => None, _ => None,
}) })

View File

@ -424,8 +424,8 @@ pub enum ValuePairs<'tcx> {
impl<'tcx> ValuePairs<'tcx> { impl<'tcx> ValuePairs<'tcx> {
pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> { pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
if let ValuePairs::Terms(ExpectedFound { expected, found }) = self if let ValuePairs::Terms(ExpectedFound { expected, found }) = self
&& let Some(expected) = expected.ty() && let Some(expected) = expected.as_type()
&& let Some(found) = found.ty() && let Some(found) = found.as_type()
{ {
Some((expected, found)) Some((expected, found))
} else { } else {

View File

@ -83,7 +83,7 @@ impl<'tcx> LateLintPass<'tcx> for OpaqueHiddenInferredBound {
}; };
// Only check types, since those are the only things that may // Only check types, since those are the only things that may
// have opaques in them anyways. // have opaques in them anyways.
let Some(proj_term) = proj.term.ty() else { return }; let Some(proj_term) = proj.term.as_type() else { return };
// HACK: `impl Trait<Assoc = impl Trait2>` from an RPIT is "ok"... // HACK: `impl Trait<Assoc = impl Trait2>` from an RPIT is "ok"...
if let ty::Alias(ty::Opaque, opaque_ty) = *proj_term.kind() if let ty::Alias(ty::Opaque, opaque_ty) = *proj_term.kind()

View File

@ -624,14 +624,22 @@ impl<'tcx> Term<'tcx> {
} }
} }
pub fn ty(&self) -> Option<Ty<'tcx>> { pub fn as_type(&self) -> Option<Ty<'tcx>> {
if let TermKind::Ty(ty) = self.unpack() { Some(ty) } else { None } if let TermKind::Ty(ty) = self.unpack() { Some(ty) } else { None }
} }
pub fn ct(&self) -> Option<Const<'tcx>> { pub fn expect_type(&self) -> Ty<'tcx> {
self.as_type().expect("expected a type, but found a const")
}
pub fn as_const(&self) -> Option<Const<'tcx>> {
if let TermKind::Const(c) = self.unpack() { Some(c) } else { None } if let TermKind::Const(c) = self.unpack() { Some(c) } else { None }
} }
pub fn expect_const(&self) -> Const<'tcx> {
self.as_const().expect("expected a const, but found a type")
}
pub fn into_arg(self) -> GenericArg<'tcx> { pub fn into_arg(self) -> GenericArg<'tcx> {
match self.unpack() { match self.unpack() {
TermKind::Ty(ty) => ty.into(), TermKind::Ty(ty) => ty.into(),

View File

@ -1077,7 +1077,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
} }
p!(")"); p!(")");
if let Some(ty) = return_ty.skip_binder().ty() { if let Some(ty) = return_ty.skip_binder().as_type() {
if !ty.is_unit() { if !ty.is_unit() {
p!(" -> ", print(return_ty)); p!(" -> ", print(return_ty));
} }
@ -1144,7 +1144,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
for (assoc_item_def_id, term) in assoc_items { for (assoc_item_def_id, term) in assoc_items {
// Skip printing `<{coroutine@} as Coroutine<_>>::Return` from async blocks, // Skip printing `<{coroutine@} as Coroutine<_>>::Return` from async blocks,
// unless we can find out what coroutine return type it comes from. // unless we can find out what coroutine return type it comes from.
let term = if let Some(ty) = term.skip_binder().ty() let term = if let Some(ty) = term.skip_binder().as_type()
&& let ty::Alias(ty::Projection, proj) = ty.kind() && let ty::Alias(ty::Projection, proj) = ty.kind()
&& let Some(assoc) = tcx.opt_associated_item(proj.def_id) && let Some(assoc) = tcx.opt_associated_item(proj.def_id)
&& assoc.trait_container(tcx) == tcx.lang_items().coroutine_trait() && assoc.trait_container(tcx) == tcx.lang_items().coroutine_trait()
@ -1322,7 +1322,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
p!(pretty_fn_sig( p!(pretty_fn_sig(
tys, tys,
false, false,
proj.skip_binder().term.ty().expect("Return type was a const") proj.skip_binder().term.as_type().expect("Return type was a const")
)); ));
resugared = true; resugared = true;
} }

View File

@ -726,7 +726,7 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceProjectionWith<'_, 'tcx> {
) )
.expect("expected to be able to unify goal projection with dyn's projection"), .expect("expected to be able to unify goal projection with dyn's projection"),
); );
proj.term.ty().unwrap() proj.term.expect_type()
} else { } else {
ty.super_fold_with(self) ty.super_fold_with(self)
} }

View File

@ -17,7 +17,7 @@ impl<'tcx> EvalCtxt<'_, InferCtxt<'tcx>> {
) -> QueryResult<'tcx> { ) -> QueryResult<'tcx> {
let tcx = self.interner(); let tcx = self.interner();
let opaque_ty = goal.predicate.alias; let opaque_ty = goal.predicate.alias;
let expected = goal.predicate.term.ty().expect("no such thing as an opaque const"); let expected = goal.predicate.term.as_type().expect("no such thing as an opaque const");
match (goal.param_env.reveal(), self.solver_mode()) { match (goal.param_env.reveal(), self.solver_mode()) {
(Reveal::UserFacing, SolverMode::Normal) => { (Reveal::UserFacing, SolverMode::Normal) => {

View File

@ -553,7 +553,7 @@ impl<'tcx> AutoTraitFinder<'tcx> {
} }
fn is_self_referential_projection(&self, p: ty::PolyProjectionPredicate<'tcx>) -> bool { fn is_self_referential_projection(&self, p: ty::PolyProjectionPredicate<'tcx>) -> bool {
if let Some(ty) = p.term().skip_binder().ty() { if let Some(ty) = p.term().skip_binder().as_type() {
matches!(ty.kind(), ty::Alias(ty::Projection, proj) if proj == &p.skip_binder().projection_term.expect_ty(self.tcx)) matches!(ty.kind(), ty::Alias(ty::Projection, proj) if proj == &p.skip_binder().projection_term.expect_ty(self.tcx))
} else { } else {
false false

View File

@ -1112,7 +1112,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
{ {
Some(( Some((
DefIdOrName::DefId(def_id), DefIdOrName::DefId(def_id),
pred.kind().rebind(proj.term.ty().unwrap()), pred.kind().rebind(proj.term.expect_type()),
pred.kind().rebind(args.as_slice()), pred.kind().rebind(args.as_slice()),
)) ))
} else { } else {
@ -1129,7 +1129,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
{ {
Some(( Some((
DefIdOrName::Name("trait object"), DefIdOrName::Name("trait object"),
pred.rebind(proj.term.ty().unwrap()), pred.rebind(proj.term.expect_type()),
pred.rebind(args.as_slice()), pred.rebind(args.as_slice()),
)) ))
} else { } else {
@ -1157,7 +1157,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
{ {
Some(( Some((
name, name,
pred.kind().rebind(proj.term.ty().unwrap()), pred.kind().rebind(proj.term.expect_type()),
pred.kind().rebind(args.as_slice()), pred.kind().rebind(args.as_slice()),
)) ))
} else { } else {
@ -3840,7 +3840,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
}) })
} else if let Some(where_pred) = where_pred.as_projection_clause() } else if let Some(where_pred) = where_pred.as_projection_clause()
&& let Some(failed_pred) = failed_pred.as_projection_clause() && let Some(failed_pred) = failed_pred.as_projection_clause()
&& let Some(found) = failed_pred.skip_binder().term.ty() && let Some(found) = failed_pred.skip_binder().term.as_type()
{ {
type_diffs = vec![Sorts(ty::error::ExpectedFound { type_diffs = vec![Sorts(ty::error::ExpectedFound {
expected: where_pred expected: where_pred

View File

@ -259,7 +259,7 @@ impl<'a, 'b, 'tcx> TypeFolder<TyCtxt<'tcx>> for AssocTypeNormalizer<'a, 'b, 'tcx
obligations.len = ?self.obligations.len(), obligations.len = ?self.obligations.len(),
"AssocTypeNormalizer: normalized type" "AssocTypeNormalizer: normalized type"
); );
normalized_ty.ty().unwrap() normalized_ty.expect_type()
} }
ty::Projection => { ty::Projection => {
@ -289,7 +289,7 @@ impl<'a, 'b, 'tcx> TypeFolder<TyCtxt<'tcx>> for AssocTypeNormalizer<'a, 'b, 'tcx
) )
.ok() .ok()
.flatten() .flatten()
.map(|term| term.ty().unwrap()) .map(|term| term.expect_type())
.map(|normalized_ty| { .map(|normalized_ty| {
PlaceholderReplacer::replace_placeholders( PlaceholderReplacer::replace_placeholders(
infcx, infcx,

View File

@ -946,7 +946,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
// since we don't actually use them. // since we don't actually use them.
&mut vec![], &mut vec![],
) )
.ty() .as_type()
.unwrap(); .unwrap();
if let ty::Dynamic(data, ..) = ty.kind() { data.principal() } else { None } if let ty::Dynamic(data, ..) = ty.kind() { data.principal() } else { None }

View File

@ -286,7 +286,7 @@ fn extend_cause_with_original_assoc_item_obligation<'tcx>(
// implemented, but rather from a "second order" obligation, where an associated // implemented, but rather from a "second order" obligation, where an associated
// type has a projection coming from another associated type. // type has a projection coming from another associated type.
// See `tests/ui/traits/assoc-type-in-superbad.rs` for an example. // See `tests/ui/traits/assoc-type-in-superbad.rs` for an example.
if let Some(term_ty) = proj.term.ty() if let Some(term_ty) = proj.term.as_type()
&& let Some(impl_item_span) = ty_to_impl_span(term_ty) && let Some(impl_item_span) = ty_to_impl_span(term_ty)
{ {
cause.span = impl_item_span; cause.span = impl_item_span;

View File

@ -58,7 +58,7 @@ fn normalize_canonicalized_projection_ty<'tcx>(
// FIXME(associated_const_equality): All users of normalize_canonicalized_projection_ty // FIXME(associated_const_equality): All users of normalize_canonicalized_projection_ty
// expected a type, but there is the possibility it could've been a const now. // expected a type, but there is the possibility it could've been a const now.
// Maybe change it to a Term later? // Maybe change it to a Term later?
Ok(NormalizationResult { normalized_ty: answer.ty().unwrap() }) Ok(NormalizationResult { normalized_ty: answer.expect_type() })
}, },
) )
} }

View File

@ -42,7 +42,7 @@ fn is_arg_ty_unified_in_fn<'tcx>(
cx.tcx.predicates_of(fn_id).predicates.iter().any(|(clause, _)| { cx.tcx.predicates_of(fn_id).predicates.iter().any(|(clause, _)| {
clause clause
.as_projection_clause() .as_projection_clause()
.and_then(|p| p.map_bound(|p| p.term.ty()).transpose()) .and_then(|p| p.map_bound(|p| p.term.as_type()).transpose())
.is_some_and(|ty| ty.skip_binder() == arg_ty_in_args) .is_some_and(|ty| ty.skip_binder() == arg_ty_in_args)
}) || fn_sig }) || fn_sig
.inputs() .inputs()

View File

@ -311,7 +311,7 @@ fn is_mixed_projection_predicate<'tcx>(
) -> bool { ) -> bool {
let generics = cx.tcx.generics_of(callee_def_id); let generics = cx.tcx.generics_of(callee_def_id);
// The predicate requires the projected type to equal a type parameter from the parent context. // The predicate requires the projected type to equal a type parameter from the parent context.
if let Some(term_ty) = projection_predicate.term.ty() if let Some(term_ty) = projection_predicate.term.as_type()
&& let ty::Param(term_param_ty) = term_ty.kind() && let ty::Param(term_param_ty) = term_ty.kind()
&& (term_param_ty.index as usize) < generics.parent_count && (term_param_ty.index as usize) < generics.parent_count
{ {
@ -370,7 +370,7 @@ fn replace_types<'tcx>(
if replaced.insert(param_ty.index) { if replaced.insert(param_ty.index) {
for projection_predicate in projection_predicates { for projection_predicate in projection_predicates {
if projection_predicate.projection_term.self_ty() == param_ty.to_ty(cx.tcx) if projection_predicate.projection_term.self_ty() == param_ty.to_ty(cx.tcx)
&& let Some(term_ty) = projection_predicate.term.ty() && let Some(term_ty) = projection_predicate.term.as_type()
&& let ty::Param(term_param_ty) = term_ty.kind() && let ty::Param(term_param_ty) = term_ty.kind()
{ {
let projection = projection_predicate let projection = projection_predicate

View File

@ -100,12 +100,12 @@ fn get_args_to_check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Ve
{ {
if ord_preds if ord_preds
.iter() .iter()
.any(|ord| Some(ord.self_ty()) == return_ty_pred.term.ty()) .any(|ord| Some(ord.self_ty()) == return_ty_pred.term.as_type())
{ {
args_to_check.push((i, "Ord".to_string())); args_to_check.push((i, "Ord".to_string()));
} else if partial_ord_preds } else if partial_ord_preds
.iter() .iter()
.any(|pord| pord.self_ty() == return_ty_pred.term.ty().unwrap()) .any(|pord| pord.self_ty() == return_ty_pred.term.expect_type())
{ {
args_to_check.push((i, "PartialOrd".to_string())); args_to_check.push((i, "PartialOrd".to_string()));
} }

View File

@ -750,7 +750,7 @@ pub fn ty_sig<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<ExprFnSig<'t
let output = bounds let output = bounds
.projection_bounds() .projection_bounds()
.find(|p| lang_items.fn_once_output().map_or(false, |id| id == p.item_def_id())) .find(|p| lang_items.fn_once_output().map_or(false, |id| id == p.item_def_id()))
.map(|p| p.map_bound(|p| p.term.ty().unwrap())); .map(|p| p.map_bound(|p| p.term.expect_type()));
Some(ExprFnSig::Trait(bound.map_bound(|b| b.args.type_at(0)), output, None)) Some(ExprFnSig::Trait(bound.map_bound(|b| b.args.type_at(0)), output, None))
}, },
_ => None, _ => None,
@ -798,7 +798,7 @@ fn sig_from_bounds<'tcx>(
// Multiple different fn trait impls. Is this even allowed? // Multiple different fn trait impls. Is this even allowed?
return None; return None;
} }
output = Some(pred.kind().rebind(p.term.ty().unwrap())); output = Some(pred.kind().rebind(p.term.expect_type()));
}, },
_ => (), _ => (),
} }
@ -836,7 +836,7 @@ fn sig_for_projection<'tcx>(cx: &LateContext<'tcx>, ty: AliasTy<'tcx>) -> Option
// Multiple different fn trait impls. Is this even allowed? // Multiple different fn trait impls. Is this even allowed?
return None; return None;
} }
output = pred.kind().rebind(p.term.ty()).transpose(); output = pred.kind().rebind(p.term.as_type()).transpose();
}, },
_ => (), _ => (),
} }