Skip to content

replace GenericArg with Term where applicable #140320

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions compiler/rustc_hir_analysis/src/check/compare_impl_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -379,13 +379,13 @@ fn compare_method_predicate_entailment<'tcx>(
// Annoyingly, asking for the WF predicates of an array (with an unevaluated const (only?))
// will give back the well-formed predicate of the same array.
let mut wf_args_seen: FxHashSet<_> = wf_args.iter().copied().collect();
while let Some(arg) = wf_args.pop() {
while let Some(term) = wf_args.pop() {
let Some(obligations) = rustc_trait_selection::traits::wf::obligations(
infcx,
param_env,
impl_m_def_id,
0,
arg,
term,
impl_m_span,
) else {
continue;
Expand All @@ -402,9 +402,9 @@ fn compare_method_predicate_entailment<'tcx>(
| ty::ClauseKind::TypeOutlives(..)
| ty::ClauseKind::Projection(..),
) => ocx.register_obligation(obligation),
ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg)) => {
if wf_args_seen.insert(arg) {
wf_args.push(arg)
ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(term)) => {
if wf_args_seen.insert(term) {
wf_args.push(term)
}
}
_ => {}
Expand Down
11 changes: 3 additions & 8 deletions compiler/rustc_hir_analysis/src/check/wfcheck.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,7 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
)
}

fn register_wf_obligation(
&self,
span: Span,
loc: Option<WellFormedLoc>,
arg: ty::GenericArg<'tcx>,
) {
fn register_wf_obligation(&self, span: Span, loc: Option<WellFormedLoc>, term: ty::Term<'tcx>) {
let cause = traits::ObligationCause::new(
span,
self.body_def_id,
Expand All @@ -91,7 +86,7 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
self.tcx(),
cause,
self.param_env,
ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg))),
ty::ClauseKind::WellFormed(term),
));
}
}
Expand Down Expand Up @@ -1486,7 +1481,7 @@ fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id
tcx.def_span(param.def_id),
matches!(param.kind, GenericParamDefKind::Type { .. })
.then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
default,
default.as_term().unwrap(),
);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -374,9 +374,12 @@ fn check_predicates<'tcx>(

// Include the well-formed predicates of the type parameters of the impl.
for arg in tcx.impl_trait_ref(impl1_def_id).unwrap().instantiate_identity().args {
let Some(term) = arg.as_term() else {
continue;
};
let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
let obligations =
wf::obligations(infcx, tcx.param_env(impl1_def_id), impl1_def_id, 0, arg, span)
wf::obligations(infcx, tcx.param_env(impl1_def_id), impl1_def_id, 0, term, span)
.unwrap();

assert!(!obligations.has_infer());
Expand Down
43 changes: 15 additions & 28 deletions compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ use rustc_infer::infer::{DefineOpaqueTypes, InferResult};
use rustc_lint::builtin::SELF_CONSTRUCTOR_FROM_OUTER_ITEM;
use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability};
use rustc_middle::ty::{
self, AdtKind, CanonicalUserType, GenericArgKind, GenericArgsRef, GenericParamDefKind,
IsIdentity, Ty, TyCtxt, TypeFoldable, TypeVisitable, TypeVisitableExt, UserArgs, UserSelfTy,
self, AdtKind, CanonicalUserType, GenericArgsRef, GenericParamDefKind, IsIdentity, Ty, TyCtxt,
TypeFoldable, TypeVisitable, TypeVisitableExt, UserArgs, UserSelfTy,
};
use rustc_middle::{bug, span_bug};
use rustc_session::lint;
Expand Down Expand Up @@ -573,7 +573,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// Registers an obligation for checking later, during regionck, that `arg` is well-formed.
pub(crate) fn register_wf_obligation(
&self,
arg: ty::GenericArg<'tcx>,
term: ty::Term<'tcx>,
span: Span,
code: traits::ObligationCauseCode<'tcx>,
) {
Expand All @@ -583,16 +583,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self.tcx,
cause,
self.param_env,
ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg))),
ty::ClauseKind::WellFormed(term),
));
}

