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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use darling::{ast::Style, FromDeriveInput, FromField};
use proc_macro2::{Span, TokenStream, TokenTree};
use proc_macro_crate::FoundCrate;
use quote::{format_ident, quote, ToTokens};
use syn::{parse_macro_input, parse_quote, DeriveInput, GenericParam, Generics};

#[proc_macro_derive(RowFormat, attributes(row))]
pub fn derive_row_format(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let mut input = parse_macro_input!(input as DeriveInput);
    if let Err(err) = fix_field_attrs(&mut input) {
        return err.into_compile_error().into();
    }

    let parsed = match RowFormat::from_derive_input(&input) {
        Ok(parsed) => parsed,
        Err(err) => return err.write_errors().into(),
    };
    let builder = match RowFormatBuilder::new(parsed) {
        Ok(builder) => builder,
        Err(err) => return err.into_compile_error().into(),
    };
    builder.implement().into()
}

#[derive(Debug, Clone, FromDeriveInput)]
#[darling(attributes(row), supports(struct_any), forward_attrs)]
struct RowFormat {
    ident: syn::Ident,
    vis: syn::Visibility,
    generics: Generics,
    data: darling::ast::Data<(), Column>,
    #[darling(default)]
    builder: Option<syn::Ident>,
    #[darling(default)]
    view: Option<syn::Ident>,
}

#[derive(Debug, Clone, FromField)]
#[darling(attributes(row), forward_attrs)]
struct Column {
    ident: Option<syn::Ident>,
    ty: syn::Type,
    #[darling(default)]
    name: Option<String>,
    #[darling(default, rename = "r#type")]
    as_type: Option<syn::Type>,
}

struct ColumnBuilder {
    ident: TokenStream,
    ty: syn::Type,
    name: String,
}

impl ColumnBuilder {
    fn new(col: Column, num: TokenStream) -> Result<Self, syn::Error> {
        let ident = col
            .ident
            .as_ref()
            .map_or_else(|| num.clone(), |ident| ident.to_token_stream());
        let name = match (col.name, &col.ident) {
            (Some(name), _) => name,
            (None, Some(ident)) => ident.to_string(),
            _ => {
                return Err(syn::Error::new_spanned(
                    col.ty.clone(),
                    "missing field name".to_string(),
                ))
            }
        };
        let ty = col.as_type.unwrap_or(col.ty);
        Ok(Self { ident, ty, name })
    }
}

struct RowFormatBuilder {
    ident: syn::Ident,
    vis: syn::Visibility,
    generics: Generics,
    style: Style,
    crt: TokenStream,
    fields: Vec<ColumnBuilder>,
    view_name: syn::Ident,
    builder_name: syn::Ident,
}

impl RowFormatBuilder {
    fn new(input: RowFormat) -> Result<Self, syn::Error> {
        let crt = ella_crate();
        let generics = Self::with_bounds(input.generics, &crt);
        let fields = input.data.take_struct().unwrap();
        let (style, fields) = fields.split();
        let fields = fields
            .iter()
            .enumerate()
            .map(|(i, f)| ColumnBuilder::new(f.clone(), syn::Index::from(i).to_token_stream()))
            .collect::<Result<Vec<_>, _>>()?;

        let view_name = input
            .view
            .unwrap_or_else(|| format_ident!("_{}View", input.ident));
        let builder_name = input
            .builder
            .unwrap_or_else(|| format_ident!("_{}Builder", input.ident));

        Ok(Self {
            ident: input.ident,
            vis: input.vis,
            generics,
            style,
            fields,
            crt,
            view_name,
            builder_name,
        })
    }

