-
Notifications
You must be signed in to change notification settings - Fork 40
Add a derive macro for Prism #101
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
Changes from all commits
Commits
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 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
[package] | ||
name = "druid-widget-nursery-derive" | ||
version = "0.1.0" | ||
edition = "2021" | ||
|
||
[lib] | ||
proc-macro = true | ||
|
||
[dependencies] | ||
proc-macro2 = "1.0.36" | ||
quote = "1.0.14" | ||
syn = "1.0.85" |
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 |
---|---|---|
@@ -0,0 +1,13 @@ | ||
use proc_macro::TokenStream; | ||
use syn::{parse_macro_input, DeriveInput}; | ||
|
||
mod prism; | ||
use prism::expand_prism; | ||
|
||
#[proc_macro_derive(Prism)] | ||
pub fn prism(input: TokenStream) -> TokenStream { | ||
let input = parse_macro_input!(input as DeriveInput); | ||
expand_prism(input) | ||
.unwrap_or_else(syn::Error::into_compile_error) | ||
.into() | ||
} |
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 |
---|---|---|
@@ -0,0 +1,104 @@ | ||
use proc_macro2::TokenStream; | ||
use quote::{format_ident, quote}; | ||
use syn::{parse_quote, spanned::Spanned, Data, DeriveInput, Fields, GenericParam, WherePredicate}; | ||
|
||
pub fn expand_prism(input: DeriveInput) -> syn::Result<TokenStream> { | ||
let variants = match input.data { | ||
Data::Enum(e) => e.variants, | ||
_ => panic!("this derive macro only works on enums"), | ||
}; | ||
|
||
let enum_name = input.ident; | ||
let enum_vis = input.vis; | ||
|
||
let mut generics = input.generics; | ||
|
||
let mut prism_where_clause = generics.make_where_clause().clone(); | ||
prism_where_clause | ||
.predicates | ||
.extend(generics.params.iter().filter_map(|param| match param { | ||
GenericParam::Type(ty) => { | ||
let name = &ty.ident; | ||
let pred: WherePredicate = parse_quote! { #name: ::std::clone::Clone }; | ||
|
||
Some(pred) | ||
} | ||
GenericParam::Lifetime(_) | GenericParam::Const(_) => None, | ||
})); | ||
|
||
let (impl_generics, enum_generics, _enum_where_clause) = generics.split_for_impl(); | ||
|
||
variants | ||
.iter() | ||
.map(|v| { | ||
let variant_name = &v.ident; | ||
let name = format_ident!("{}{}", enum_name, variant_name, span = v.span()); | ||
|
||
let inner_type; | ||
let inner_expr; | ||
let cloned_inner; | ||
let variant_expr; | ||
|
||
match &v.fields { | ||
Fields::Named(_) => { | ||
return Err(syn::Error::new_spanned( | ||
&v, | ||
"variants with named fields are not supported for deriving `Prism`", | ||
)); | ||
} | ||
Fields::Unnamed(f) => { | ||
let fields = f.unnamed.iter(); | ||
|
||
// By having the comma outside instead of inside the #(), | ||
// it is only added between items, not after the last one. | ||
// For `Variant()` the inner type is `()`, for `Variant(A)` | ||
// it is `(A)` (equal to just `A`), for `Variant(A, B)` it | ||
// is the tuple `(A, B)`. | ||
inner_type = quote! { (#(#fields),*) }; | ||
|
||
let fields = (0..f.unnamed.len()).map(|n| format_ident!("_v{}", n + 1)); | ||
let cloned = fields | ||
.clone() | ||
.map(|f| quote! { ::std::clone::Clone::clone(#f) }); | ||
|
||
inner_expr = quote! { (#(#fields),*) }; | ||
cloned_inner = quote! { (#(#cloned),*) }; | ||
variant_expr = inner_expr.clone(); | ||
} | ||
Fields::Unit => { | ||
inner_type = quote! { () }; | ||
inner_expr = quote! { () }; | ||
cloned_inner = quote! { () }; | ||
variant_expr = quote! {}; | ||
} | ||
} | ||
|
||
Ok(quote! { | ||
#[derive(Clone)] | ||
#enum_vis struct #name; | ||
|
||
#[automatically_derived] | ||
impl #impl_generics ::druid_widget_nursery::prism::Prism< | ||
#enum_name #enum_generics, | ||
#inner_type, | ||
> for #name #prism_where_clause { | ||
fn get( | ||
&self, | ||
data: &#enum_name #enum_generics, | ||
) -> ::std::option::Option<#inner_type> { | ||
match data { | ||
#enum_name::#variant_name #variant_expr => { | ||
::std::option::Option::Some(#cloned_inner) | ||
} | ||
_ => ::std::option::Option::None, | ||
} | ||
} | ||
|
||
fn put(&self, data: &mut #enum_name #enum_generics, #inner_expr: #inner_type) { | ||
*data = #enum_name::#variant_name #variant_expr; | ||
} | ||
} | ||
}) | ||
}) | ||
.collect() | ||
} |
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
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 |
---|---|---|
@@ -0,0 +1,37 @@ | ||
#![cfg(feature = "derive")] | ||
|
||
use std::{fmt::Debug, marker::PhantomData}; | ||
|
||
use druid_widget_nursery::prism::Prism; | ||
|
||
#[derive(Clone, Prism)] | ||
enum MyOption<T> { | ||
Some(T), | ||
None, | ||
} | ||
|
||
#[derive(Clone, Prism)] | ||
enum CLike { | ||
A, | ||
B, | ||
C, | ||
} | ||
|
||
#[derive(Clone, Prism)] | ||
enum Complex { | ||
First, | ||
Second(), | ||
Third(u32), | ||
Fourth(String, Box<Complex>), | ||
} | ||
|
||
#[derive(Clone, Prism)] | ||
enum LotsOfGenerics<T, U: Debug> | ||
where | ||
T: Clone, | ||
(T, U): Clone, | ||
{ | ||
V1, | ||
V2(T), | ||
V3(PhantomData<T>, Box<(U, U)>), | ||
} |
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.
should we make it
mod $enum_name { pub struct $variant_name; }
instead ofstruct $enum_name$variant_name
?this is done in derive
Lens
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.
I like that! I thought this kind of thing would require inherent associated types, great to hear it doesn't.
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.
Unfortunately this doesn't work because enum variants already exist in the value namespace (
Option::Some
in the value namespace is a function fromT
toOption<T>
).Because of rust-lang/rust#76347, I only got errors after fully implementing this idea 🙄
Uh oh!
There was an error while loading. Please reload this page.
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.
Oh by the way the way druid does it / what almost worked wasn't
mod $enum_name
, it wasmod $mod_name {}
+impl #enum_name { pub const Some: $mod_name = $mod_name::Some; }
.The first approach immediately resulted in amibiguity errors between the enum and module.
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.
Here's the broken code that uses associated constants: jplatte@7a62a9b