ravenous-tools/more_fields_macro/src/lib.rs

82 lines
2.9 KiB
Rust

// Workspace: more_fields_macro
// File: more_fields_macro/src/lib.rs
//! A very simple proc macro in chage of giving a field slice over ("name","sql_type")
//! This macro is a fork of the excellent work of : https://crates.io/crates/struct_iterable
//!
//! Other ressources include:
//! - https://github.com/rust-lang/reference/blob/master/src/procedural-macros.md#attribute-macros
//! - https://docs.rs/syn/latest/syn/struct.Attribute.html
//! - https://docs.rs/syn/latest/syn/struct.Attribute.html#parsing-from-tokens-to-attribute
//! - https://docs.rs/syn/latest/syn/struct.Ident.html
//!
// use proc_macro::TokenStream;
// use quote::quote;
// use syn::{Data, DeriveInput, Fields, parse_macro_input};
extern crate proc_macro;
use proc_macro::{Span, TokenStream};
use quote::quote;
use syn::DeriveInput;
use syn::Ident;
use syn::parse_macro_input;
use syn::{Data, Fields};
#[proc_macro_derive(FieldsAsSlice, attributes(INTEGER, NULL, REAL, TEXT, BLOB))]
pub fn derive_iterable(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let struct_name = input.ident;
let fields = match input.data {
Data::Struct(data_struct) => {
// let list_attrs = input.attrs.iter().map(|v| v.path());
match data_struct.fields {
Fields::Named(fields_named) => fields_named.named,
_ => panic!("Only structs with named fields are supported"),
}
}
_ => panic!("Only structs are supported"),
};
let fields_iter = fields.iter().map(|field| {
let field_ident = &field.ident;
let val = field
.attrs
.iter()
.map(|v| v.path().get_ident())
.next()
.flatten()
.cloned()
.unwrap_or_else(|| syn::Ident::new("TEXT", Span::call_site().into()))
.to_string();
let field_name = field_ident.as_ref().unwrap().to_string();
quote! {
(#field_name, #val)
}
});
let name_of_static_str = struct_name.to_string().to_ascii_uppercase() + "_ATTR_SLICE";
let name_of_static = Ident::new(&name_of_static_str, Span::call_site().into());
let expanded = quote! {
/// Derived implementation of a (attribute, type) slice
/// allowing a constant time serialisation & deserialisation into rusqlite
const #name_of_static: &[(&str, &str)] = &[
#(#fields_iter),*
];
impl FieldsAsSlice for #struct_name {
/// Gives a precompiled slice of the &[(fields: &str, sqlite_type: &str)]
fn attributes_slice<'a>() -> &'static [(&'static str, &'static str)] {
#name_of_static
}
}
};
TokenStream::from(expanded)
}
// As an hashmap (incorrect as of no ordering)
// let mut h = std::collections::HashMap::new();
// #(h.insert(#fields_iter);)*
// h