    fn implement(self) -> TokenStream {
        let crt = &self.crt;
        let row = quote! { #crt::common::row };
        let ident = &self.ident;
        let generics = &self.generics;
        let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

        let view_name = &self.view_name;
        let builder_name = &self.builder_name;

        let field_types = self.field_types();

        let impl_builder = self.impl_builder();
        let impl_view = self.impl_view();

        let num_cols = quote! {
            #(<#field_types as #row::RowFormat>::COLUMNS +)* 0
        };

        quote! {
            #[automatically_derived]
            impl #impl_generics #crt::common::row::RowFormat for #ident #ty_generics #where_clause {
                const COLUMNS: usize = #num_cols;
                type Builder = #builder_name #ty_generics;
                type View = #view_name #ty_generics;

                fn builder(fields: &[::std::sync::Arc<#crt::derive::Field>]) -> #crt::Result<Self::Builder> {
                    #builder_name::<#ty_generics>::new(fields)
                }

                fn view(rows: usize, fields: &[::std::sync::Arc<#crt::derive::Field>], arrays: &[#crt::derive::ArrayRef]) -> #crt::Result<Self::View> {
                    #view_name::<#ty_generics>::new(rows, fields, arrays)
                }
            }

            #impl_builder
            #impl_view
        }
    }

    fn impl_builder(&self) -> TokenStream {
        let crt = &self.crt;
        let row = quote! { #crt::common::row };
        let vis = &self.vis;
        let ident = &self.ident;
        let generics = &self.generics;
        let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

        let builder_name = &self.builder_name;
        let field_types = self.field_types();
        let field_idents = self.field_idents();
        let builder_fields = self
            .field_names()
            .into_iter()
            .map(|name| syn::Ident::new(&name, Span::call_site()))
            .collect::<Vec<_>>();

        let len = syn::Ident::new("_ella_len", Span::call_site());
        let doc = format!("[`{}::RowBatchBuilder`] for [`{}`]", row, ident);

        quote! {
            #[doc = #doc]
            #[derive(Debug, Clone)]
            #vis struct #builder_name #generics {
                #len: usize,
                #(#builder_fields: <#field_types as #row::RowFormat>::Builder, )*
            }

            #[automatically_derived]
            impl #impl_generics #builder_name #ty_generics #where_clause {
                fn new(mut fields: &[::std::sync::Arc<#crt::derive::Field>]) -> #crt::Result<#builder_name #ty_generics> {
                    if fields.len() != <#ident #ty_generics as #row::RowFormat>::COLUMNS {
                        return Err(#crt::Error::ColumnCount(<#ident #ty_generics as #row::RowFormat>::COLUMNS, fields.len()));
                    }

                    #(
                        let cols = <#field_types as #row::RowFormat>::COLUMNS;
                        let #builder_fields = <#field_types as #row::RowFormat>::builder(&fields[..cols])?;
                        fields = &fields[cols..];
                    )*

                    Ok(#builder_name {
                        #len: 0,
                        #(#builder_fields, )*
                    })
                }
            }

            #[automatically_derived]
            impl #impl_generics #row::RowBatchBuilder<#ident #ty_generics> for #builder_name #ty_generics #where_clause {
                #[inline]
                fn len(&self) -> usize {
                    self.#len
                }

                fn push(&mut self, row: #ident #ty_generics) {
                    #(
                        <<#field_types as #row::RowFormat>::Builder as #row::RowBatchBuilder<#field_types>>::push(&mut self.#builder_fields, row.#field_idents.into());
                    )*
                    self.#len += 1;
                }

                fn build_columns(&mut self) -> #crt::Result<::std::vec::Vec<#crt::derive::ArrayRef>> {
                    // TODO: internal state should be consistent on error
                    let mut cols = ::std::vec::Vec::with_capacity(<#ident #ty_generics as #row::RowFormat>::COLUMNS);
                    #(
                        cols.extend(<<#field_types as #row::RowFormat>::Builder as #row::RowBatchBuilder<#field_types>>::build_columns(&mut self.#builder_fields)?);
                    )*
                    self.#len = 0;
                    Ok(cols)
                }
            }
        }
    }

    fn impl_view(&self) -> TokenStream {
        let crt = &self.crt;
        let row = quote! { #crt::common::row };
        let vis = &self.vis;
        let ident = &self.ident;
        let generics = &self.generics;
        let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

        let view_name = &self.view_name;
        let field_types = self.field_types();
        let field_idents = self.field_idents();
        let view_fields = self
            .field_names()
            .into_iter()
            .map(|name| syn::Ident::new(&name, Span::call_site()))
            .collect::<Vec<_>>();

        let len = syn::Ident::new("_ella_len", Span::call_site());
        let doc = format!("[`{}::RowFormatView`] for [`{}`]", row, ident);

        let impl_accessors = if self.style.is_tuple() {
            quote! {
                fn row(&self, i: usize) -> #ident #ty_generics {
                    #ident(
                        #(<<#field_types as #row::RowFormat>::View as #row::RowFormatView<#field_types>>::row(&self.#view_fields, i).into(), )*
                    )
                }

                unsafe fn row_unchecked(&self, i: usize) -> #ident #ty_generics {
                    #ident(
                        #(<<#field_types as #row::RowFormat>::View as #row::RowFormatView<#field_types>>::row_unchecked(&self.#view_fields, i).into(), )*
                    )
                }
            }
        } else {
            quote! {
                fn row(&self, i: usize) -> #ident #ty_generics {
                    #ident {
                        #(#field_idents: <<#field_types as #row::RowFormat>::View as #row::RowFormatView<#field_types>>::row(&self.#view_fields, i).into(), )*
                    }
                }

                unsafe fn row_unchecked(&self, i: usize) -> #ident #ty_generics {
                    #ident {
                        #(#field_idents: <<#field_types as #row::RowFormat>::View as #row::RowFormatView<#field_types>>::row_unchecked(&self.#view_fields, i).into(), )*
                    }
                }
            }
        };

        quote! {
            #[doc = #doc]
            #[derive(Debug, Clone)]
            #vis struct #view_name #generics {
                #len: usize,
                #(#view_fields: <#field_types as #row::RowFormat>::View, )*
            }

            #[automatically_derived]
            impl #impl_generics #view_name #ty_generics #where_clause {
                fn new(rows: usize, mut fields: &[::std::sync::Arc<#crt::derive::Field>], mut arrays: &[#crt::derive::ArrayRef]) -> #crt::Result<#view_name #ty_generics> {
                    if arrays.len() != <#ident #ty_generics as #row::RowFormat>::COLUMNS {
                        return Err(#crt::Error::ColumnCount(<#ident as #row::RowFormat>::COLUMNS, fields.len()));
                    }

                    #(
                        let cols = <#field_types as #row::RowFormat>::COLUMNS;
                        let #view_fields = <#field_types as #row::RowFormat>::view(rows, &fields[..cols], &arrays[..cols])?;
                        debug_assert_eq!(<<#field_types as #row::RowFormat>::View as #row::RowFormatView<#field_types>>::len(&#view_fields), rows);
                        fields = &fields[cols..];
                        arrays = &arrays[cols..];
                    )*

                    Ok(#view_name {
                        #len: rows,
                        #(#view_fields, )*
                    })
                }
            }

            #[automatically_derived]
            impl #impl_generics #row::RowFormatView<#ident #ty_generics> for #view_name #ty_generics #where_clause {
                #[inline]
                fn len(&self) -> usize {
                    self.#len
                }

                #impl_accessors
            }

            #[automatically_derived]
            impl #impl_generics ::core::iter::IntoIterator for #view_name #ty_generics #where_clause {
                type Item = #ident #ty_generics;
                type IntoIter = #row::RowViewIter<#ident #ty_generics, #view_name #ty_generics>;

                fn into_iter(self) -> Self::IntoIter {
                    #row::RowViewIter::new(self)
                }
            }
        }
    }

    fn field_idents(&self) -> Vec<TokenStream> {
        self.fields.iter().map(|c| c.ident.clone()).collect()
    }

    fn field_types(&self) -> Vec<syn::Type> {
        self.fields.iter().map(|c| c.ty.clone()).collect()
    }

    fn field_names(&self) -> Vec<String> {
        self.fields.iter().map(|c| c.name.clone()).collect()
    }

    fn with_bounds(mut generics: Generics, crt: &TokenStream) -> Generics {
        for param in &mut generics.params {
            if let GenericParam::Type(ref mut param) = *param {
                param
                    .bounds
                    .push(parse_quote!(#crt::common::row::RowFormat));
                param.bounds.push(parse_quote!(::core::fmt::Debug));
                param.bounds.push(parse_quote!(::core::clone::Clone));
            }
        }
        generics
    }
}

fn ella_crate() -> TokenStream {
    let crt = proc_macro_crate::crate_name("ella").expect("ella crate not found in manifest");
    match crt {
        FoundCrate::Itself => quote! { ::ella },
        FoundCrate::Name(name) => {
            let ident = format_ident!("{name}");
            quote! { ::#ident }
        }
    }
}

/// Search field attributes for `type` key and replace with raw `r#type`.
///
/// See [TedDriggs/darling#238](https://github.com/TedDriggs/darling/issues/238)
fn fix_field_attrs(input: &mut DeriveInput) -> Result<(), syn::Error> {
    match &mut input.data {
        syn::Data::Struct(data) => {
            for f in &mut data.fields {
                for attr in &mut f.attrs {
                    if attr.path().is_ident("row") {
                        if let syn::Meta::List(list) = &mut attr.meta {
                            list.tokens = std::mem::take(&mut list.tokens)
                                .into_iter()
                                .map(|token| match token {
                                    TokenTree::Ident(ident) if ident == "type" => TokenTree::Ident(
                                        proc_macro2::Ident::new_raw("type", ident.span()),
                                    ),
                                    _ => token,
                                })
                                .collect();
                        }
                    }
                }
            }
        }
        syn::Data::Enum(data) => {
            return Err(syn::Error::new(
                data.enum_token.span,
                "RowFormat macro does not support enums".to_string(),
            ))
        }
        syn::Data::Union(data) => {
            return Err(syn::Error::new(
                data.union_token.span,
                "RowFormat macro does not support unions".to_string(),
            ))
        }
    }
    Ok(())
}