-
Notifications
You must be signed in to change notification settings - Fork 89
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
feat: add impl-level exporting QoL macro #707
Open
HoloTheDrunk
wants to merge
6
commits into
rune-rs:main
Choose a base branch
from
HoloTheDrunk:export_item_impl
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
6 commits
Select commit
Hold shift + click to select a range
1198c4c
feat: add impl-level exporting macro
HoloTheDrunk 65c6ddd
feat: add usage example and required module func
HoloTheDrunk 29a2f41
style: fix clippy error
HoloTheDrunk 7749a76
feat: add exporter function gen, small attr change
HoloTheDrunk d53816a
feat: add support for associated functions
HoloTheDrunk 4e98260
fix: change export attr, improve test
HoloTheDrunk 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
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 |
---|---|---|
@@ -0,0 +1,161 @@ | ||
use proc_macro2::TokenStream; | ||
use quote::{quote, ToTokens}; | ||
use syn::parse::ParseStream; | ||
use syn::punctuated::Punctuated; | ||
use syn::spanned::Spanned; | ||
use syn::Token; | ||
|
||
pub(crate) struct ItemImplAttrs { | ||
/// Name of the function meta list function | ||
list: syn::Ident, | ||
/// Name of the function export function | ||
exporter: Option<syn::Ident>, | ||
} | ||
|
||
impl Default for ItemImplAttrs { | ||
fn default() -> Self { | ||
Self { | ||
list: syn::Ident::new("rune_api", proc_macro2::Span::call_site()), | ||
exporter: None, | ||
} | ||
} | ||
} | ||
|
||
impl ItemImplAttrs { | ||
const LIST_IDENT: &'static str = "list"; | ||
const EXPORTER_IDENT: &'static str = "exporter"; | ||
|
||
pub(crate) fn parse(input: ParseStream) -> syn::Result<Self> { | ||
let mut attrs = Self::default(); | ||
|
||
while !input.is_empty() { | ||
let ident = input.parse::<syn::Ident>()?; | ||
|
||
match ident.to_string().as_str() { | ||
Self::LIST_IDENT | Self::EXPORTER_IDENT => { | ||
input.parse::<Token![=]>()?; | ||
if ident == Self::LIST_IDENT { | ||
attrs.list = input.parse()?; | ||
} else { | ||
attrs.exporter = Some(input.parse()?); | ||
} | ||
} | ||
_ => return Err(syn::Error::new_spanned(ident, "Unsupported option")), | ||
} | ||
|
||
if input.parse::<Option<Token![,]>>()?.is_none() { | ||
break; | ||
} | ||
} | ||
|
||
Ok(attrs) | ||
} | ||
} | ||
|
||
pub(crate) struct ItemImpl(pub syn::ItemImpl); | ||
|
||
impl ItemImpl { | ||
pub(crate) fn expand(self, attrs: ItemImplAttrs) -> syn::Result<TokenStream> { | ||
let Self(mut block) = self; | ||
|
||
let mut export_list = Vec::new(); | ||
let export_attr: syn::Attribute = syn::parse_quote!(#[rune(export)]); | ||
|
||
for item in block.items.iter_mut() { | ||
if let syn::ImplItem::Fn(method) = item { | ||
let attr_index = method | ||
.attrs | ||
.iter() | ||
.enumerate() | ||
.find_map(|(index, attr)| (*attr == export_attr).then_some(index)); | ||
|
||
if let Some(index) = attr_index { | ||
method.attrs.remove(index); | ||
|
||
let reparsed = syn::parse::Parser::parse2( | ||
crate::function::Function::parse, | ||
method.to_token_stream(), | ||
)?; | ||
|
||
let name = method.sig.ident.clone(); | ||
let name_string = syn::LitStr::new( | ||
&reparsed.sig.ident.to_string(), | ||
reparsed.sig.ident.span(), | ||
); | ||
let path = syn::Path { | ||
leading_colon: None, | ||
segments: Punctuated::from_iter( | ||
[ | ||
reparsed | ||
.takes_self | ||
.then(|| syn::PathSegment::from(<syn::Token![Self]>::default())) | ||
.or_else(|| { | ||
Some(syn::PathSegment::from( | ||
syn::parse2::<syn::Ident>( | ||
block.self_ty.to_token_stream(), | ||
) | ||
.unwrap(), | ||
)) | ||
}), | ||
Some(syn::PathSegment::from(name.clone())), | ||
] | ||
.into_iter() | ||
.flatten(), | ||
), | ||
}; | ||
|
||
let docs = reparsed.docs; | ||
let arguments = reparsed.arguments; | ||
let meta_kind = syn::Ident::new( | ||
["function", "instance"][reparsed.takes_self as usize], | ||
reparsed.sig.span(), | ||
); | ||
let build_with = if reparsed.takes_self { | ||
None | ||
} else { | ||
Some(quote!(.build()?)) | ||
}; | ||
|
||
let meta = quote! { | ||
rune::__private::FunctionMetaData { | ||
kind: rune::__private::FunctionMetaKind::#meta_kind(#name_string, #path)?#build_with, | ||
name: #name_string, | ||
deprecated: None, | ||
docs: &#docs[..], | ||
arguments: &#arguments[..], | ||
} | ||
}; | ||
|
||
export_list.push(meta); | ||
} | ||
} | ||
} | ||
|
||
let name = attrs.list; | ||
|
||
let export_count = export_list.len(); | ||
let list_function = quote! { | ||
fn #name() -> ::rune::alloc::Result<[::rune::__private::FunctionMetaData; #export_count]> { | ||
Ok([ #(#export_list),* ]) | ||
} | ||
}; | ||
block.items.push(syn::parse2(list_function).unwrap()); | ||
|
||
if let Some(exporter_name) = attrs.exporter { | ||
let exporter_function = quote! { | ||
fn #exporter_name(mut module: ::rune::Module) -> ::rune::alloc::Result<Result<::rune::Module, ::rune::ContextError>> { | ||
for meta in Self::#name()? { | ||
if let Err(e) = module.function_from_meta(meta) { | ||
return Ok(Err(e)); | ||
} | ||
} | ||
Ok(Ok(module)) | ||
} | ||
}; | ||
|
||
block.items.push(syn::parse2(exporter_function).unwrap()); | ||
} | ||
|
||
Ok(block.to_token_stream()) | ||
} | ||
} |
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 |
---|---|---|
|
@@ -37,6 +37,7 @@ mod hash; | |
mod inst_display; | ||
mod instrument; | ||
mod internals; | ||
mod item_impl; | ||
mod macro_; | ||
mod module; | ||
mod opaque; | ||
|
@@ -77,6 +78,54 @@ pub fn function( | |
output.into() | ||
} | ||
|
||
/// Create a function to export all functions marked with the `#[rune(export)]` attribute within a module. | ||
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. within an impl block, not a module? |
||
/// | ||
/// ### Example | ||
/// | ||
/// ```rs | ||
/// #[derive(rune::Any)] | ||
/// struct MyStruct { | ||
/// field: u32, | ||
/// } | ||
/// | ||
/// #[rune::item_impl(exporter = export_rune_api)] | ||
/// impl MyStruct { | ||
/// // Exported | ||
/// #[rune(export)] | ||
/// fn foo(&self) -> u32 { | ||
/// self.field + 1 | ||
/// } | ||
/// | ||
/// // Not exported | ||
/// fn bar(&self) -> u32 { | ||
/// self.field + 2 | ||
/// } | ||
/// } | ||
/// | ||
/// fn main() { | ||
/// let mut module = rune::Module::new(); | ||
/// module.ty::<MyStruct>().unwrap(); | ||
/// module = MyStruct::export_rune_api(module) | ||
/// .expect("Allocation error") | ||
/// .expect("Context error"); | ||
/// } | ||
/// ``` | ||
#[proc_macro_attribute] | ||
pub fn item_impl( | ||
attrs: proc_macro::TokenStream, | ||
item: proc_macro::TokenStream, | ||
) -> proc_macro::TokenStream { | ||
let attrs = syn::parse_macro_input!(attrs with crate::item_impl::ItemImplAttrs::parse); | ||
let item = crate::item_impl::ItemImpl(syn::parse_macro_input!(item as syn::ItemImpl)); | ||
|
||
let output = match item.expand(attrs) { | ||
Ok(output) => output, | ||
Err(e) => return proc_macro::TokenStream::from(e.to_compile_error()), | ||
}; | ||
|
||
output.into() | ||
} | ||
|
||
#[proc_macro_attribute] | ||
pub fn macro_( | ||
attrs: proc_macro::TokenStream, | ||
|
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.
This is a bit too clever, prefer just using an if statement instead.