Skip to content

Split TypeFolder and FallibleTypeFolder atwain #139768

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 16, 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
7 changes: 6 additions & 1 deletion compiler/rustc_infer/src/traits/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use std::hash::{Hash, Hasher};

use hir::def_id::LocalDefId;
use rustc_hir as hir;
use rustc_macros::{TypeFoldable, TypeVisitable};
use rustc_middle::traits::query::NoSolution;
use rustc_middle::traits::solve::Certainty;
pub use rustc_middle::traits::*;
Expand All @@ -35,9 +36,11 @@ use crate::infer::InferCtxt;
/// either identifying an `impl` (e.g., `impl Eq for i32`) that
/// satisfies the obligation, or else finding a bound that is in
/// scope. The eventual result is usually a `Selection` (defined below).
#[derive(Clone)]
#[derive(Clone, TypeFoldable, TypeVisitable)]
pub struct Obligation<'tcx, T> {
/// The reason we have to prove this thing.
#[type_foldable(identity)]
#[type_visitable(ignore)]
pub cause: ObligationCause<'tcx>,

/// The environment in which we should prove this thing.
Expand All @@ -51,6 +54,8 @@ pub struct Obligation<'tcx, T> {
/// If this goes over a certain threshold, we abort compilation --
/// in such cases, we can not say whether or not the predicate
/// holds for certain. Stupid halting problem; such a drag.
#[type_foldable(identity)]
#[type_visitable(ignore)]
pub recursion_depth: usize,
}

Expand Down
32 changes: 1 addition & 31 deletions compiler/rustc_infer/src/traits/structural_impls.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use std::fmt;

use rustc_middle::ty::{
self, FallibleTypeFolder, TyCtxt, TypeFoldable, TypeVisitable, TypeVisitor, try_visit,
};
use rustc_middle::ty;

use crate::traits;
use crate::traits::project::Normalized;
Expand Down Expand Up @@ -34,31 +32,3 @@ impl<'tcx> fmt::Debug for traits::MismatchedProjectionTypes<'tcx> {
write!(f, "MismatchedProjectionTypes({:?})", self.err)
}
}

///////////////////////////////////////////////////////////////////////////
// TypeFoldable implementations.

impl<'tcx, O: TypeFoldable<TyCtxt<'tcx>>> TypeFoldable<TyCtxt<'tcx>>
for traits::Obligation<'tcx, O>
{
fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
self,
folder: &mut F,
) -> Result<Self, F::Error> {
Ok(traits::Obligation {
cause: self.cause,
recursion_depth: self.recursion_depth,
predicate: self.predicate.try_fold_with(folder)?,
param_env: self.param_env.try_fold_with(folder)?,
})
}
}

