1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use proc_macro::TokenStream;
use syn::{
	parse::Parse,
	Attribute,
	ItemEnum,
	ItemStruct,
	Token,
	__private::ToTokens,
};

mod ext_traits;
mod preprocessor;
mod process_enum;
mod process_struct;
mod processed_fields;

enum Item {
	Struct(ItemStruct),
	Enum(ItemEnum),
}

impl Parse for Item {
	fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
		let attrs = input.call(Attribute::parse_outer)?;
		let vis = input.parse()?;

		if input.peek(Token![struct]) {
			input
				.parse()
				.map(|item: ItemStruct| ItemStruct { vis, attrs, ..item })
				.map(Item::Struct)
		} else {
			input
				.parse()
				.map(|item: ItemEnum| ItemEnum { attrs, vis, ..item })
				.map(Item::Enum)
		}
	}
}

impl From<Item> for TokenStream {
	fn from(val: Item) -> Self {
		match val {
			Item::Struct(item) => item.into_token_stream().into(),
			Item::Enum(item) => item.into_token_stream().into(),
		}
	}
}

impl Item {
	fn into_processed(self) -> TokenStream {
		let result = match self {
			Item::Struct(item) => process_struct::into_processed(item),
			Item::Enum(item) => process_enum::into_processed(item),
		};

		match result {
			Ok(token_stream) => token_stream,
			Err(error) => error.to_compile_error().into(),
		}
	}
}

#[proc_macro_attribute]
pub fn sync(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = syn::parse_macro_input!(input as Item);

	if let Some(token) = args.into_iter().next() {
		return syn::Error::new(token.span().into(), "unexpected arguments")
			.to_compile_error()
			.into();
	}

	input.into_processed()
}