-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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
1 parent
0b1d804
commit 689d055
Showing
2 changed files
with
59 additions
and
2 deletions.
There are no files selected for viewing
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
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 { | ||
} | ||
} | ||
} |
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