Created
April 6, 2023 17:03
-
-
Save trueharuu/d2c1984a259aeca257d97511f8c52b36 to your computer and use it in GitHub Desktop.
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
// use proc_macro2::TokenStream; | |
use quote::{ToTokens}; // 1.0.26; | |
use syn::{parse_quote, Ident, Item, ItemConst, ItemEnum, ItemFn, ItemStatic, Signature, Stmt}; // 2.0.11 | |
/// input: | |
/// ```rs | |
/// #[alias(B, C)] | |
/// pub const A: u32 = 0; | |
/// ``` | |
/// | |
/// output: | |
/// ```rs | |
/// pub const A: u32 = 0; | |
/// pub const B: u32 = 0; | |
/// pub const C: u32 = 0; | |
/// ``` | |
pub fn main() { | |
let names = vec!["B", "C"]; | |
let tokens: Stmt = parse_quote! { pub static A: u32 = 0; }; | |
let new = names | |
.into_iter() | |
.map(|name| match &tokens { | |
Stmt::Item(i) => match i { | |
Item::Const(c) => Some(Stmt::Item(Item::Const(ItemConst { | |
ident: syn::parse_str::<Ident>(name).unwrap(), | |
..c.clone() | |
}))), | |
Item::Enum(c) => Some(Stmt::Item(Item::Enum(ItemEnum { | |
ident: syn::parse_str::<Ident>(name).unwrap(), | |
..c.clone() | |
}))), | |
Item::Fn(c) => Some(Stmt::Item(Item::Fn(ItemFn { | |
sig: Signature { | |
ident: syn::parse_str::<Ident>(name).unwrap(), | |
..c.sig.clone() | |
}, | |
..c.clone() | |
}))), | |
Item::Static(c) => Some(Stmt::Item(Item::Static(ItemStatic { | |
ident: syn::parse_str::<Ident>(name).unwrap(), | |
..c.clone() | |
}))), | |
_ => None, | |
}, | |
_ => None, | |
}).map(|x| x.unwrap().into_token_stream().to_string()) | |
.collect::<Vec<_>>(); | |
println!("{}", tokens.into_token_stream()); | |
println!("{}", new.join("\n")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment