about summary refs log tree commit diff
path: root/tvix/nix-compat-derive/src/de.rs
blob: ee79ea9d10120ad17f015a01d9ab63c5d6017e50 (plain) (blame)
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
use proc_macro2::{Span, TokenStream};
use quote::{quote, quote_spanned, ToTokens};
use syn::spanned::Spanned;
use syn::{DeriveInput, Generics, Path, Type};

use crate::internal::attrs::Default;
use crate::internal::inputs::RemoteInput;
use crate::internal::{attrs, Container, Context, Data, Field, Remote, Style, Variant};

pub fn expand_nix_deserialize(nnixrs: Path, input: &mut DeriveInput) -> syn::Result<TokenStream> {
    let cx = Context::new();
    let cont = Container::from_ast(&cx, nnixrs, input);
    cx.check()?;
    let cont = cont.unwrap();

    let ty = cont.ident_type();
    let body = nix_deserialize_body(&cont);
    let crate_path = cont.crate_path();

    Ok(nix_deserialize_impl(
        crate_path,
        &ty,
        &cont.original.generics,
        body,
    ))
}

pub fn expand_nix_deserialize_remote(
    crate_path: Path,
    input: &RemoteInput,
) -> syn::Result<TokenStream> {
    let cx = Context::new();
    let remote = Remote::from_ast(&cx, crate_path, input);
    cx.check()?;
    let remote = remote.unwrap();

    let crate_path = remote.crate_path();
    let body = nix_deserialize_body_from(crate_path, &remote.attrs).expect("From tokenstream");
    let generics = Generics::default();
    Ok(nix_deserialize_impl(crate_path, remote.ty, &generics, body))
}

fn nix_deserialize_impl(
    crate_path: &Path,
    ty: &Type,
    generics: &Generics,
    body: TokenStream,
) -> TokenStream {
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    quote! {
        #[automatically_derived]
        impl #impl_generics #crate_path::nix_daemon::de::NixDeserialize for #ty #ty_generics
            #where_clause
        {
            #[allow(clippy::manual_async_fn)]
            fn try_deserialize<R>(reader: &mut R) -> impl ::std::future::Future<Output=Result<Option<Self>, R::Error>> + Send + '_
                where R: ?Sized + #crate_path::nix_daemon::de::NixRead + Send,
            {
                #body
            }
        }
    }
}

fn nix_deserialize_body_from(
    crate_path: &syn::Path,
    attrs: &attrs::Container,
) -> Option<TokenStream> {
    if let Some(span) = attrs.from_str.as_ref() {
        Some(nix_deserialize_from_str(crate_path, span.span()))
    } else if let Some(type_from) = attrs.type_from.as_ref() {
        Some(nix_deserialize_from(type_from))
    } else {
        attrs
            .type_try_from
            .as_ref()
            .map(|type_try_from| nix_deserialize_try_from(crate_path, type_try_from))
    }
}

fn nix_deserialize_body(cont: &Container) -> TokenStream {
    if let Some(tokens) = nix_deserialize_body_from(cont.crate_path(), &cont.attrs) {
        tokens
    } else {
        match &cont.data {
            Data::Struct(style, fields) => nix_deserialize_struct(*style, fields),
            Data::Enum(variants) => nix_deserialize_enum(variants),
        }
    }
}

