-
Notifications
You must be signed in to change notification settings - Fork 221
Add support for custom bakes to databake #6576
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
sffc
wants to merge
3
commits into
unicode-org:main
Choose a base branch
from
sffc:databake-custom-bake
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 all commits
Commits
Show all changes
3 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 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 | ||||
---|---|---|---|---|---|---|
|
@@ -6,6 +6,7 @@ | |||||
|
||||||
use proc_macro::TokenStream; | ||||||
use proc_macro2::TokenStream as TokenStream2; | ||||||
use quote::format_ident; | ||||||
use quote::quote; | ||||||
use syn::{ | ||||||
parse::{Parse, ParseStream}, | ||||||
|
@@ -31,6 +32,40 @@ use synstructure::{AddBounds, Structure}; | |||||
/// pub age: u32, | ||||||
/// } | ||||||
/// ``` | ||||||
/// | ||||||
/// # Custom baked type | ||||||
/// | ||||||
/// To bake to a different type than this, use `custom_bake` | ||||||
/// and implement `CustomBake`. | ||||||
/// | ||||||
/// ```rust | ||||||
/// use databake::Bake; | ||||||
/// use databake::CustomBake; | ||||||
/// | ||||||
/// #[derive(Bake)] | ||||||
/// #[databake(path = bar::module)] | ||||||
/// #[databake(path = custom_bake)] | ||||||
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.
Suggested change
|
||||||
/// pub struct Message<'a> { | ||||||
/// pub message: &'a str, | ||||||
/// } | ||||||
/// | ||||||
/// // Bake to a string: | ||||||
/// impl CustomBake for Message<'_> { | ||||||
/// type BakedType<'a> = &'a str where Self: 'a; | ||||||
/// fn to_custom_bake(&self) -> Self::BakedType<'_> { | ||||||
/// &self.message | ||||||
/// } | ||||||
/// } | ||||||
/// | ||||||
/// impl<'a> Message<'a> { | ||||||
/// pub fn from_custom_bake(message: &'a str) -> Self { | ||||||
/// Self { message } | ||||||
/// } | ||||||
/// } | ||||||
/// ``` | ||||||
/// | ||||||
/// If the constructor is unsafe, use `custom_bake_unsafe` | ||||||
/// and implement `CustomBakeUnsafe`. | ||||||
#[proc_macro_derive(Bake, attributes(databake))] | ||||||
pub fn bake_derive(input: TokenStream) -> TokenStream { | ||||||
let input = parse_macro_input!(input as DeriveInput); | ||||||
|
@@ -40,44 +75,89 @@ pub fn bake_derive(input: TokenStream) -> TokenStream { | |||||
fn bake_derive_impl(input: &DeriveInput) -> TokenStream2 { | ||||||
let mut structure = Structure::new(input); | ||||||
|
||||||
struct PathAttr(Punctuated<PathSegment, Token![::]>); | ||||||
enum DatabakeAttr { | ||||||
Path(Punctuated<PathSegment, Token![::]>), | ||||||
CustomBake, | ||||||
CustomBakeUnsafe, | ||||||
} | ||||||
|
||||||
impl Parse for PathAttr { | ||||||
impl Parse for DatabakeAttr { | ||||||
fn parse(input: ParseStream<'_>) -> syn::parse::Result<Self> { | ||||||
let i: Ident = input.parse()?; | ||||||
if i != "path" { | ||||||
return Err(input.error(format!("expected token \"path\", found {i:?}"))); | ||||||
if i == "path" { | ||||||
input.parse::<Token![=]>()?; | ||||||
Ok(Self::Path(input.parse::<Path>()?.segments)) | ||||||
} else if i == "custom_bake" { | ||||||
Ok(Self::CustomBake) | ||||||
} else if i == "custom_bake_unsafe" { | ||||||
Ok(Self::CustomBakeUnsafe) | ||||||
} else { | ||||||
Err(input.error(format!("expected token \"path\", found {i:?}"))) | ||||||
} | ||||||
input.parse::<Token![=]>()?; | ||||||
Ok(Self(input.parse::<Path>()?.segments)) | ||||||
} | ||||||
} | ||||||
|
||||||
let path = input | ||||||
let attrs = input | ||||||
.attrs | ||||||
.iter() | ||||||
.find(|a| a.path().is_ident("databake")) | ||||||
.expect("missing databake(path = ...) attribute") | ||||||
.parse_args::<PathAttr>() | ||||||
.unwrap() | ||||||
.0; | ||||||
.filter(|a| a.path().is_ident("databake")) | ||||||
.map(|a| a.parse_args::<DatabakeAttr>().unwrap()) | ||||||
.collect::<Vec<_>>(); | ||||||
|
||||||
let bake_body = structure.each_variant(|vi| { | ||||||
let recursive_calls = vi.bindings().iter().map(|b| { | ||||||
let ident = b.binding.clone(); | ||||||
quote! { let #ident = #ident.bake(env); } | ||||||
}); | ||||||
let path = attrs | ||||||
.iter() | ||||||
.filter_map(|a| match a { | ||||||
DatabakeAttr::Path(path) => Some(path), | ||||||
_ => None, | ||||||
}) | ||||||
.next() | ||||||
.expect("missing databake(path = ...) attribute"); | ||||||
|
||||||
let constructor = vi.construct(|_, i| { | ||||||
let ident = &vi.bindings()[i].binding; | ||||||
quote! { # #ident } | ||||||
}); | ||||||
let is_custom_bake = attrs.iter().any(|a| matches!(a, DatabakeAttr::CustomBake)); | ||||||
|
||||||
quote! { | ||||||
#(#recursive_calls)* | ||||||
databake::quote! { #path::#constructor } | ||||||
let is_custom_bake_unsafe = attrs | ||||||
.iter() | ||||||
.any(|a| matches!(a, DatabakeAttr::CustomBakeUnsafe)); | ||||||
|
||||||
let bake_body = if is_custom_bake || is_custom_bake_unsafe { | ||||||
let type_ident = &structure.ast().ident; | ||||||
let baked_ident = format_ident!("baked"); | ||||||
if is_custom_bake_unsafe { | ||||||
quote! { | ||||||
x => { | ||||||
let baked = databake::CustomBake::to_custom_bake(x).bake(env); | ||||||
databake::quote! { | ||||||
// Safety: the bake is generated from `CustomBakeUnsafe::to_custom_bake` | ||||||
unsafe { #path::#type_ident::from_custom_bake(##baked_ident) } | ||||||
} | ||||||
} | ||||||
} | ||||||
} else { | ||||||
quote! { | ||||||
x => { | ||||||
let baked = databake::CustomBake::to_custom_bake(x).bake(env); | ||||||
databake::quote! { #path::#type_ident::from_custom_bake(##baked_ident) } | ||||||
} | ||||||
} | ||||||
} | ||||||
}); | ||||||
} else { | ||||||
structure.each_variant(|vi| { | ||||||
let recursive_calls = vi.bindings().iter().map(|b| { | ||||||
let ident = b.binding.clone(); | ||||||
quote! { let #ident = #ident.bake(env); } | ||||||
}); | ||||||
|
||||||
let constructor = vi.construct(|_, i| { | ||||||
let ident = &vi.bindings()[i].binding; | ||||||
quote! { # #ident } | ||||||
}); | ||||||
|
||||||
quote! { | ||||||
#(#recursive_calls)* | ||||||
databake::quote! { #path::#constructor } | ||||||
} | ||||||
}) | ||||||
}; | ||||||
|
||||||
let borrows_size_body = structure.each_variant(|vi| { | ||||||
let recursive_calls = vi.bindings().iter().map(|b| { | ||||||
|
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,39 @@ | ||
// This file is part of ICU4X. For terms of use, please see the file | ||
// called LICENSE at the top level of the ICU4X source tree | ||
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). | ||
|
||
use crate::Bake; | ||
|
||
/// A trait for an item that can bake to something other than itself. | ||
/// | ||
/// For an unsafe version of this trait, see [`CustomBakeUnsafe`]. | ||
/// | ||
/// The type implementing this trait should have an associated function | ||
/// with the following signature: | ||
/// | ||
/// ```ignore | ||
/// /// The argument should have been returned from [`Self::to_custom_bake`]. | ||
/// pub fn from_custom_bake(baked: CustomBake::BakedType) -> Self | ||
/// ``` | ||
pub trait CustomBake { | ||
/// The type of the custom bake. | ||
type BakedType<'a>: Bake | ||
where | ||
Self: 'a; | ||
/// Returns `self` as the custom bake type. | ||
fn to_custom_bake(&self) -> Self::BakedType<'_>; | ||
} | ||
|
||
/// Same as [`CustomBake`] but allows for the constructor to be `unsafe`. | ||
/// | ||
/// # Safety | ||
/// | ||
/// The type implementing this trait MUST have an associated unsafe function | ||
/// with the following signature: | ||
/// | ||
/// ```ignore | ||
/// /// # Safety | ||
/// /// The argument MUST have been returned from [`Self::to_custom_bake`]. | ||
/// pub unsafe fn from_custom_bake(baked: CustomBakeUnsafe::BakedType) -> Self | ||
/// ``` | ||
pub unsafe trait CustomBakeUnsafe: CustomBake {} |
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
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.
I think having a trait for this is overkill if you can provide a method to the macro
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.
Reasons I made it a trait:
How do you suggest handling the safety requirement without a trait?