/// Registers obligations that all `args` are well-formed.
pub(crate) fn add_wf_bounds(&self, args: GenericArgsRef<'tcx>, span: Span) {
for arg in args.iter().filter(|arg| {
matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
}) {
self.register_wf_obligation(arg, span, ObligationCauseCode::WellFormed(None));
for term in args.iter().filter_map(ty::GenericArg::as_term) {
self.register_wf_obligation(term, span, ObligationCauseCode::WellFormed(None));
}
}

Expand Down Expand Up @@ -1320,27 +1318,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
infer_args: bool,
) -> ty::GenericArg<'tcx> {
let tcx = self.fcx.tcx();
match param.kind {
GenericParamDefKind::Lifetime => self
.fcx
.re_infer(
self.span,
rustc_hir_analysis::hir_ty_lowering::RegionInferReason::Param(param),
)
.into(),
GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
if !infer_args && let Some(default) = param.default_value(tcx) {
// If we have a default, then it doesn't matter that we're not inferring
// the type/const arguments: We provide the default where any is missing.
return default.instantiate(tcx, preceding_args);
}
// If no type/const arguments were provided, we have to infer them.
// This case also occurs as a result of some malformed input, e.g.,
// a lifetime argument being given instead of a type/const parameter.
// Using inference instead of `Error` gives better error messages.
self.fcx.var_for_def(self.span, param)
}
if !infer_args && let Some(default) = param.default_value(tcx) {
// If we have a default, then it doesn't matter that we're not inferring
// the type/const arguments: We provide the default where any is missing.
return default.instantiate(tcx, preceding_args);
}
// If no type/const arguments were provided, we have to infer them.
// This case also occurs as a result of some malformed input, e.g.,
// a lifetime argument being given instead of a type/const parameter.
// Using inference instead of `Error` gives better error messages.
self.fcx.var_for_def(self.span, param)
}
}

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_hir_typeck/src/writeback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -863,7 +863,7 @@ impl<'cx, 'tcx> Resolver<'cx, 'tcx> {
Resolver { fcx, span, body, nested_goals, should_normalize }
}

fn report_error(&self, p: impl Into<ty::GenericArg<'tcx>>) -> ErrorGuaranteed {
fn report_error(&self, p: impl Into<ty::Term<'tcx>>) -> ErrorGuaranteed {
if let Some(guar) = self.fcx.tainted_by_errors() {
guar
} else {
Expand All @@ -887,7 +887,7 @@ impl<'cx, 'tcx> Resolver<'cx, 'tcx> {
new_err: impl Fn(TyCtxt<'tcx>, ErrorGuaranteed) -> T,
) -> T
where
T: Into<ty::GenericArg<'tcx>> + TypeSuperFoldable<TyCtxt<'tcx>> + Copy,
T: Into<ty::Term<'tcx>> + TypeSuperFoldable<TyCtxt<'tcx>> + Copy,
{
let tcx = self.fcx.tcx;
// We must deeply normalize in the new solver, since later lints expect
Expand Down
16 changes: 13 additions & 3 deletions compiler/rustc_infer/src/infer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ use rustc_middle::traits::solve::Goal;
use rustc_middle::ty::error::{ExpectedFound, TypeError};
use rustc_middle::ty::{
self, BoundVarReplacerDelegate, ConstVid, FloatVid, GenericArg, GenericArgKind, GenericArgs,
GenericArgsRef, GenericParamDefKind, InferConst, IntVid, PseudoCanonicalInput, Ty, TyCtxt,
TyVid, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypingEnv,
TypingMode, fold_regions,
GenericArgsRef, GenericParamDefKind, InferConst, IntVid, PseudoCanonicalInput, Term, TermKind,
Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable,
TypeVisitableExt, TypingEnv, TypingMode, fold_regions,
};
use rustc_span::{Span, Symbol};
use snapshot::undo_log::InferCtxtUndoLogs;
Expand Down Expand Up @@ -1401,6 +1401,16 @@ impl<'tcx> TyOrConstInferVar {
}
}

/// Tries to extract an inference variable from a type or a constant, returns `None`
/// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
/// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
pub fn maybe_from_term(term: Term<'tcx>) -> Option<Self> {
match term.unpack() {
TermKind::Ty(ty) => Self::maybe_from_ty(ty),
TermKind::Const(ct) => Self::maybe_from_const(ct),
}
}

/// Tries to extract an inference variable from a type, returns `None`
/// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
Expand Down
17 changes: 13 additions & 4 deletions compiler/rustc_middle/src/ty/generic_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,17 +250,17 @@ impl<'tcx> GenericArg<'tcx> {
}

#[inline]
pub fn as_type(self) -> Option<Ty<'tcx>> {
pub fn as_region(self) -> Option<ty::Region<'tcx>> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why did you flip these lol

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

region, type, const is the correct order :<

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

definitely do not agree. ty region const is the order in folders.

match self.unpack() {
GenericArgKind::Type(ty) => Some(ty),
GenericArgKind::Lifetime(re) => Some(re),
_ => None,
}
}

#[inline]
pub fn as_region(self) -> Option<ty::Region<'tcx>> {
pub fn as_type(self) -> Option<Ty<'tcx>> {
match self.unpack() {
GenericArgKind::Lifetime(re) => Some(re),
GenericArgKind::Type(ty) => Some(ty),
_ => None,
}
}
Expand All @@ -273,6 +273,15 @@ impl<'tcx> GenericArg<'tcx> {
}
}

#[inline]
pub fn as_term(self) -> Option<ty::Term<'tcx>> {
match self.unpack() {
GenericArgKind::Lifetime(_) => None,
GenericArgKind::Type(ty) => Some(ty.into()),
GenericArgKind::Const(ct) => Some(ct.into()),
}
}

