Skip to content

Instantly share code, notes, and snippets.

@trueharuu
Created April 6, 2023 17:03
Show Gist options
  • Save trueharuu/d2c1984a259aeca257d97511f8c52b36 to your computer and use it in GitHub Desktop.
Save trueharuu/d2c1984a259aeca257d97511f8c52b36 to your computer and use it in GitHub Desktop.
// 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