lofty-rs/lofty_attr/src/lib.rs

63 lines
1.6 KiB
Rust
Raw Normal View History

2022-11-24 20:22:41 +00:00
//! Macros for [Lofty](https://crates.io/crates/lofty)
mod internal;
mod lofty_file;
mod lofty_tag;
2022-09-24 07:43:56 +00:00
mod util;
2022-07-24 20:08:46 +00:00
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, AttributeArgs, Data, DataStruct, DeriveInput, Fields, ItemStruct};
2022-07-24 20:08:46 +00:00
2022-08-10 18:28:48 +00:00
/// Creates a file usable by Lofty
///
/// See [here](https://github.com/Serial-ATA/lofty-rs/tree/main/examples/custom_resolver) for an example of how to use it.
2022-07-24 20:08:46 +00:00
#[proc_macro_derive(LoftyFile, attributes(lofty))]
2022-08-10 18:28:48 +00:00
pub fn lofty_file(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
2022-07-24 20:08:46 +00:00
let data_struct = match input.data {
2022-07-24 20:08:46 +00:00
Data::Struct(
ref data_struct @ DataStruct {
fields: Fields::Named(_),
..
},
) => data_struct,
_ => {
return TokenStream::from(
util::err(
2022-07-24 20:08:46 +00:00
input.ident.span(),
"This macro can only be used on structs with named fields",
2022-07-24 20:08:46 +00:00
)
.to_compile_error(),
);
},
};
let mut errors = Vec::new();
let ret = lofty_file::parse(&input, data_struct, &mut errors);
2022-11-24 20:22:41 +00:00
finish(&ret, &errors)
}
#[proc_macro_attribute]
#[doc(hidden)]
pub fn tag(args_input: TokenStream, input: TokenStream) -> TokenStream {
let args = parse_macro_input!(args_input as AttributeArgs);
let input = parse_macro_input!(input as ItemStruct);
let mut errors = Vec::new();
let ret = lofty_tag::parse(args, input, &mut errors);
2022-11-24 20:22:41 +00:00
finish(&ret, &errors)
}
2022-07-24 20:08:46 +00:00
2022-11-24 20:22:41 +00:00
fn finish(ret: &proc_macro2::TokenStream, errors: &[syn::Error]) -> TokenStream {
let compile_errors = errors.iter().map(syn::Error::to_compile_error);
2022-07-24 20:08:46 +00:00
TokenStream::from(quote! {
#(#compile_errors)*
#ret
2022-07-24 20:08:46 +00:00
})
}