Skip to content

Commit

Permalink
Closes #28 #29 parse ItemStruct and ItemEnum
Browse files Browse the repository at this point in the history
Using combination of `syn` parse definitons and use `quote` to assemble
it back into `proc_macro2::TokenStream`.
  • Loading branch information
atahanyorganci committed Feb 5, 2022
1 parent 0b1d804 commit 689d055
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 2 deletions.
56 changes: 56 additions & 0 deletions alloy-macros/src/cst.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
use proc_macro2::{Ident, TokenStream};
use quote::quote;
use syn::{ItemEnum, ItemStruct};

// Strip the `CST` suffix from the given identifier if it exists, otherwise
// add `AST` suffix.
fn get_ast_ident(ident: &Ident) -> Ident {
let cst = ident.to_string();
let ast = if let Some(s) = cst.strip_suffix("CST") {
s.to_string()
} else {
format!("{cst}AST")
};
Ident::new(&ast, ident.span())
}

pub(super) fn struct_ast(s: ItemStruct) -> TokenStream {
let ItemStruct {
attrs,
vis,
struct_token,
ident,
generics,
fields: _,
semi_token,
} = s;
let ast_ident = get_ast_ident(&ident);
let fields = if semi_token.is_some() {
quote! {();}
} else {
quote! {{}}
};
quote! {
#(#attrs)*
#vis #struct_token #ast_ident #generics
#fields
}
}

pub(super) fn enum_ast(e: ItemEnum) -> TokenStream {
let ItemEnum {
attrs,
vis,
enum_token,
ident,
generics,
brace_token: _,
variants: _,
} = e;
let ast_ident = get_ast_ident(&ident);
quote! {
#(#attrs)*
#vis #enum_token #ast_ident #generics {
}
}
}
5 changes: 3 additions & 2 deletions alloy-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, spanned::Spanned, Expr, Item, LitStr};

mod cst;
mod expand;

#[proc_macro]
Expand Down Expand Up @@ -32,8 +33,8 @@ pub fn assert_expr(input: TokenStream) -> TokenStream {
pub fn cst_to_ast(input: TokenStream) -> TokenStream {
let s = parse_macro_input!(input as Item);
let tokens = match s {
Item::Enum(_e) => quote! {},
Item::Struct(_s) => quote! {},
Item::Enum(e) => cst::enum_ast(e),
Item::Struct(s) => cst::struct_ast(s),
_ => panic!("only enums and structs can derive AST"),
};
tokens.into()
Expand Down

0 comments on commit 689d055

Please sign in to comment.