Skip to main content

vortex_array_macros/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Proc macros for `vortex-array`.
5
6use proc_macro::TokenStream;
7use proc_macro2::Span;
8use quote::format_ident;
9use quote::quote;
10use syn::Field;
11use syn::Fields;
12use syn::Ident;
13use syn::ItemStruct;
14use syn::LitInt;
15use syn::Path;
16use syn::Token;
17use syn::Type;
18use syn::Visibility;
19use syn::parse::Parse;
20use syn::parse::ParseStream;
21use syn::parse_macro_input;
22use syn::spanned::Spanned;
23
24/// Name of the per-field attribute that pins a field to a slot index.
25const SLOT_ATTR: &str = "slot";
26
27/// Slot field names that are rejected because their generated accessors would shadow the inherent
28/// methods of `ArrayView` (which the by-value accessors take precedence over) or the ext trait's
29/// own methods.
30const RESERVED_FIELD_NAMES: &[&str] = &[
31    "array",
32    "borrow_slots",
33    "data",
34    "dtype",
35    "encoding_id",
36    "into_owned",
37    "is_empty",
38    "len",
39    "slots",
40    "slots_view",
41    "statistics",
42    "validity",
43];
44
45/// Generate slot index constants, a borrowed view struct, and a typed ext trait
46/// from a slot struct definition.
47///
48/// Fields must be `ArrayRef` (required slot), `Option<ArrayRef>` (optional slot), or
49/// `Vec<ArrayRef>` (variadic tail of required slots).
50///
51/// Every field must carry a `#[slot(..)]` attribute naming the exact slot index it maps
52/// to. The attribute — not the declaration order — defines the storage layout, so fields
53/// may be reordered, grouped, or documented in any order without changing the slot
54/// indices an array is built from or read back with.
55///
56/// # Example
57///
58/// ```ignore
59/// #[array_slots(Patched)]
60/// pub struct PatchedSlots {
61///     #[slot(0)]
62///     pub inner: ArrayRef,
63///     #[slot(1)]
64///     pub lane_offsets: ArrayRef,
65///     #[slot(2)]
66///     pub patch_indices: ArrayRef,
67///     #[slot(3)]
68///     pub patch_values: ArrayRef,
69/// }
70/// ```
71///
72/// # Generated output
73///
74/// Given the above, the macro generates:
75///
76/// ```ignore
77/// // --- The original struct, minus the consumed `#[slot(..)]` attributes ---
78/// pub struct PatchedSlots { ... }
79///
80/// // --- Slot index constants and conversion methods on the struct ---
81/// impl PatchedSlots {
82///     pub const INNER: usize = 0;
83///     pub const LANE_OFFSETS: usize = 1;
84///     pub const PATCH_INDICES: usize = 2;
85///     pub const PATCH_VALUES: usize = 3;
86///     pub const COUNT: usize = 4;
87///     pub const NAMES: [&'static str; 4] = ["inner", "lane_offsets", "patch_indices", "patch_values"];
88///
89///     /// Take ownership of slots from an `ArraySlots`.
90///     pub fn from_slots(slots: ArraySlots) -> Self { ... }
91///
92///     /// Convert back into storage order.
93///     pub fn into_slots(self) -> ArraySlots { ... }
94/// }
95///
96/// // --- Borrowed view with &ArrayRef / Option<&ArrayRef> fields ---
97/// pub struct PatchedSlotsView<'a> {
98///     pub inner: &'a ArrayRef,
99///     pub lane_offsets: &'a ArrayRef,
100///     pub patch_indices: &'a ArrayRef,
101///     pub patch_values: &'a ArrayRef,
102/// }
103///
104/// impl<'a> PatchedSlotsView<'a> {
105///     pub fn from_slots(slots: &'a [Option<ArrayRef>]) -> Self { ... }
106///     pub fn to_owned(&self) -> PatchedSlots { ... }
107/// }
108///
109/// // --- Ext trait with per-field accessors + slots_view() ---
110/// pub trait PatchedArraySlotsExt<'a>: BorrowArraySlots<'a, Patched> {
111///     fn inner(self) -> &'a ArrayRef { ... }         // indexes slots directly
112///     fn lane_offsets(self) -> &'a ArrayRef { ... }
113///     fn patch_indices(self) -> &'a ArrayRef { ... }
114///     fn patch_values(self) -> &'a ArrayRef { ... }
115///     fn slots_view(self) -> PatchedSlotsView<'a> { ... }
116/// }
117///
118/// impl<'a, S: BorrowArraySlots<'a, Patched>> PatchedArraySlotsExt<'a> for S {}
119/// ```
120///
121/// # Borrowing
122///
123/// `vortex_array::BorrowArraySlots<'a, V>` is implemented for `&'a T` where
124/// `T: TypedArrayRef<V>` (an owned `Array<V>`, or any generic typed array), and for
125/// `ArrayView<'a, V>` itself. The accessors take `self` by value, so:
126///
127/// - on an `Array<V>` or `&Array<V>`, the result borrows from the array, as with any `&self`
128///   method;
129/// - on an `ArrayView<'a, V>`, the result borrows for `'a`, the lifetime of the array the view
130///   points at, so a slot read from a temporary view, such as
131///   `array.as_::<Patched>().inner()`, outlives the view.
132///
133/// Encoding ext traits that build on the slot accessors take `TypedArrayRef<V>` as their
134/// supertrait; the blanket impl makes the accessors available on `&Self` in their default
135/// methods.
136///
137/// # Slot index annotations
138///
139/// - Fixed fields use `#[slot(N)]`, where `N` is the exact index of the slot.
140/// - A variadic tail uses `#[slot(N..)]`, where `N` is the index its first slot occupies.
141///
142/// The annotations are validated at compile time: the fixed indices must cover
143/// `0..FIXED_COUNT` exactly — no duplicates and no gaps — and a variadic tail must start
144/// immediately after the last fixed slot. A field without a `#[slot(..)]` attribute is a
145/// compile error, so the layout can never silently fall back to declaration order.
146///
147/// # Required vs optional slots
148///
149/// - `ArrayRef` — the slot must be present. `from_slots()` panics if `None`.
150///   The ext trait accessor and the view field are `&'a ArrayRef`.
151///
152/// - `Option<ArrayRef>` — the slot may be absent. `from_slots()` preserves `None`.
153///   The ext trait accessor and the view field are `Option<&'a ArrayRef>`.
154///
155/// The underlying storage is always `ArraySlots` — the field type only
156/// controls whether the macro inserts a `.vortex_expect()` unwrap or not.
157///
158/// # Field names
159///
160/// The ext trait accessor is named after the field. Because the accessors take an `ArrayView`
161/// by value, Rust picks them over `ArrayView`'s own `&self` methods, so a field whose name
162/// matches one of those methods (`validity`, `dtype`, `len`, ...) would hide it. Such field
163/// names are rejected; a validity slot, for example, is conventionally named `validity_child`.
164///
165/// # Variadic tail slots
166///
167/// One field may be `Vec<ArrayRef>`, declaring that every slot from its index onward
168/// belongs to a homogeneous, variable-length run of required slots. This supports
169/// encodings like `Chunked` (`[chunk_offsets, chunks...]`), `Struct`
170/// (`[validity?, fields...]`), and `Union` (`[type_ids, children...]`).
171///
172/// ```ignore
173/// #[array_slots(Chunked)]
174/// pub struct ChunkedSlots {
175///     #[slot(0)]
176///     pub chunk_offsets: ArrayRef,
177///     #[slot(1..)]
178///     pub chunks: Vec<ArrayRef>,
179/// }
180/// ```
181///
182/// For a struct with a variadic tail, the macro generates a different set of
183/// constants — slot count is no longer a compile-time constant:
184///
185/// ```ignore
186/// impl ChunkedSlots {
187///     pub const CHUNK_OFFSETS: usize = 0;
188///     /// Offset at which the `chunks` slots begin.
189///     pub const CHUNKS_OFFSET: usize = 1;
190///     /// Number of fixed (non-variadic) slots.
191///     pub const FIXED_COUNT: usize = 1;
192///     /// Names of the fixed slots in storage order.
193///     pub const FIXED_NAMES: [&'static str; 1] = ["chunk_offsets"];
194///
195///     /// Name of the slot at `idx`, e.g. "chunk_offsets" or "chunks[3]".
196///     pub fn slot_name(idx: usize) -> String { ... }
197///
198///     pub fn from_slots(slots: ArraySlots) -> Self { ... }
199///     pub fn into_slots(self) -> ArraySlots { ... }
200/// }
201/// ```
202///
203/// The view field and ext trait accessor for the tail are a `vortex_array::SlotSlice<'a>`,
204/// a borrowed run of required slots supporting `len()`, `get()`, `iter()`, and
205/// indexing:
206///
207/// ```ignore
208/// pub struct ChunkedSlotsView<'a> {
209///     pub chunk_offsets: &'a ArrayRef,
210///     pub chunks: SlotSlice<'a>,
211/// }
212///
213/// pub trait ChunkedArraySlotsExt<'a>: BorrowArraySlots<'a, Chunked> {
214///     fn chunk_offsets(self) -> &'a ArrayRef { ... }
215///     fn chunks(self) -> SlotSlice<'a> { ... }
216///     fn slots_view(self) -> ChunkedSlotsView<'a> { ... }
217/// }
218/// ```
219#[proc_macro_attribute]
220pub fn array_slots(attr: TokenStream, item: TokenStream) -> TokenStream {
221    let encoding = parse_macro_input!(attr as Path);
222    let item_struct = parse_macro_input!(item as ItemStruct);
223
224    match expand_array_slots(encoding, item_struct) {
225        Ok(tokens) => tokens.into(),
226        Err(err) => err.to_compile_error().into(),
227    }
228}
229
230fn expand_array_slots(
231    encoding: Path,
232    item_struct: ItemStruct,
233) -> syn::Result<proc_macro2::TokenStream> {
234    if !item_struct.generics.params.is_empty() || item_struct.generics.where_clause.is_some() {
235        return Err(syn::Error::new(
236            item_struct.generics.span(),
237            "#[array_slots] does not support generic slot structs",
238        ));
239    }
240
241    let fields = match &item_struct.fields {
242        Fields::Named(fields) => &fields.named,
243        _ => {
244            return Err(syn::Error::new(
245                item_struct.span(),
246                "#[array_slots] requires a struct with named fields",
247            ));
248        }
249    };
250
251    let encoding_ident = encoding
252        .segments
253        .last()
254        .map(|segment| &segment.ident)
255        .ok_or_else(|| syn::Error::new(encoding.span(), "missing encoding type"))?;
256
257    let struct_ident = item_struct.ident.clone();
258    let struct_vis = item_struct.vis.clone();
259    let view_ident = format_ident!("{}View", ident_name(&struct_ident));
260    let ext_ident = format_ident!("{}ArraySlotsExt", ident_name(encoding_ident));
261
262    let field_specs = fields
263        .iter()
264        .map(|field| SlotField::new(field, &struct_ident, &encoding))
265        .collect::<syn::Result<Vec<_>>>()?;
266
267    // The `#[slot(..)]` annotations, not the declaration order, define storage order.
268    let (fixed_specs, tail_spec) = partition_by_slot_index(&field_specs)?;
269
270    let idx_consts = fixed_specs.iter().copied().map(SlotField::idx_const);
271    let view_fields = field_specs.iter().map(SlotField::view_field);
272    let view_from_slots = field_specs.iter().map(SlotField::view_from_slots);
273    let view_to_owned = field_specs.iter().map(SlotField::view_to_owned);
274    let ext_methods = field_specs.iter().map(SlotField::ext_method);
275
276    let counts = gen_counts(&fixed_specs, tail_spec);
277    let from_slots = gen_from_slots(&fixed_specs, tail_spec);
278    let into_slots = gen_into_slots(&fixed_specs, tail_spec);
279
280    // `#[slot(..)]` is inert helper syntax consumed here; strip it from the emitted struct.
281    let item_struct = strip_slot_attrs(item_struct);
282
283    Ok(quote! {
284        #item_struct
285
286        impl #struct_ident {
287            #(#idx_consts)*
288
289            #counts
290
291            #[doc = "Convert owned slot storage into an owned slot struct."]
292            #from_slots
293
294            #[doc = "Convert this slot struct into storage order."]
295            #into_slots
296        }
297
298        #[derive(Clone, Copy, Debug)]
299        #[doc = concat!("Borrowed view of `", stringify!(#struct_ident), "`.")]
300        #struct_vis struct #view_ident<'a> {
301            #(#view_fields,)*
302        }
303
304        impl<'a> #view_ident<'a> {
305            #[doc = "Borrow a slot slice as a typed view."]
306            pub fn from_slots(slots: &'a [Option<::vortex_array::ArrayRef>]) -> Self {
307                Self {
308                    #(#view_from_slots,)*
309                }
310            }
311
312            #[doc = "Clone all referenced slots into an owned slot struct."]
313            pub fn to_owned(&self) -> #struct_ident {
314                #struct_ident {
315                    #(#view_to_owned,)*
316                }
317            }
318        }
319
320        #[doc = concat!("Typed slot accessors for `", stringify!(#encoding_ident), "` arrays.")]
321        #[doc = ""]
322        #[doc = "Implemented for `&'a T` where `T: TypedArrayRef`, and for `ArrayView<'a, _>`. The"]
323        #[doc = "accessors take `self` by value and return references borrowed for `'a`, so slots"]
324        #[doc = "read from a temporary `ArrayView` outlive the view."]
325        #struct_vis trait #ext_ident<'a>: ::vortex_array::BorrowArraySlots<'a, #encoding> {
326            #(#ext_methods)*
327
328            #[doc = "Returns a borrowed view of all slots."]
329            #[inline]
330            fn slots_view(self) -> #view_ident<'a> {
331                #view_ident::from_slots(
332                    ::vortex_array::BorrowArraySlots::<'a, #encoding>::borrow_slots(self),
333                )
334            }
335        }
336
337        impl<'a, S: ::vortex_array::BorrowArraySlots<'a, #encoding>> #ext_ident<'a> for S {}
338    })
339}
340
341/// Split the fields into the fixed slots (sorted by slot index) and the optional variadic
342/// tail, validating that the annotated indices describe a complete, gap-free layout.
343fn partition_by_slot_index(
344    field_specs: &[SlotField],
345) -> syn::Result<(Vec<&SlotField>, Option<&SlotField>)> {
346    let mut fixed_specs = Vec::with_capacity(field_specs.len());
347    let mut tail_spec: Option<&SlotField> = None;
348
349    for spec in field_specs {
350        if matches!(spec.slot_type, SlotFieldType::VariadicTail) {
351            if let Some(previous) = tail_spec {
352                return Err(syn::Error::new(
353                    spec.index_span,
354                    format!(
355                        "#[array_slots] allows at most one variadic tail, but `{}` is already \
356                         declared as one",
357                        previous.slot_name
358                    ),
359                ));
360            }
361            tail_spec = Some(spec);
362        } else {
363            fixed_specs.push(spec);
364        }
365    }
366
367    fixed_specs.sort_by_key(|spec| spec.index);
368
369    for (expected, spec) in fixed_specs.iter().enumerate() {
370        if spec.index == expected {
371            continue;
372        }
373        // `fixed_specs` is sorted, so a smaller index than expected means the previous
374        // field claimed the same slot, and a larger one means nothing claimed `expected`.
375        return Err(if spec.index < expected {
376            syn::Error::new(
377                spec.index_span,
378                format!(
379                    "#[array_slots] slot index {} is claimed by both `{}` and `{}`",
380                    spec.index,
381                    fixed_specs[expected - 1].slot_name,
382                    spec.slot_name
383                ),
384            )
385        } else {
386            syn::Error::new(
387                spec.index_span,
388                format!(
389                    "#[array_slots] no field claims slot index {expected}; fixed slot indices \
390                     must cover 0..{} without gaps",
391                    fixed_specs.len()
392                ),
393            )
394        });
395    }
396
397    if let Some(tail) = tail_spec
398        && tail.index != fixed_specs.len()
399    {
400        return Err(syn::Error::new(
401            tail.index_span,
402            format!(
403                "#[array_slots] variadic tail `{}` must start at slot index {}, immediately after \
404                 the {} fixed slot(s), but is annotated `#[slot({}..)]`",
405                tail.slot_name,
406                fixed_specs.len(),
407                fixed_specs.len(),
408                tail.index
409            ),
410        ));
411    }
412
413    Ok((fixed_specs, tail_spec))
414}
415
416/// Remove the inert `#[slot(..)]` helper attributes so the struct can be re-emitted.
417fn strip_slot_attrs(mut item_struct: ItemStruct) -> ItemStruct {
418    if let Fields::Named(fields) = &mut item_struct.fields {
419        for field in &mut fields.named {
420            field.attrs.retain(|attr| !attr.path().is_ident(SLOT_ATTR));
421        }
422    }
423    item_struct
424}
425
426fn gen_counts(
427    fixed_specs: &[&SlotField],
428    tail_spec: Option<&SlotField>,
429) -> proc_macro2::TokenStream {
430    let names = fixed_specs.iter().map(|field| field.slot_name.as_str());
431    let fixed_count = fixed_specs.len();
432
433    match tail_spec {
434        None => quote! {
435            #[doc = "Total number of slots."]
436            pub const COUNT: usize = #fixed_count;
437
438            #[doc = "Slot names in storage order."]
439            pub const NAMES: [&'static str; #fixed_count] = [#(#names),*];
440        },
441        Some(tail) => {
442            let offset_const = &tail.const_ident;
443            let tail_name = &tail.slot_name;
444            quote! {
445                #[doc = concat!("Offset at which the `", #tail_name, "` slots begin.")]
446                pub const #offset_const: usize = #fixed_count;
447
448                #[doc = "Number of fixed (non-variadic) slots."]
449                pub const FIXED_COUNT: usize = #fixed_count;
450
451                #[doc = "Names of the fixed slots in storage order."]
452                pub const FIXED_NAMES: [&'static str; #fixed_count] = [#(#names),*];
453
454                #[doc = "Name of the slot at the given index."]
455                pub fn slot_name(idx: usize) -> String {
456                    if idx < Self::FIXED_COUNT {
457                        Self::FIXED_NAMES[idx].to_string()
458                    } else {
459                        format!(concat!(#tail_name, "[{}]"), idx - Self::#offset_const)
460                    }
461                }
462            }
463        }
464    }
465}
466
467fn gen_from_slots(
468    fixed_specs: &[&SlotField],
469    tail_spec: Option<&SlotField>,
470) -> proc_macro2::TokenStream {
471    let owned_from_slots = fixed_specs.iter().copied().map(SlotField::owned_from_slots);
472
473    match tail_spec {
474        None => quote! {
475            pub fn from_slots(mut slots: ::vortex_array::ArraySlots) -> Self {
476                Self {
477                    #(#owned_from_slots,)*
478                }
479            }
480        },
481        Some(tail) => {
482            let tail_ident = &tail.field_ident;
483            let offset_const = &tail.const_ident;
484            let expect_message = &tail.expect_message;
485            quote! {
486                pub fn from_slots(mut slots: ::vortex_array::ArraySlots) -> Self {
487                    let __variadic_tail: ::std::vec::Vec<::vortex_array::ArrayRef> = slots
488                        .drain(Self::#offset_const..)
489                        .map(|slot| ::vortex_error::VortexExpect::vortex_expect(
490                            slot,
491                            #expect_message,
492                        ))
493                        .collect();
494                    Self {
495                        #(#owned_from_slots,)*
496                        #tail_ident: __variadic_tail,
497                    }
498                }
499            }
500        }
501    }
502}
503
504fn gen_into_slots(
505    fixed_specs: &[&SlotField],
506    tail_spec: Option<&SlotField>,
507) -> proc_macro2::TokenStream {
508    let fixed_into_slots = fixed_specs.iter().copied().map(SlotField::storage_slot);
509
510    match tail_spec {
511        None => quote! {
512            pub fn into_slots(self) -> ::vortex_array::ArraySlots {
513                ::vortex_array::smallvec::smallvec![#(#fixed_into_slots),*]
514            }
515        },
516        Some(tail) => {
517            let tail_ident = &tail.field_ident;
518            quote! {
519                pub fn into_slots(self) -> ::vortex_array::ArraySlots {
520                    let mut slots: ::vortex_array::ArraySlots =
521                        ::vortex_array::smallvec::smallvec![#(#fixed_into_slots),*];
522                    slots.extend(self.#tail_ident.into_iter().map(Some));
523                    slots
524                }
525            }
526        }
527    }
528}
529
530struct SlotField {
531    field_ident: Ident,
532    field_vis: Visibility,
533    const_ident: Ident,
534    slot_name: String,
535    slot_type: SlotFieldType,
536    index: usize,
537    index_span: Span,
538    expect_message: syn::LitStr,
539    struct_ident: Ident,
540    encoding: Path,
541}
542
543impl SlotField {
544    fn new(field: &Field, struct_ident: &Ident, encoding: &Path) -> syn::Result<Self> {
545        let field_ident = field
546            .ident
547            .clone()
548            .ok_or_else(|| syn::Error::new(field.span(), "slot fields must be named"))?;
549        let field_name = ident_name(&field_ident);
550        let slot_type = SlotFieldType::from_syn_type(&field.ty)?;
551        let annotation = SlotIndexAttr::from_field(field, &field_name)?;
552
553        match (slot_type, annotation.variadic) {
554            (SlotFieldType::VariadicTail, false) => {
555                return Err(syn::Error::new(
556                    annotation.span,
557                    format!(
558                        "`{field_name}` is a variadic `Vec<ArrayRef>` tail, so it must be \
559                         annotated `#[slot({}..)]`",
560                        annotation.index
561                    ),
562                ));
563            }
564            (SlotFieldType::Required | SlotFieldType::Optional, true) => {
565                return Err(syn::Error::new(
566                    annotation.span,
567                    format!(
568                        "`#[slot(N..)]` declares a variadic `Vec<ArrayRef>` tail; `{field_name}` \
569                         occupies a single slot, so annotate it `#[slot({})]`",
570                        annotation.index
571                    ),
572                ));
573            }
574            _ => {}
575        }
576
577        let const_ident = match slot_type {
578            SlotFieldType::VariadicTail => {
579                format_ident!("{}_OFFSET", to_screaming_snake_case(&field_name))
580            }
581            _ => format_ident!("{}", to_screaming_snake_case(&field_name)),
582        };
583        let expect_message = syn::LitStr::new(
584            &format!("{} {} slot", ident_name(struct_ident), field_name),
585            field.span(),
586        );
587
588        if RESERVED_FIELD_NAMES.contains(&field_name.as_str()) {
589            return Err(syn::Error::new(
590                field_ident.span(),
591                format!(
592                    "the slot field `{field_name}` would generate an accessor that shadows \
593                     `ArrayView::{field_name}`; rename the field, e.g. to `{field_name}_child`"
594                ),
595            ));
596        }
597
598        Ok(Self {
599            field_ident,
600            field_vis: field.vis.clone(),
601            const_ident,
602            slot_name: field_name,
603            slot_type,
604            index: annotation.index,
605            index_span: annotation.span,
606            expect_message,
607            struct_ident: struct_ident.clone(),
608            encoding: encoding.clone(),
609        })
610    }
611
612    fn idx_const(&self) -> proc_macro2::TokenStream {
613        let const_ident = &self.const_ident;
614        let index = self.index;
615        let slot_name = &self.slot_name;
616
617        quote! {
618            #[doc = concat!("Slot index for `", #slot_name, "`.")]
619            pub const #const_ident: usize = #index;
620        }
621    }
622
623    fn view_field(&self) -> proc_macro2::TokenStream {
624        let field_ident = &self.field_ident;
625        let field_vis = &self.field_vis;
626        let ty = self.slot_type.view_field_ty();
627
628        quote! {
629            #field_vis #field_ident: #ty
630        }
631    }
632
633    /// The expression that reads this field out of a borrowed `slots` slice, whose lifetime
634    /// the result carries.
635    fn borrow_from_slots(&self, slots: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
636        let struct_ident = &self.struct_ident;
637        let const_ident = &self.const_ident;
638        let expect_message = &self.expect_message;
639
640        match self.slot_type {
641            SlotFieldType::Required => quote! {
642                ::vortex_error::VortexExpect::vortex_expect(
643                    #slots[#struct_ident::#const_ident].as_ref(),
644                    #expect_message,
645                )
646            },
647            SlotFieldType::Optional => quote! {
648                #slots[#struct_ident::#const_ident].as_ref()
649            },
650            SlotFieldType::VariadicTail => quote! {
651                ::vortex_array::SlotSlice::new(
652                    &#slots[#struct_ident::#const_ident..],
653                    #expect_message,
654                )
655            },
656        }
657    }
658
659    fn view_from_slots(&self) -> proc_macro2::TokenStream {
660        let field_ident = &self.field_ident;
661        let value = self.borrow_from_slots(&quote! { slots });
662
663        quote! {
664            #field_ident: #value
665        }
666    }
667
668    fn view_to_owned(&self) -> proc_macro2::TokenStream {
669        let field_ident = &self.field_ident;
670
671        match self.slot_type {
672            SlotFieldType::Required => quote! {
673                #field_ident: ::std::clone::Clone::clone(self.#field_ident)
674            },
675            SlotFieldType::Optional => quote! {
676                #field_ident: self.#field_ident.cloned()
677            },
678            SlotFieldType::VariadicTail => quote! {
679                #field_ident: self.#field_ident.to_vec()
680            },
681        }
682    }
683
684    fn owned_from_slots(&self) -> proc_macro2::TokenStream {
685        let field_ident = &self.field_ident;
686        let struct_ident = &self.struct_ident;
687        let const_ident = &self.const_ident;
688        let expect_message = &self.expect_message;
689
690        match self.slot_type {
691            SlotFieldType::Required => quote! {
692                #field_ident: ::vortex_error::VortexExpect::vortex_expect(
693                    slots[#struct_ident::#const_ident].take(),
694                    #expect_message,
695                )
696            },
697            SlotFieldType::Optional => quote! {
698                #field_ident: slots[#struct_ident::#const_ident].take()
699            },
700            SlotFieldType::VariadicTail => {
701                unreachable!("variadic tail is drained before fixed fields")
702            }
703        }
704    }
705
706    fn storage_slot(&self) -> proc_macro2::TokenStream {
707        let field_ident = &self.field_ident;
708
709        match self.slot_type {
710            SlotFieldType::Required => quote! {
711                Some(self.#field_ident)
712            },
713            SlotFieldType::Optional => quote! {
714                self.#field_ident
715            },
716            SlotFieldType::VariadicTail => {
717                unreachable!("variadic tail is appended after fixed fields")
718            }
719        }
720    }
721
722    fn ext_method(&self) -> proc_macro2::TokenStream {
723        let field_ident = &self.field_ident;
724        let ty = self.slot_type.view_field_ty();
725        let slot_name = &self.slot_name;
726        let encoding = &self.encoding;
727        let value = self.borrow_from_slots(&quote! {
728            ::vortex_array::BorrowArraySlots::<'a, #encoding>::borrow_slots(self)
729        });
730
731        quote! {
732            #[doc = concat!("Returns the `", #slot_name, "` slot.")]
733            #[inline]
734            fn #field_ident(self) -> #ty {
735                #value
736            }
737        }
738    }
739}
740
741/// A parsed `#[slot(N)]` or `#[slot(N..)]` field annotation.
742struct SlotIndexAttr {
743    index: usize,
744    /// Whether the trailing `..` was present, marking a variadic tail.
745    variadic: bool,
746    span: Span,
747}
748
749impl SlotIndexAttr {
750    fn from_field(field: &Field, field_name: &str) -> syn::Result<Self> {
751        let mut annotation = None;
752        for attr in &field.attrs {
753            if !attr.path().is_ident(SLOT_ATTR) {
754                continue;
755            }
756            if annotation.is_some() {
757                return Err(syn::Error::new(
758                    attr.span(),
759                    format!("`{field_name}` has more than one `#[slot(..)]` attribute"),
760                ));
761            }
762            annotation = Some(attr.parse_args::<Self>()?);
763        }
764
765        annotation.ok_or_else(|| {
766            syn::Error::new(
767                field.span(),
768                format!(
769                    "`{field_name}` is missing a `#[slot(N)]` attribute; every field of an \
770                     `#[array_slots]` struct must pin itself to a slot index so that reordering \
771                     field declarations cannot change the slot layout"
772                ),
773            )
774        })
775    }
776}
777
778impl Parse for SlotIndexAttr {
779    fn parse(input: ParseStream) -> syn::Result<Self> {
780        let literal: LitInt = input.parse()?;
781        let index = literal.base10_parse::<usize>()?;
782        let variadic = input.peek(Token![..]);
783        if variadic {
784            input.parse::<Token![..]>()?;
785        }
786        if !input.is_empty() {
787            return Err(input.error("expected `#[slot(N)]` or `#[slot(N..)]`"));
788        }
789
790        Ok(Self {
791            index,
792            variadic,
793            span: literal.span(),
794        })
795    }
796}
797
798#[derive(Clone, Copy)]
799enum SlotFieldType {
800    Required,
801    Optional,
802    VariadicTail,
803}
804
805impl SlotFieldType {
806    fn from_syn_type(ty: &Type) -> syn::Result<Self> {
807        if is_array_ref_type(ty) {
808            return Ok(Self::Required);
809        }
810
811        if let Some(inner_ty) = wrapper_inner_type(ty, "Option")
812            && is_array_ref_type(inner_ty)
813        {
814            return Ok(Self::Optional);
815        }
816
817        if let Some(inner_ty) = wrapper_inner_type(ty, "Vec")
818            && is_array_ref_type(inner_ty)
819        {
820            return Ok(Self::VariadicTail);
821        }
822
823        Err(syn::Error::new(
824            ty.span(),
825            "#[array_slots] fields must be ArrayRef, Option<ArrayRef>, or Vec<ArrayRef>",
826        ))
827    }
828
829    fn view_field_ty(self) -> proc_macro2::TokenStream {
830        match self {
831            Self::Required => quote! { &'a ::vortex_array::ArrayRef },
832            Self::Optional => quote! { Option<&'a ::vortex_array::ArrayRef> },
833            Self::VariadicTail => quote! { ::vortex_array::SlotSlice<'a> },
834        }
835    }
836}
837
838fn is_array_ref_type(ty: &Type) -> bool {
839    matches!(
840        ty,
841        Type::Path(type_path)
842            if type_path.qself.is_none()
843                && type_path
844                    .path
845                    .segments
846                    .last()
847                    .is_some_and(|segment| segment.ident == "ArrayRef")
848    )
849}
850
851fn wrapper_inner_type<'a>(ty: &'a Type, wrapper: &str) -> Option<&'a Type> {
852    let Type::Path(type_path) = ty else {
853        return None;
854    };
855    let segment = type_path.path.segments.last()?;
856    if segment.ident != wrapper {
857        return None;
858    }
859
860    let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {
861        return None;
862    };
863
864    match args.args.first()? {
865        syn::GenericArgument::Type(inner_ty) => Some(inner_ty),
866        _ => None,
867    }
868}
869
870fn ident_name(ident: &Ident) -> String {
871    ident.to_string().trim_start_matches("r#").to_owned()
872}
873
874fn to_screaming_snake_case(name: &str) -> String {
875    let mut result = String::with_capacity(name.len());
876    let mut prev_is_lower_or_digit = false;
877
878    for ch in name.chars() {
879        if ch.is_ascii_uppercase() && prev_is_lower_or_digit {
880            result.push('_');
881        }
882        result.push(ch.to_ascii_uppercase());
883        prev_is_lower_or_digit = ch.is_ascii_lowercase() || ch.is_ascii_digit();
884    }
885
886    result
887}