-
-
Notifications
You must be signed in to change notification settings - Fork 14.8k
Change derive macro for Eq to not impl Eq trait fn #153125
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
Open
KiChjang
wants to merge
6
commits into
rust-lang:main
Choose a base branch
from
KiChjang:derive-eq-const-assertion
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ad2da29
Change derive macro for Eq to not impl Eq trait fn
KiChjang aeb9f0f
Emit const fn in impl block instead of const item
KiChjang b5a6295
Emit const item block instead and use MutVisitor pattern
KiChjang c70ca54
Add dummy self pointer arg to emitted const fn
KiChjang 606910f
Ensure Self type paths are converted to its concrete types
KiChjang a0ec53f
Do not respan generic parameter declarations
KiChjang File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,13 +1,82 @@ | ||
| use rustc_ast::mut_visit::{self, MutVisitor}; | ||
| use rustc_ast::{self as ast, MetaItem, Safety}; | ||
| use rustc_data_structures::fx::FxHashSet; | ||
| use rustc_expand::base::{Annotatable, ExtCtxt}; | ||
| use rustc_span::{Span, sym}; | ||
| use rustc_span::{Ident, Span, kw, sym}; | ||
| use thin_vec::{ThinVec, thin_vec}; | ||
|
|
||
| use crate::deriving::generic::ty::*; | ||
| use crate::deriving::generic::*; | ||
| use crate::deriving::path_std; | ||
|
|
||
| struct ReplaceSelfTyVisitor(Box<ast::Ty>); | ||
| impl MutVisitor for ReplaceSelfTyVisitor { | ||
| fn visit_ty(&mut self, ty: &mut ast::Ty) { | ||
| if let ast::TyKind::Path(None, path) = &mut ty.kind | ||
| && let [segment] = &path.segments[..] | ||
| && *segment == kw::SelfUpper | ||
| { | ||
| *ty = *self.0.clone(); | ||
| } else { | ||
| mut_visit::walk_ty(self, ty); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| struct RespanGenericsVisitor(Span); | ||
| impl MutVisitor for RespanGenericsVisitor { | ||
| fn visit_generics(&mut self, generics: &mut ast::Generics) { | ||
| generics.where_clause.span = self.0.with_ctxt(generics.where_clause.span.ctxt()); | ||
| generics.span = self.0.with_ctxt(generics.span.ctxt()); | ||
| mut_visit::walk_generics(self, generics); | ||
| } | ||
| fn visit_where_predicate(&mut self, predicate: &mut ast::WherePredicate) { | ||
| predicate.span = self.0.with_ctxt(predicate.span.ctxt()); | ||
| mut_visit::walk_where_predicate(self, predicate); | ||
| } | ||
| fn visit_where_predicate_kind(&mut self, kind: &mut ast::WherePredicateKind) { | ||
| match kind { | ||
| ast::WherePredicateKind::BoundPredicate(bound_predicate) => { | ||
| bound_predicate.bounded_ty.span = | ||
| self.0.with_ctxt(bound_predicate.bounded_ty.span.ctxt()); | ||
| } | ||
| ast::WherePredicateKind::EqPredicate(eq_predicate) => { | ||
| eq_predicate.lhs_ty.span = self.0.with_ctxt(eq_predicate.lhs_ty.span.ctxt()); | ||
| eq_predicate.rhs_ty.span = self.0.with_ctxt(eq_predicate.rhs_ty.span.ctxt()); | ||
| } | ||
| ast::WherePredicateKind::RegionPredicate(_) => {} | ||
| } | ||
| mut_visit::walk_where_predicate_kind(self, kind); | ||
| } | ||
| fn visit_param_bound( | ||
| &mut self, | ||
| bound: &mut rustc_ast::GenericBound, | ||
| _ctxt: rustc_ast::visit::BoundKind, | ||
| ) { | ||
| match bound { | ||
| ast::GenericBound::Trait(poly_trait_ref) => { | ||
| poly_trait_ref.span = self.0.with_ctxt(poly_trait_ref.span.ctxt()); | ||
| } | ||
| ast::GenericBound::Outlives(_) => {} | ||
| ast::GenericBound::Use(_, _) => {} | ||
| } | ||
| ast::mut_visit::walk_param_bound(self, bound); | ||
| } | ||
| } | ||
|
|
||
| struct StripConstTraitBoundsVisitor; | ||
| impl MutVisitor for StripConstTraitBoundsVisitor { | ||
| fn visit_param_bound( | ||
| &mut self, | ||
| bound: &mut rustc_ast::GenericBound, | ||
| _ctxt: rustc_ast::visit::BoundKind, | ||
| ) { | ||
| if let ast::GenericBound::Trait(poly_trait_ref) = bound { | ||
| poly_trait_ref.modifiers.constness = ast::BoundConstness::Never; | ||
| } | ||
| mut_visit::walk_param_bound(self, bound); | ||
| } | ||
| } | ||
|
|
||
| pub(crate) fn expand_deriving_eq( | ||
| cx: &ExtCtxt<'_>, | ||
| span: Span, | ||
|
|
@@ -18,45 +87,122 @@ pub(crate) fn expand_deriving_eq( | |
| ) { | ||
| let span = cx.with_def_site_ctxt(span); | ||
|
|
||
| let mut fn_generics = ast::Generics { span, ..Default::default() }; | ||
| let mut self_ty = None; | ||
|
|
||
| let trait_def = TraitDef { | ||
| span, | ||
| path: path_std!(cmp::Eq), | ||
| skip_path_as_bound: false, | ||
| needs_copy_as_bound_if_packed: true, | ||
| additional_bounds: Vec::new(), | ||
| supports_unions: true, | ||
| methods: vec![MethodDef { | ||
| name: sym::assert_fields_are_eq, | ||
| generics: Bounds::empty(), | ||
| explicit_self: true, | ||
| nonself_args: vec![], | ||
| ret_ty: Unit, | ||
| attributes: thin_vec![ | ||
| // This method will never be called, so doing codegen etc. for it is unnecessary. | ||
| // We prevent this by adding `#[inline]`, which improves compile-time. | ||
| cx.attr_word(sym::inline, span), | ||
| cx.attr_nested_word(sym::doc, sym::hidden, span), | ||
| cx.attr_nested_word(sym::coverage, sym::off, span), | ||
| ], | ||
| fieldless_variants_strategy: FieldlessVariantsStrategy::Unify, | ||
| combine_substructure: combine_substructure(Box::new(|a, b, c| { | ||
| cs_total_eq_assert(a, b, c) | ||
| })), | ||
| }], | ||
| methods: Vec::new(), | ||
| associated_types: Vec::new(), | ||
| is_const, | ||
| is_staged_api_crate: cx.ecfg.features.staged_api(), | ||
| safety: Safety::Default, | ||
| document: true, | ||
| }; | ||
| trait_def.expand_ext(cx, mitem, item, push, true) | ||
| trait_def.expand_ext( | ||
| cx, | ||
| mitem, | ||
| item, | ||
| &mut |mut a| { | ||
| let Annotatable::Item(item) = &mut a else { | ||
| unreachable!("should have emitted an Item in trait_def.expand_ext"); | ||
| }; | ||
| let ast::ItemKind::Impl(imp) = &mut item.kind else { | ||
| unreachable!("should have emitted an Impl in trait_def.expand_ext"); | ||
| }; | ||
| use ast::mut_visit::MutVisitor; | ||
| RespanGenericsVisitor(span).visit_generics(&mut imp.generics); | ||
| fn_generics = imp.generics.clone(); | ||
| self_ty = Some(imp.self_ty.clone()); | ||
| push(a) | ||
| }, | ||
| true, | ||
| ); | ||
|
|
||
| let self_ty = | ||
| self_ty.unwrap_or_else(|| cx.dcx().span_bug(span, "missing self type in `derive(Eq)`")); | ||
| let assert_stmts = eq_assert_stmts_from_item(cx, span, item, ReplaceSelfTyVisitor(self_ty)); | ||
|
|
||
| // Skip generating `assert_fields_are_eq` impl if there are no assertions to make | ||
| if assert_stmts.is_empty() { | ||
| return; | ||
| } | ||
|
|
||
| StripConstTraitBoundsVisitor.visit_generics(&mut fn_generics); | ||
| push(Annotatable::Item(expand_const_item_block(cx, span, fn_generics, assert_stmts))); | ||
| } | ||
|
|
||
| fn expand_const_item_block( | ||
| cx: &ExtCtxt<'_>, | ||
| span: Span, | ||
| fn_generics: ast::Generics, | ||
| assert_stmts: ThinVec<ast::Stmt>, | ||
| ) -> Box<ast::Item> { | ||
| cx.item( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. A brief example of the kind of code being generated would be helpful here. |
||
| span, | ||
| ast::AttrVec::new(), | ||
| ast::ItemKind::ConstBlock(ast::ConstBlockItem { | ||
| span, | ||
| id: ast::DUMMY_NODE_ID, | ||
| block: cx.block( | ||
| span, | ||
| thin_vec![ast::Stmt { | ||
| span, | ||
| id: ast::DUMMY_NODE_ID, | ||
| kind: ast::StmtKind::Item(Box::new(ast::Item { | ||
| span, | ||
| id: ast::DUMMY_NODE_ID, | ||
| attrs: thin_vec![ | ||
| cx.attr_nested_word(sym::doc, sym::hidden, span), | ||
| cx.attr_nested_word(sym::coverage, sym::off, span), | ||
| // This function will never be called, so doing codegen etc. for it is | ||
| // unnecessary. We prevent this by adding `#[inline]`, which improves | ||
| // compile-time. | ||
| cx.attr_word(sym::inline, span), | ||
| ], | ||
| vis: ast::Visibility { | ||
| kind: ast::VisibilityKind::Inherited, | ||
| span, | ||
| tokens: None, | ||
| }, | ||
| tokens: None, | ||
| kind: ast::ItemKind::Fn(Box::new(ast::Fn { | ||
| defaultness: ast::Defaultness::Implicit, | ||
| ident: Ident::new(sym::assert_fields_are_eq, span), | ||
| generics: fn_generics, | ||
| sig: ast::FnSig { | ||
| header: ast::FnHeader { | ||
| constness: ast::Const::Yes(span), | ||
| coroutine_kind: None, | ||
| safety: ast::Safety::Default, | ||
| ext: ast::Extern::None, | ||
| }, | ||
| decl: cx.fn_decl(ThinVec::new(), ast::FnRetTy::Default(span)), | ||
| span, | ||
| }, | ||
| contract: None, | ||
| define_opaque: None, | ||
| body: Some(cx.block(span, assert_stmts)), | ||
| eii_impls: ThinVec::new(), | ||
| })) | ||
| })) | ||
| },], | ||
| ), | ||
| }), | ||
| ) | ||
| } | ||
|
|
||
| fn cs_total_eq_assert( | ||
| fn eq_assert_stmts_from_item( | ||
| cx: &ExtCtxt<'_>, | ||
| trait_span: Span, | ||
| substr: &Substructure<'_>, | ||
| ) -> BlockOrExpr { | ||
| span: Span, | ||
| item: &Annotatable, | ||
| mut replace_self_ty: ReplaceSelfTyVisitor, | ||
| ) -> ThinVec<ast::Stmt> { | ||
| let mut stmts = ThinVec::new(); | ||
| let mut seen_type_names = FxHashSet::default(); | ||
| let mut process_variant = |variant: &ast::VariantData| { | ||
|
|
@@ -69,28 +215,36 @@ fn cs_total_eq_assert( | |
| { | ||
| // Already produced an assertion for this type. | ||
| } else { | ||
| use ast::mut_visit::MutVisitor; | ||
| let mut field_ty = field.ty.clone(); | ||
| replace_self_ty.visit_ty(&mut field_ty); | ||
| // let _: AssertParamIsEq<FieldTy>; | ||
| super::assert_ty_bounds( | ||
| cx, | ||
| &mut stmts, | ||
| field.ty.clone(), | ||
| field_ty, | ||
| field.span, | ||
| &[sym::cmp, sym::AssertParamIsEq], | ||
| ); | ||
| } | ||
| } | ||
| }; | ||
|
|
||
| match *substr.fields { | ||
| StaticStruct(vdata, ..) => { | ||
| process_variant(vdata); | ||
| } | ||
| StaticEnum(enum_def, ..) => { | ||
| for variant in &enum_def.variants { | ||
| process_variant(&variant.data); | ||
| match item { | ||
| Annotatable::Item(item) => match &item.kind { | ||
| ast::ItemKind::Struct(_, _, vdata) => { | ||
| process_variant(vdata); | ||
| } | ||
| } | ||
| _ => cx.dcx().span_bug(trait_span, "unexpected substructure in `derive(Eq)`"), | ||
| ast::ItemKind::Enum(_, _, enum_def) => { | ||
| for variant in &enum_def.variants { | ||
| process_variant(&variant.data); | ||
| } | ||
| } | ||
| ast::ItemKind::Union(_, _, vdata) => { | ||
| process_variant(vdata); | ||
| } | ||
| _ => cx.dcx().span_bug(span, "unexpected item in `derive(Eq)`"), | ||
| }, | ||
| _ => cx.dcx().span_bug(span, "unexpected item in `derive(Eq)`"), | ||
| } | ||
| BlockOrExpr::new_stmts(stmts) | ||
| stmts | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Blank line after the struct, and likewise below.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Also, the three visitors need a brief comment explaining what they are doing and why.