zvariant_derive/
value.rs

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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens};
use syn::{
    spanned::Spanned, Attribute, Data, DataEnum, DeriveInput, Error, Expr, Fields, Generics, Ident,
    Lifetime, LifetimeDef,
};

use crate::utils::*;

pub enum ValueType {
    Value,
    OwnedValue,
}

pub fn expand_derive(ast: DeriveInput, value_type: ValueType) -> Result<TokenStream, Error> {
    let zv = zvariant_path();

    match &ast.data {
        Data::Struct(ds) => match &ds.fields {
            Fields::Named(_) | Fields::Unnamed(_) => {
                let StructAttributes { signature, .. } = StructAttributes::parse(&ast.attrs)?;
                let signature = signature.map(|signature| match signature.as_str() {
                    "dict" => "a{sv}".to_string(),
                    _ => signature,
                });

                impl_struct(
                    value_type,
                    ast.ident,
                    ast.generics,
                    &ds.fields,
                    signature,
                    &zv,
                )
            }
            Fields::Unit => Err(Error::new(ast.span(), "Unit structures not supported")),
        },
        Data::Enum(data) => impl_enum(value_type, ast.ident, ast.generics, ast.attrs, data, &zv),
        _ => Err(Error::new(
            ast.span(),
            "only structs and enums are supported",
        )),
    }
}