impl<'tcx, O: TypeVisitable<TyCtxt<'tcx>>> TypeVisitable<TyCtxt<'tcx>>
for traits::Obligation<'tcx, O>
{
fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
try_visit!(self.predicate.visit_with(visitor));
self.param_env.visit_with(visitor)
}
}
60 changes: 43 additions & 17 deletions compiler/rustc_macros/src/type_foldable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,13 @@ pub(super) fn type_foldable_derive(mut s: synstructure::Structure<'_>) -> proc_m

s.add_bounds(synstructure::AddBounds::Generics);
s.bind_with(|_| synstructure::BindStyle::Move);
let body_fold = s.each_variant(|vi| {
let try_body_fold = s.each_variant(|vi| {
let bindings = vi.bindings();
vi.construct(|_, index| {
let bind = &bindings[index];

let mut fixed = false;

// retain value of fields with #[type_foldable(identity)]
bind.ast().attrs.iter().for_each(|x| {
if !x.path().is_ident("type_foldable") {
return;
}
let _ = x.parse_nested_meta(|nested| {
if nested.path.is_ident("identity") {
fixed = true;
}
Ok(())
});
});

if fixed {
if has_ignore_attr(&bind.ast().attrs, "type_foldable", "identity") {
bind.to_token_stream()
} else {
quote! {
Expand All @@ -44,15 +30,55 @@ pub(super) fn type_foldable_derive(mut s: synstructure::Structure<'_>) -> proc_m
})
});

let body_fold = s.each_variant(|vi| {
let bindings = vi.bindings();
vi.construct(|_, index| {
let bind = &bindings[index];

// retain value of fields with #[type_foldable(identity)]
if has_ignore_attr(&bind.ast().attrs, "type_foldable", "identity") {
bind.to_token_stream()
} else {
quote! {
::rustc_middle::ty::TypeFoldable::fold_with(#bind, __folder)
}
}
})
});

s.bound_impl(
quote!(::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>),
quote! {
fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(
self,
__folder: &mut __F
) -> Result<Self, __F::Error> {
Ok(match self { #body_fold })
Ok(match self { #try_body_fold })
}

fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(
self,
__folder: &mut __F
) -> Self {
match self { #body_fold }
}
},
)
}

fn has_ignore_attr(attrs: &[syn::Attribute], name: &'static str, meta: &'static str) -> bool {
let mut ignored = false;
attrs.iter().for_each(|attr| {
if !attr.path().is_ident(name) {
return;
}
let _ = attr.parse_nested_meta(|nested| {
if nested.path.is_ident(meta) {
ignored = true;
}
Ok(())
});
});

ignored
}
9 changes: 0 additions & 9 deletions compiler/rustc_middle/src/infer/canonical.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,6 @@ pub type CanonicalVarInfo<'tcx> = ir::CanonicalVarInfo<TyCtxt<'tcx>>;
pub type CanonicalVarValues<'tcx> = ir::CanonicalVarValues<TyCtxt<'tcx>>;
pub type CanonicalVarInfos<'tcx> = &'tcx List<CanonicalVarInfo<'tcx>>;

impl<'tcx> ty::TypeFoldable<TyCtxt<'tcx>> for CanonicalVarInfos<'tcx> {
fn try_fold_with<F: ty::FallibleTypeFolder<TyCtxt<'tcx>>>(
self,
folder: &mut F,
) -> Result<Self, F::Error> {
ty::util::fold_list(self, folder, |tcx, v| tcx.mk_canonical_var_infos(v))
}
}

/// When we canonicalize a value to form a query, we wind up replacing
/// various parts of it with canonical variables. This struct stores
/// those replaced bits to remember for when we process the query
Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_middle/src/mir/syntax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -931,6 +931,8 @@ pub enum TerminatorKind<'tcx> {
asm_macro: InlineAsmMacro,

/// The template for the inline assembly, with placeholders.
#[type_foldable(identity)]
Copy link
Member Author

Choose a reason for hiding this comment

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

Ideally we'd have most of these MIR fields marked as ignore/identity, but these are the only ones that we need to get rid of some annoying noop impls.

#[type_visitable(ignore)]
template: &'tcx [InlineAsmTemplatePiece],

/// The operands for the inline assembly, as `Operand`s or `Place`s.
Expand All @@ -941,6 +943,8 @@ pub enum TerminatorKind<'tcx> {

/// Source spans for each line of the inline assembly code. These are
/// used to map assembler errors back to the line in the source code.
#[type_foldable(identity)]
#[type_visitable(ignore)]
line_spans: &'tcx [Span],

/// Valid targets for the inline assembly.
Expand Down
47 changes: 46 additions & 1 deletion compiler/rustc_middle/src/ty/generic_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use smallvec::SmallVec;
use crate::ty::codec::{TyDecoder, TyEncoder};
use crate::ty::{
self, ClosureArgs, CoroutineArgs, CoroutineClosureArgs, FallibleTypeFolder, InlineConstArgs,
Lift, List, Ty, TyCtxt, TypeFoldable, TypeVisitable, TypeVisitor, VisitorResult,
Lift, List, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeVisitable, TypeVisitor, VisitorResult,
walk_visitable_list,
};

Expand Down Expand Up @@ -337,6 +337,14 @@ impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for GenericArg<'tcx> {
GenericArgKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
}
}

fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
match self.unpack() {
GenericArgKind::Lifetime(lt) => lt.fold_with(folder).into(),
GenericArgKind::Type(ty) => ty.fold_with(folder).into(),
GenericArgKind::Const(ct) => ct.fold_with(folder).into(),
}
}
}

impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for GenericArg<'tcx> {
Expand Down Expand Up @@ -606,6 +614,27 @@ impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for GenericArgsRef<'tcx> {
}
}
0 => Ok(self),
_ => ty::util::try_fold_list(self, folder, |tcx, v| tcx.mk_args(v)),
}
}

fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
// See justification for this behavior in `try_fold_with`.
match self.len() {
1 => {
let param0 = self[0].fold_with(folder);
if param0 == self[0] { self } else { folder.cx().mk_args(&[param0]) }
}
2 => {
let param0 = self[0].fold_with(folder);
let param1 = self[1].fold_with(folder);
if param0 == self[0] && param1 == self[1] {
self
} else {
folder.cx().mk_args(&[param0, param1])
}
}
0 => self,
_ => ty::util::fold_list(self, folder, |tcx, v| tcx.mk_args(v)),
}
}
Expand Down Expand Up @@ -641,6 +670,22 @@ impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for &'tcx ty::List<Ty<'tcx>> {
Ok(folder.cx().mk_type_list(&[param0, param1]))
}
}
_ => ty::util::try_fold_list(self, folder, |tcx, v| tcx.mk_type_list(v)),
}
}

fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
// See comment justifying behavior in `try_fold_with`.
match self.len() {
2 => {
let param0 = self[0].fold_with(folder);
let param1 = self[1].fold_with(folder);
if param0 == self[0] && param1 == self[1] {
self
} else {
folder.cx().mk_type_list(&[param0, param1])
}
}
_ => ty::util::fold_list(self, folder, |tcx, v| tcx.mk_type_list(v)),
}
}
Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_middle/src/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,13 @@ impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Term<'tcx> {
ty::TermKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
}
}

fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
match self.unpack() {
ty::TermKind::Ty(ty) => ty.fold_with(folder).into(),
ty::TermKind::Const(ct) => ct.fold_with(folder).into(),
}
}
}

impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Term<'tcx> {
Expand Down
Loading
Loading