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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
extern crate proc_macro;
use crate::proc_macro::TokenStream;
use quote::quote;
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::token::Comma;
use syn::token::Eq;
use syn::Lit;
use syn::Path;
use syn::{Attribute, Data, DeriveInput, Field, Fields, Ident, Result as SynResult};
const NAMED_STRUCT_ONLY_ERR: &str = "Derive macro only implemented for named structs";
const INVALID_ATTR_NAME: &str = "Invalid struct attribute. Accepted name is only 'path'";
const INVALID_ATTR_COUNT: &str =
"Invalid struct attributes. Only use 'path' attribute in struct once";
const INVALID_FIELD_ATTR_NAME: &str =
"Invalid field attribute. Accepted attribute names are 'name', and 'hash'";
const INVALID_FIELD_ATTR_COUNT: &str =
"Invalid field attributes. Only use 'name' or 'hash' attribute in field once";
#[proc_macro_derive(Prc, attributes(prc))]
pub fn prc_derive(input: TokenStream) -> TokenStream {
match derive_or_error(input) {
Err(err) => err.to_compile_error().into(),
Ok(result) => result,
}
}
fn derive_or_error(input: TokenStream) -> SynResult<TokenStream> {
let input: DeriveInput = syn::parse(input)?;
let ident = input.ident;
let attrs = parse_struct_attributes(&input.attrs)?;
match input.data {
Data::Struct(data_struct) => match &data_struct.fields {
Fields::Named(fields) => derive_named_struct(ident, &attrs, &fields.named),
Fields::Unnamed(..) => panic!("{}", NAMED_STRUCT_ONLY_ERR),
Fields::Unit => panic!("{}", NAMED_STRUCT_ONLY_ERR),
},
_ => panic!("{}", NAMED_STRUCT_ONLY_ERR),
}
}
#[derive(Default)]
struct MainAttributes {
path: Option<Path>,
}
enum MainAttribute {
Path(Path),
}
enum FieldAttribute {
Name(Lit),
Hash(Lit),
}
fn parse_struct_attributes(attrs: &[Attribute]) -> SynResult<MainAttributes> {
let mut attributes = MainAttributes::default();
attrs
.iter()
.filter(|attr| attr.path.is_ident("prc"))
.try_for_each(|attr| {
let attr_kind: MainAttribute = attr.parse_args()?;
match attr_kind {
MainAttribute::Path(path) => {
if attributes.path.is_some() {
panic!("{}", INVALID_ATTR_COUNT);
} else {
attributes.path = Some(path);
}
}
}
SynResult::Ok(())
})?;
Ok(attributes)
}
impl Parse for MainAttribute {
fn parse(input: ParseStream) -> SynResult<Self> {
let key: Ident = input.parse()?;
let struct_attr = match key.to_string().as_ref() {
"path" => {
let _eq: Eq = input.parse()?;
MainAttribute::Path(input.parse()?)
}
_ => panic!("{}", INVALID_ATTR_NAME),
};
SynResult::Ok(struct_attr)
}
}
impl Parse for FieldAttribute {
fn parse(input: ParseStream) -> SynResult<Self> {
let key: Ident = input.parse()?;
match key.to_string().as_ref() {
"name" => {
let _eq: Eq = input.parse()?;
Ok(FieldAttribute::Name(input.parse()?))
}
"hash" => {
let _eq: Eq = input.parse()?;
Ok(FieldAttribute::Hash(input.parse()?))
}
_ => Err(input.error(INVALID_FIELD_ATTR_NAME)),
}
}
}
fn derive_named_struct(
ident: Ident,
attrs: &MainAttributes,
fields: &Punctuated<Field, Comma>,
) -> SynResult<TokenStream> {
let path = attrs
.path
.as_ref()
.map(|some_path| quote!(#some_path))
.unwrap_or(quote!(::prc));
let names = fields
.iter()
.map(|field| {
let attrs = field
.attrs
.iter()
.filter(|attr| attr.path.is_ident("prc"))
.map(|attr| attr.parse_args())
.collect::<Result<Vec<_>, _>>()?;
if attrs.len() > 1 {
panic!("{}", INVALID_FIELD_ATTR_COUNT);
}
let ident = field.ident.as_ref().unwrap();
let ident_string = ident.to_string();
let hash = match attrs.get(0) {
Some(FieldAttribute::Hash(hash)) => quote!(#path::hash40::Hash40(#hash)),
Some(FieldAttribute::Name(name)) => quote!(#path::hash40::hash40(#name)),
None => quote!(#path::hash40::hash40(#ident_string)),
};
Ok((ident, hash))
})
.collect::<SynResult<Vec<_>>>()?;
let struct_names = names.iter().map(|name| name.0);
let hashes = names.iter().map(|name| &name.1);
Ok(quote! {
impl Prc for #ident {
fn read_param<R: ::std::io::Read + ::std::io::Seek>(reader: &mut R, offsets: #path::prc_trait::FileOffsets) -> #path::prc_trait::Result<Self> {
let data = #path::prc_trait::StructData::from_stream(reader)?;
Ok(Self {
#(
#struct_names: data.read_child(reader, #hashes, offsets)?,
)*
})
}
}
}
.into())
}