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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
use proc_macro::{self, TokenStream};
use proc_macro2::{Ident, Span};
use quote::quote;
use syn::{parse_macro_input, Attribute, DeriveInput, Lit, Meta, NestedMeta};

#[proc_macro_derive(UID, attributes(uid, alias))]
pub fn derive(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let ident: proc_macro2::Ident = input.ident;
    let attrs: Vec<_> = input
        .attrs
        .into_iter()
        .filter(|attr| attr.path.is_ident("uid") || attr.path.is_ident("alias"))
        .collect();
    let token = match attrs.len() {
        n if n == 0 => Ok(quote! {
        impl UniqueIdentifier for #ident {
            type Data = Vec<f64>;
        }
        })
        .map(|token| token.into()),
        n if n == 1 => {
            let attr = &attrs[0];
            match attr.path.get_ident() {
                Some(id) if id == "uid" => get_data_type(attr)
                    .map(|data| {
                        quote! {
                        impl UniqueIdentifier for #ident {
                            type Data = #data;
                        }
                        }
                    })
                    .map(|token| token.into()),
                Some(id) if id == "alias" => {
                    get_name_client_traits(attr).and_then(|alias| alias.token(ident))
                }
                _ => Err(syn::Error::new_spanned(
                    attr,
                    "expected only a single attribute",
                )),
            }
        }
        _ => Err(syn::Error::new(
            Span::mixed_site(),
            "expected only a single input",
        )),
    };
    match token {
        Ok(token) => token,
        Err(e) => e.into_compile_error().into(),
    }
}
fn get_data_type(attr: &Attribute) -> syn::Result<syn::TypePath> {
    let meta = attr.parse_meta()?;
    match meta {
        Meta::List(list) => {
            if list.nested.len() == 1 {
                let nested = &list.nested[0];
                match nested {
                    NestedMeta::Meta(Meta::NameValue(nv)) => {
                        if nv.path.is_ident("data") {
                            if let Lit::Str(ref val) = nv.lit {
                                val.parse()
                            } else {
                                Err(syn::Error::new_spanned(&nv.lit, "expected String litteral"))
                            }
                        } else {
                            Err(syn::Error::new_spanned(
                                &nv.path,
                                "expected `data` as uid attribute",
                            ))
                        }
                    }
                    _ => Err(syn::Error::new_spanned(
                        nested,
                        "expected `name = \"<value>\"` argument",
                    )),
                }
            } else {
                Err(syn::Error::new_spanned(
                    list,
                    "expected only a single attribute",
                ))
            }
        }
        _ => Err(syn::Error::new_spanned(
            meta,
            "expected a list of attributes",
        )),
    }
}

struct Alias {
    name: syn::Result<syn::TypePath>,
    client: Client,
}
struct Client {
    name: syn::Result<syn::TypePath>,
    traits: syn::Result<String>,
}
impl Alias {
    fn token(self, ident: Ident) -> syn::Result<TokenStream> {
        self.name
            .and_then(|name| {
                if let (Ok(client), Ok(traits)) = (self.client.name, self.client.traits) {
                    traits
                        .split(',')
                        .map(|t| match t.trim() {
                            "Write" => Ok(quote! {
                                impl dos_actors::io::Write<#ident> for #client {
                                    fn write(&mut self) -> Option<std::sync::Arc<dos_actors::io::Data<#ident>>> {
                                        let mut data: std::sync::Arc<dos_actors::io::Data<#name>> = self.write()?;
                                        let inner = std::sync::Arc::get_mut(&mut data)?;
                                        Some(std::sync::Arc::new(inner.into()))
                                    }
                                }
                            }),
                            "Read" => Ok(quote! {
                                impl dos_actors::io::Read<#ident> for #client {
                                    fn read(&mut self, data: std::sync::Arc<dos_actors::io::Data<#ident>>) {
        let inner = std::sync::Arc::get_mut(&mut data).expect("failed to get a mutable reference to data");
        <Self as dos_actors::io::Read<#name>>::read(self, std::sync::Arc::new(inner.into()));                                    }
                                }
                            }),
                            "Size" => Ok(quote! {
                                impl dos_actors::Size<#ident> for #client {
                                    fn len(&self) -> usize {
                                        <Self as dos_actors::Size<#name>>::len(self)
                                    }
                                }
                            }),
                            _ => Err(syn::Error::new(Span::mixed_site(), "missing alias client")),
                        })
                        .collect::<syn::Result<Vec<_>>>()
                } else {
                    Err(syn::Error::new(Span::mixed_site(), "missing alias client"))
                }
                .map(|client_token| {
                    quote! {
                    impl UniqueIdentifier for #ident {
                        type Data = <#name as UniqueIdentifier>::Data;
                    }
                    #(#client_token)*
                    }
                })
            })
            .map(|token| token.into())
    }
}

fn get_name_client_traits(attr: &Attribute) -> syn::Result<Alias> {
    let client = Client {
        name: Err(syn::Error::new(Span::mixed_site(), "missing alias name")),
        traits: Err(syn::Error::new(Span::mixed_site(), "missing alias client")),
    };
    let mut alias = Alias {
        name: Err(syn::Error::new(Span::mixed_site(), "missing alias name")),
        client,
    };

    let meta = attr.parse_meta()?;
    match meta {
        Meta::List(list) => {
            for nested in list.nested.iter() {
                match nested {
                    NestedMeta::Meta(Meta::NameValue(nv)) if nv.path.is_ident("name") => {
                        alias.name = if let Lit::Str(ref val) = nv.lit {
                            val.parse()
                        } else {
                            Err(syn::Error::new_spanned(&nv.lit, "expected String litteral"))
                        };
                        Ok(())
                    }
                    NestedMeta::Meta(Meta::NameValue(nv)) if nv.path.is_ident("client") => {
                        alias.client.name = if let Lit::Str(ref val) = nv.lit {
                            val.parse()
                        } else {
                            Err(syn::Error::new_spanned(&nv.lit, "expected String litteral"))
                        };
                        Ok(())
                    }
                    NestedMeta::Meta(Meta::NameValue(nv)) if nv.path.is_ident("traits") => {
                        alias.client.traits = if let Lit::Str(ref val) = nv.lit {
                            Ok(val.value())
                        } else {
                            Err(syn::Error::new_spanned(&nv.lit, "expected String litteral"))
                        };
                        Ok(())
                    }
                    _ => Err(syn::Error::new_spanned(
                        nested,
                        "expected `name = \"<value>\"` argument",
                    )),
                }?;
            }
            Ok(alias)
        }
        _ => Err(syn::Error::new_spanned(
            meta,
            "expected a list of attributes",
        )),
    }
}