fn nix_deserialize_struct(style: Style, fields: &[Field<'_>]) -> TokenStream {
    let read_fields = fields.iter().map(|f| {
        let field = f.var_ident();
        let ty = f.ty;
        let read_value = quote_spanned! {
            ty.span()=> if first__ {
                first__ = false;
                if let Some(v) = reader.try_read_value::<#ty>().await? {
                    v
                } else {
                    return Ok(None);
                }
            } else {
                reader.read_value::<#ty>().await?
            }
        };
        if let Some(version) = f.attrs.version.as_ref() {
            let default = match &f.attrs.default {
                Default::Default => quote_spanned!(ty.span()=>::std::default::Default::default),
                Default::Path(path) => path.to_token_stream(),
                _ => panic!("No default for versioned field"),
            };
            quote! {
                let #field : #ty = if (#version).contains(&reader.version().minor()) {
                    #read_value
                } else {
                    #default()
                };
            }
        } else {
            quote! {
                let #field : #ty = #read_value;
            }
        }
    });

    let field_names = fields.iter().map(|f| f.var_ident());
    let construct = match style {
        Style::Struct => {
            quote! {
                Self { #(#field_names),* }
            }
        }
        Style::Tuple => {
            quote! {
                Self(#(#field_names),*)
            }
        }
        Style::Unit => quote!(Self),
    };
    quote! {
        #[allow(unused_assignments)]
        async move {
            let mut first__ = true;
            #(#read_fields)*
            Ok(Some(#construct))
        }
    }
}

fn nix_deserialize_variant(variant: &Variant<'_>) -> TokenStream {
    let ident = variant.ident;
    let read_fields = variant.fields.iter().map(|f| {
        let field = f.var_ident();
        let ty = f.ty;
        let read_value = quote_spanned! {
            ty.span()=> if first__ {
                first__ = false;
                if let Some(v) = reader.try_read_value::<#ty>().await? {
                    v
                } else {
                    return Ok(None);
                }
            } else {
                reader.read_value::<#ty>().await?
            }
        };
        if let Some(version) = f.attrs.version.as_ref() {
            let default = match &f.attrs.default {
                Default::Default => quote_spanned!(ty.span()=>::std::default::Default::default),
                Default::Path(path) => path.to_token_stream(),
                _ => panic!("No default for versioned field"),
            };
            quote! {
                let #field : #ty = if (#version).contains(&reader.version().minor()) {
                    #read_value
                } else {
                    #default()
                };
            }
        } else {
            quote! {
                let #field : #ty = #read_value;
            }
        }
    });
    let field_names = variant.fields.iter().map(|f| f.var_ident());
    let construct = match variant.style {
        Style::Struct => {
            quote! {
                Self::#ident { #(#field_names),* }
            }
        }
        Style::Tuple => {
            quote! {
                Self::#ident(#(#field_names),*)
            }
        }
        Style::Unit => quote!(Self::#ident),
    };
    let version = &variant.attrs.version;
    quote! {
        #version => {
            #(#read_fields)*
            Ok(Some(#construct))
        }
    }
}

fn nix_deserialize_enum(variants: &[Variant<'_>]) -> TokenStream {
    let match_variant = variants
        .iter()
        .map(|variant| nix_deserialize_variant(variant));
    quote! {
        #[allow(unused_assignments)]
        async move {
            let mut first__ = true;
            match reader.version().minor() {
                #(#match_variant)*
            }
        }
    }
}

fn nix_deserialize_from(ty: &Type) -> TokenStream {
    quote_spanned! {
        ty.span() =>
        async move {
            if let Some(value) = reader.try_read_value::<#ty>().await? {
                Ok(Some(<Self as ::std::convert::From<#ty>>::from(value)))
            } else {
                Ok(None)
            }
        }
    }
}

fn nix_deserialize_try_from(crate_path: &Path, ty: &Type) -> TokenStream {
    quote_spanned! {
        ty.span() =>
        async move {
            use #crate_path::nix_daemon::de::Error;
            if let Some(item) = reader.try_read_value::<#ty>().await? {
                <Self as ::std::convert::TryFrom<#ty>>::try_from(item)
                    .map_err(Error::invalid_data)
                    .map(Some)
            } else {
                Ok(None)
            }
        }
    }
}

fn nix_deserialize_from_str(crate_path: &Path, span: Span) -> TokenStream {
    quote_spanned! {
        span =>
        async move {
            use #crate_path::nix_daemon::de::Error;
            if let Some(buf) = reader.try_read_bytes().await? {
                let s = ::std::str::from_utf8(&buf)
                    .map_err(Error::invalid_data)?;
                <Self as ::std::str::FromStr>::from_str(s)
                    .map_err(Error::invalid_data)
                    .map(Some)
            } else {
                Ok(None)
            }
        }
    }
}