fn impl_struct(
    value_type: ValueType,
    name: Ident,
    generics: Generics,
    fields: &Fields,
    signature: Option<String>,
    zv: &TokenStream,
) -> Result<TokenStream, Error> {
    let statc_lifetime = LifetimeDef::new(Lifetime::new("'static", Span::call_site()));
    let (value_type, value_lifetime) = match value_type {
        ValueType::Value => {
            let mut lifetimes = generics.lifetimes();
            let value_lifetime = lifetimes
                .next()
                .cloned()
                .unwrap_or_else(|| statc_lifetime.clone());
            if lifetimes.next().is_some() {
                return Err(Error::new(
                    name.span(),
                    "Type with more than 1 lifetime not supported",
                ));
            }

            (quote! { #zv::Value<#value_lifetime> }, value_lifetime)
        }
        ValueType::OwnedValue => (quote! { #zv::OwnedValue }, statc_lifetime),
    };

    let type_params = generics.type_params().cloned().collect::<Vec<_>>();
    let (from_value_where_clause, into_value_where_clause) = if !type_params.is_empty() {
        (
            Some(quote! {
                where
                #(
                    #type_params: ::std::convert::TryFrom<#zv::Value<#value_lifetime>> + #zv::Type
                ),*
            }),
            Some(quote! {
                where
                #(
                    #type_params: ::std::convert::Into<#zv::Value<#value_lifetime>> + #zv::Type
                ),*
            }),
        )
    } else {
        (None, None)
    };
    let (impl_generics, ty_generics, _) = generics.split_for_impl();
    match fields {
        Fields::Named(_) => {
            let field_names: Vec<_> = fields
                .iter()
                .map(|field| field.ident.to_token_stream())
                .collect();
            let (from_value_impl, into_value_impl) = match signature {
                Some(signature) if signature == "a{sv}" => (
                    // User wants the type to be encoded as a dict.
                    // FIXME: Not the most efficient implementation.
                    quote! {
                        let mut fields = <::std::collections::HashMap::<::std::string::String, #zv::Value>>::try_from(value)?;

                        ::std::result::Result::Ok(Self {
                            #(
                                #field_names:
                                    fields
                                        .remove(stringify!(#field_names))
                                        .ok_or_else(|| #zv::Error::IncorrectType)?
                                        .downcast()
                                        .ok_or_else(|| #zv::Error::IncorrectType)?
                            ),*
                        })
                    },
                    quote! {
                        let mut fields = ::std::collections::HashMap::new();
                        #(
                            fields.insert(stringify!(#field_names), #zv::Value::from(s.#field_names));
                        )*

                        #zv::Value::from(fields).into()
                    },
                ),
                Some(_) | None => (
                    quote! {
                        let mut fields = #zv::Structure::try_from(value)?.into_fields();

                        ::std::result::Result::Ok(Self {
                            #(
                                #field_names:
                                    fields
                                        .remove(0)
                                        .downcast()
                                        .ok_or_else(|| #zv::Error::IncorrectType)?
                            ),*
                        })
                    },
                    quote! {
                        #zv::StructureBuilder::new()
                        #(
                            .add_field(s.#field_names)
                        )*
                        .build()
                        .into()
                    },
                ),
            };
            Ok(quote! {
                impl #impl_generics ::std::convert::TryFrom<#value_type> for #name #ty_generics
                    #from_value_where_clause
                {
                    type Error = #zv::Error;

                    #[inline]
                    fn try_from(value: #value_type) -> #zv::Result<Self> {
                        #from_value_impl
                    }
                }

                impl #impl_generics From<#name #ty_generics> for #value_type
                    #into_value_where_clause
                {
                    #[inline]
                    fn from(s: #name #ty_generics) -> Self {
                        #into_value_impl
                    }
                }
            })
        }
        Fields::Unnamed(_) if fields.iter().next().is_some() => {
            // Newtype struct.
            Ok(quote! {
                impl #impl_generics ::std::convert::TryFrom<#value_type> for #name #ty_generics
                    #from_value_where_clause
                {
                    type Error = #zv::Error;

                    #[inline]
                    fn try_from(value: #value_type) -> #zv::Result<Self> {
                        ::std::convert::TryInto::try_into(value).map(Self)
                    }
                }

                impl #impl_generics From<#name #ty_generics> for #value_type
                    #into_value_where_clause
                {
                    #[inline]
                    fn from(s: #name #ty_generics) -> Self {
                        s.0.into()
                    }
                }
            })
        }
        Fields::Unnamed(_) => panic!("impl_struct must not be called for tuples"),
        Fields::Unit => panic!("impl_struct must not be called for unit structures"),
    }
}

fn impl_enum(
    value_type: ValueType,
    name: Ident,
    _generics: Generics,
    attrs: Vec<Attribute>,
    data: &DataEnum,
    zv: &TokenStream,
) -> Result<TokenStream, Error> {
    let repr: TokenStream = match attrs.iter().find(|attr| attr.path.is_ident("repr")) {
        Some(repr_attr) => repr_attr.parse_args()?,
        None => quote! { u32 },
    };

    let mut variant_names = vec![];
    let mut variant_values = vec![];
    for variant in &data.variants {
        // Ensure all variants of the enum are unit type
        match variant.fields {
            Fields::Unit => {
                variant_names.push(&variant.ident);
                let value = match &variant
                    .discriminant
                    .as_ref()
                    .ok_or_else(|| Error::new(variant.span(), "expected `Name = Value` variants"))?
                    .1
                {
                    Expr::Lit(lit_exp) => &lit_exp.lit,
                    _ => {
                        return Err(Error::new(
                            variant.span(),
                            "expected `Name = Value` variants",
                        ))
                    }
                };
                variant_values.push(value);
            }
            _ => return Err(Error::new(variant.span(), "must be a unit variant")),
        }
    }

    let value_type = match value_type {
        ValueType::Value => quote! { #zv::Value<'_> },
        ValueType::OwnedValue => quote! { #zv::OwnedValue },
    };

    Ok(quote! {
        impl ::std::convert::TryFrom<#value_type> for #name {
            type Error = #zv::Error;

            #[inline]
            fn try_from(value: #value_type) -> #zv::Result<Self> {
                let v: #repr = ::std::convert::TryInto::try_into(value)?;

                ::std::result::Result::Ok(match v {
                    #(
                        #variant_values => #name::#variant_names
                     ),*,
                    _ => return ::std::result::Result::Err(#zv::Error::IncorrectType),
                })
            }
        }

        impl ::std::convert::From<#name> for #value_type {
            #[inline]
            fn from(e: #name) -> Self {
                let u: #repr = match e {
                    #(
                        #name::#variant_names => #variant_values
                     ),*
                };

                <#zv::Value as ::std::convert::From<_>>::from(u).into()
             }
        }
    })
}