commit 2054845649b0342f8ad31d76b561ebf77678a13f Author: Sam Johnson Date: Wed Jul 5 09:56:56 2023 -0400 working diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4fffb2f --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +/Cargo.lock diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..65d905c --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "pub-fields" +version = "0.1.0" +edition = "2021" +authors = ["sam0x17"] +description = "Provides a proc macro attribute that defaults all struct fields to public unless private is prepended." + +[lib] +proc-macro = true + +[dependencies] +syn = { version = "2", features = ["full"]} +quote = "1" diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..59cdb14 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,17 @@ +use proc_macro::TokenStream; +use quote::ToTokens; +use syn::{parse::Nothing, parse_macro_input, parse_quote, ItemStruct}; + +#[proc_macro_attribute] +pub fn pub_fields(attr: TokenStream, tokens: TokenStream) -> TokenStream { + parse_macro_input!(attr as Nothing); + let mut item_struct = parse_macro_input!(tokens as ItemStruct); + for field in &mut item_struct.fields { + field.vis = match &field.vis { + syn::Visibility::Public(p) => syn::Visibility::Public(*p), + syn::Visibility::Restricted(res) => syn::Visibility::Restricted(res.clone()), + syn::Visibility::Inherited => parse_quote!(pub), + }; + } + item_struct.to_token_stream().into() +} diff --git a/tests/tests.rs b/tests/tests.rs new file mode 100644 index 0000000..21d837d --- /dev/null +++ b/tests/tests.rs @@ -0,0 +1,15 @@ +mod submod { + use pub_fields::pub_fields; + + #[pub_fields] + pub struct MyStruct { + a: usize, + b: usize, + c: usize, + } +} + +#[test] +fn test_it() { + let x = submod::MyStruct { a: 3, b: 4, c: 5 }; +}