Skip to content
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

Option to make constructor const #51

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,12 +162,48 @@ fn new_for_enum(ast: &syn::DeriveInput, data: &syn::DataEnum) -> proc_macro2::To
my_quote!(#(#impls)*)
}

fn parse_derive_new_attr(attrs: &[syn::Attribute]) -> bool {
let mut is_const = false;

for i in attrs {
if let Ok(meta) = i.parse_meta() {
if !meta.path().is_ident("new") {
continue;
}
let list = match meta {
syn::Meta::List(l) => l,
_ => panic!("Invalid #[new] attribute, expected #[new(..)]")
};
for item in list.nested.iter() {
match *item {
syn::NestedMeta::Meta(syn::Meta::Path(ref path)) => {
if path.is_ident("const") {
is_const = true;
continue;
}
}
_ => {},
}
panic!("Invalid #[new] attribute");
}
}
}

is_const
}

fn new_impl(
ast: &syn::DeriveInput,
fields: Option<&syn::punctuated::Punctuated<syn::Field, Token![,]>>,
named: bool,
variant: Option<&syn::Ident>,
) -> proc_macro2::TokenStream {
let is_const = parse_derive_new_attr(&ast.attrs);
let const_opt = if is_const {
my_quote!(const)
} else {
my_quote!()
};
let name = &ast.ident;
let unit = fields.is_none();
let empty = Default::default();
Expand Down Expand Up @@ -209,7 +245,7 @@ fn new_impl(
impl #impl_generics #name #ty_generics #where_clause {
#[doc = #doc]
#lint_attrs
pub fn #new(#(#args),*) -> Self {
pub #const_opt fn #new(#(#args),*) -> Self {
#name #qual #inits
}
}
Expand Down
10 changes: 10 additions & 0 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,16 @@ pub struct Bar {
pub y: String,
}

#[derive(new)]
#[new(const)]
struct ConstFoo {
pub x: u8,
pub y: u8,
pub z: u8,
}

const CONST_FOO: ConstFoo = ConstFoo::new(1, 2, 3);

#[test]
fn test_simple_struct() {
let x = Bar::new(42, "Hello".to_owned());
Expand Down