/// Unpack the `GenericArg` as a region when it is known certainly to be a region.
pub fn expect_region(self) -> ty::Region<'tcx> {
self.as_region().unwrap_or_else(|| bug!("expected a region, but found another kind"))
Expand Down
15 changes: 15 additions & 0 deletions compiler/rustc_middle/src/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ use crate::ty::codec::{TyDecoder, TyEncoder};
pub use crate::ty::diagnostics::*;
use crate::ty::fast_reject::SimplifiedType;
use crate::ty::util::Discr;
use crate::ty::walk::TypeWalker;

pub mod abstract_const;
pub mod adjustment;
Expand Down Expand Up @@ -631,6 +632,20 @@ impl<'tcx> Term<'tcx> {
TermKind::Const(ct) => ct.is_ct_infer(),
}
}

/// Iterator that walks `self` and any types reachable from
/// `self`, in depth-first order. Note that just walks the types
/// that appear in `self`, it does not descend into the fields of
/// structs or variants. For example:
///
/// ```text
/// isize => { isize }
/// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
/// [isize] => { [isize], isize }
/// ```
pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
TypeWalker::new(self.into())
}
}

const TAG_MASK: usize = 0b11;
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/print/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3247,7 +3247,7 @@ define_print! {
ty::ClauseKind::ConstArgHasType(ct, ty) => {
p!("the constant `", print(ct), "` has type `", print(ty), "`")
},
ty::ClauseKind::WellFormed(arg) => p!(print(arg), " well-formed"),
ty::ClauseKind::WellFormed(term) => p!(print(term), " well-formed"),
ty::ClauseKind::ConstEvaluatable(ct) => {
p!("the constant `", print(ct), "` can be evaluated")
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_next_trait_solver/src/delegate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub trait SolverDelegate: Deref<Target = Self::Infcx> + Sized {
fn well_formed_goals(
&self,
param_env: <Self::Interner as Interner>::ParamEnv,
arg: <Self::Interner as Interner>::GenericArg,
term: <Self::Interner as Interner>::Term,
) -> Option<Vec<Goal<Self::Interner, <Self::Interner as Interner>::Predicate>>>;

fn clone_opaque_types_for_query_response(
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -533,8 +533,8 @@ where
ty::PredicateKind::DynCompatible(trait_def_id) => {
self.compute_dyn_compatible_goal(trait_def_id)
}
ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg)) => {
self.compute_well_formed_goal(Goal { param_env, predicate: arg })
ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(term)) => {
self.compute_well_formed_goal(Goal { param_env, predicate: term })
}
ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(ct)) => {
self.compute_const_evaluatable_goal(Goal { param_env, predicate: ct })
Expand Down Expand Up @@ -1012,9 +1012,9 @@ where
pub(super) fn well_formed_goals(
&self,
param_env: I::ParamEnv,
arg: I::GenericArg,
term: I::Term,
) -> Option<Vec<Goal<I, I::Predicate>>> {
self.delegate.well_formed_goals(param_env, arg)
self.delegate.well_formed_goals(param_env, term)
}

pub(super) fn trait_ref_is_knowable(
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_next_trait_solver/src/solve/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ where
}

#[instrument(level = "trace", skip(self))]
fn compute_well_formed_goal(&mut self, goal: Goal<I, I::GenericArg>) -> QueryResult<I> {
fn compute_well_formed_goal(&mut self, goal: Goal<I, I::Term>) -> QueryResult<I> {
match self.well_formed_goals(goal.param_env, goal.predicate) {
Some(goals) => {
self.add_goals(GoalSource::Misc, goals);
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_privacy/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ where
ty.visit_with(self)
}
ty::ClauseKind::ConstEvaluatable(ct) => ct.visit_with(self),
ty::ClauseKind::WellFormed(arg) => arg.visit_with(self),
ty::ClauseKind::WellFormed(term) => term.visit_with(self),
}
}

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_smir/src/rustc_smir/convert/ty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -638,8 +638,8 @@ impl<'tcx> Stable<'tcx> for ty::ClauseKind<'tcx> {
const_.stable(tables),
ty.stable(tables),
),
ClauseKind::WellFormed(generic_arg) => {
stable_mir::ty::ClauseKind::WellFormed(generic_arg.unpack().stable(tables))
ClauseKind::WellFormed(term) => {
stable_mir::ty::ClauseKind::WellFormed(term.unpack().stable(tables))
}
ClauseKind::ConstEvaluatable(const_) => {
stable_mir::ty::ClauseKind::ConstEvaluatable(const_.stable(tables))
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_smir/src/stable_mir/ty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1462,7 +1462,7 @@ pub enum ClauseKind {
TypeOutlives(TypeOutlivesPredicate),
Projection(ProjectionPredicate),
ConstArgHasType(TyConst, Ty),
WellFormed(GenericArgKind),
WellFormed(TermKind),
ConstEvaluatable(TyConst),
}

Expand Down
Loading
Loading