-
Notifications
You must be signed in to change notification settings - Fork 123
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
Support pointwise addition for arrays and tuples #343
Open
matthiasgoergens
wants to merge
2
commits into
JelteF:master
Choose a base branch
from
matthiasgoergens:matthias/derive-for-arrays
base: master
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 all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
There are no files selected for viewing
This file contains 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 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,28 +1,64 @@ | ||
use proc_macro2::TokenStream; | ||
use quote::quote; | ||
use syn::{Field, Ident, Index}; | ||
use syn::{Field, Ident, Index, Type, TypeArray, TypeTuple}; | ||
|
||
pub fn tuple_exprs(fields: &[&Field], method_ident: &Ident) -> Vec<TokenStream> { | ||
let mut exprs = vec![]; | ||
|
||
for i in 0..fields.len() { | ||
let i = Index::from(i); | ||
// generates `self.0.add(rhs.0)` | ||
let expr = quote! { self.#i.#method_ident(rhs.#i) }; | ||
exprs.push(expr); | ||
} | ||
exprs | ||
let fields: Vec<&Type> = fields.iter().map(|field| &field.ty).collect::<Vec<_>>(); | ||
inner_tuple_exprs("e! {}, &fields, method_ident) | ||
} | ||
|
||
pub fn struct_exprs(fields: &[&Field], method_ident: &Ident) -> Vec<TokenStream> { | ||
let mut exprs = vec![]; | ||
fields | ||
.iter() | ||
.map(|field| { | ||
// It's safe to unwrap because struct fields always have an identifier | ||
let field_path = field.ident.as_ref().unwrap(); | ||
elem_content("e! { .#field_path }, &field.ty, method_ident) | ||
}) | ||
.collect() | ||
} | ||
|
||
pub fn inner_tuple_exprs( | ||
field_path: &TokenStream, | ||
fields: &[&Type], | ||
method_ident: &Ident, | ||
) -> Vec<TokenStream> { | ||
fields | ||
.iter() | ||
.enumerate() | ||
.map(|(i, ty)| { | ||
let i = Index::from(i); | ||
elem_content("e! { #field_path.#i }, ty, method_ident) | ||
}) | ||
.collect() | ||
} | ||
|
||
pub fn elem_content( | ||
field_path: &TokenStream, | ||
ty: &Type, | ||
method_ident: &Ident, | ||
) -> TokenStream { | ||
match ty { | ||
Type::Array(TypeArray { elem, .. }) => { | ||
let fn_body = elem_content("e! {}, elem.as_ref(), method_ident); | ||
|
||
for field in fields { | ||
// It's safe to unwrap because struct fields always have an identifier | ||
let field_id = field.ident.as_ref().unwrap(); | ||
// generates `x: self.x.add(rhs.x)` | ||
let expr = quote! { self.#field_id.#method_ident(rhs.#field_id) }; | ||
exprs.push(expr) | ||
quote! { | ||
lhs #field_path.into_iter().zip(rhs #field_path.into_iter()) | ||
.map(|(lhs, rhs)| #fn_body) | ||
.collect::<Vec<_>>() | ||
.try_into() | ||
.unwrap_or_else(|_| unreachable!("Lengths should always match.")) | ||
} | ||
} | ||
Type::Tuple(TypeTuple { elems, .. }) => { | ||
let exprs = inner_tuple_exprs( | ||
field_path, | ||
&elems.iter().collect::<Vec<_>>(), | ||
method_ident, | ||
); | ||
quote! { (#(#exprs),*) } | ||
} | ||
// generates `lhs.x.add(rhs.x)` | ||
_ => quote! { lhs #field_path.#method_ident(rhs #field_path) }, | ||
} | ||
exprs | ||
} |
This file contains 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 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 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.
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.
@matthiasgoergens
Nah... this is not good, as is not zero-cost and forbids
no_std
usages.I wonder whether it could be solved with some additional add-hoc type machinery, which can be put into the
add
module of thederive_more
crate. We could provide either our customAddable
trait, or a#[repr(transparent)]
wrapper type implementing theAdd
trait fromcore
, and fill it with all the necessary blanket implementations for tuples and arrays. While in macro expansion, it would be only enough to call these implementations, which will do the job recursively and automatically.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.
Expanding this machinery to all types, we may support also the following case:
Which won't work if we try detecting the tuple/array type via macro.
However, I do think that the coherence won't allow this, as we will quickly hit the "upstream crates may add a new impl of trait
core::ops::Add
" error. Which, in turn, could be tried to overcome with autoref-based specialization.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.
Yeah... it seems that something like the following should work in general case, allowing us to consider type aliases naturally:
This way autoref-based specialization will try first to resolve our custom implementations for tuple and arrays, and fallback to
core::ops::Add
otherwise.