chore: add kloud_entries_macro_derive
This commit is contained in:
parent
24ceeaba86
commit
5a3f2f08c4
5 changed files with 102 additions and 0 deletions
69
kloud_entries_macro_derive/src/lib.rs
Normal file
69
kloud_entries_macro_derive/src/lib.rs
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
extern crate proc_macro;
|
||||
extern crate syn;
|
||||
// #[macro_use]
|
||||
extern crate quote;
|
||||
|
||||
// use std::collections::BTreeMap;
|
||||
|
||||
use proc_macro::{TokenStream};
|
||||
use syn::{parse_macro_input, DeriveInput };
|
||||
use quote::quote;
|
||||
// use proc_macro2::{Span, TokenStream};
|
||||
// use syn::{parse_macro_input, Attribute, DeriveInput, Ident, Result};
|
||||
// use proc_macro::TokenStream;
|
||||
|
||||
// #[proc_macro_derive(KloudEntries, attributes(kloud_entries))] // It does not work from caller
|
||||
#[proc_macro_derive(KloudEntries)]
|
||||
pub fn kloud_entries_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
// Construct a representation of Rust code as a syntax tree
|
||||
// that we can manipulate
|
||||
// let ast = syn::parse(input).unwrap();
|
||||
// // Build the trait implementation
|
||||
// impl_kloud_entries(&ast).into()
|
||||
let input = parse_macro_input!(input as DeriveInput);
|
||||
// proc_macro::TokenStream::from(impl_kloud_entries(&input))
|
||||
impl_kloud_entries(&input)
|
||||
}
|
||||
|
||||
fn impl_kloud_entries(ast: &syn::DeriveInput) -> TokenStream {
|
||||
let name = &ast.ident;
|
||||
// let attrs = &ast.attrs;
|
||||
// eprintln!("{:#?}",&attrs);
|
||||
// let name_items = &format!("{}Items",&ast.ident);
|
||||
let gen = quote! {
|
||||
impl KloudEntries for #name {
|
||||
fn load_content_data(content: &str, frmt: &str) -> Vec<#name> {
|
||||
match frmt {
|
||||
"yaml" => ::serde_yaml::from_str(&content)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!();
|
||||
Vec::new()
|
||||
}),
|
||||
"json" => ::serde_json::from_str(&content)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!();
|
||||
Vec::new()
|
||||
}),
|
||||
"toml" => ::toml::from_str(&content)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!();
|
||||
Vec::new()
|
||||
}),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
fn data_map_to_content(data_map: BTreeMap<String,#name>, frmt: &str) -> Result<String> {
|
||||
Ok(match frmt {
|
||||
"toml" => toml::to_string_pretty(&data_map)
|
||||
.context("Failed to 'string' loaded data")?,
|
||||
"yaml" => serde_yaml::to_string(&data_map)
|
||||
.context("Failed to 'string' loaded data")?,
|
||||
"json" => serde_json::to_string_pretty(&data_map)
|
||||
.context("Failed to 'string' loaded data")?,
|
||||
_ => String::from(""),
|
||||
})
|
||||
}
|
||||
}
|
||||
};
|
||||
gen.into()
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue