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
use proc_macro2::TokenStream;
use quote::quote;

#[expect(clippy::too_many_arguments)]
pub fn cuda_struct_declaration(
    crate_path: &syn::Path,
    struct_attrs_cuda: &[syn::Attribute],
    struct_layout_attrs: &[syn::Attribute],
    struct_vis_cuda: &syn::Visibility,
    struct_name_cuda: &syn::Ident,
    struct_generics_cuda: &syn::Generics,
    struct_fields_cuda: &syn::Fields,
    struct_semi_cuda: Option<syn::token::Semi>,
) -> TokenStream {
    let (_impl_generics, _ty_generics, where_clause) = struct_generics_cuda.split_for_impl();

    let struct_repr = if struct_attrs_cuda
        .iter()
        .any(|attr| attr.path().is_ident("repr"))
    {
        quote! {}
    } else {
        quote! { #[repr(C)] }
    };

    #[expect(clippy::option_if_let_else)]
    let struct_fields_where_clause = if let Some(struct_semi_cuda) = struct_semi_cuda {
        quote!(#struct_fields_cuda #where_clause #struct_semi_cuda)
    } else {
        quote!(#where_clause #struct_fields_cuda)
    };

    let const_type_layout_crate_path = quote! { #crate_path::deps::const_type_layout }.to_string();

    quote! {
        #[allow(dead_code)]
        #[doc(hidden)]
        #(#struct_attrs_cuda)*
        #[derive(#crate_path::deps::const_type_layout::TypeLayout)]
        #struct_repr
        #(#struct_layout_attrs)*
        #[layout(crate = #const_type_layout_crate_path)]
        #struct_vis_cuda struct #struct_name_cuda #struct_generics_cuda #struct_fields_where_clause
    }
}

#[expect(clippy::too_many_arguments)]
pub fn rust_to_cuda_trait(
    crate_path: &syn::Path,
    struct_name: &syn::Ident,
    struct_name_cuda: &syn::Ident,
    struct_generics_cuda: &syn::Generics,
    struct_fields_cuda: &syn::Fields,
    combined_cuda_alloc_type: &TokenStream,
    r2c_field_declarations: &[TokenStream],
    r2c_field_initialisations: &[TokenStream],
    r2c_field_destructors: &[TokenStream],
) -> TokenStream {
    let rust_to_cuda_struct_construction = match struct_fields_cuda {
        syn::Fields::Named(_) => quote! {
            #struct_name_cuda {
                #(#r2c_field_initialisations)*
            }
        },
        syn::Fields::Unnamed(_) => quote! {
            #struct_name_cuda (
                #(#r2c_field_initialisations)*
            )
        },
        syn::Fields::Unit => quote! { #struct_name_cuda },
    };

    let (impl_generics, ty_generics, where_clause) = struct_generics_cuda.split_for_impl();

    quote! {
        unsafe impl #impl_generics #crate_path::lend::RustToCuda for #struct_name #ty_generics
            #where_clause
        {
            type CudaRepresentation = #struct_name_cuda #ty_generics;

            type CudaAllocation = #combined_cuda_alloc_type;

            #[cfg(not(target_os = "cuda"))]
            unsafe fn borrow<CudaAllocType: #crate_path::alloc::CudaAlloc>(
                &self,
                alloc: CudaAllocType,
            ) -> #crate_path::deps::rustacuda::error::CudaResult<(
                #crate_path::utils::ffi::DeviceAccessible<Self::CudaRepresentation>,
                #crate_path::alloc::CombinedCudaAlloc<Self::CudaAllocation, CudaAllocType>
            )> {
                let alloc_front = #crate_path::alloc::NoCudaAlloc;
                let alloc_tail = alloc;

                #(#r2c_field_declarations)*

                let borrow = #rust_to_cuda_struct_construction;

                Ok((
                    #crate_path::utils::ffi::DeviceAccessible::from(borrow),
                    #crate_path::alloc::CombinedCudaAlloc::new(alloc_front, alloc_tail)
                ))
            }

            #[cfg(not(target_os = "cuda"))]
            unsafe fn restore<CudaAllocType: #crate_path::alloc::CudaAlloc>(
                &mut self,
                alloc: #crate_path::alloc::CombinedCudaAlloc<
                    Self::CudaAllocation, CudaAllocType
                >,
            ) -> #crate_path::deps::rustacuda::error::CudaResult<CudaAllocType> {
                let (alloc_front, alloc_tail) = alloc.split();

                #(#r2c_field_destructors)*

                Ok(alloc_tail)
            }
        }
    }
}

#[expect(clippy::too_many_arguments)]
pub fn rust_to_cuda_async_trait(
    crate_path: &syn::Path,
    struct_name: &syn::Ident,
    struct_name_cuda: &syn::Ident,
    struct_generics_cuda_async: &syn::Generics,
    struct_fields_cuda: &syn::Fields,
    combined_cuda_alloc_async_type: &TokenStream,
    r2c_field_async_declarations: &[TokenStream],
    r2c_field_async_completions: &[syn::Ident],
    r2c_field_initialisations: &[TokenStream],
    r2c_field_async_destructors: &[TokenStream],
    r2c_field_async_completion_calls: &[TokenStream],
) -> TokenStream {
    let rust_to_cuda_struct_construction = match struct_fields_cuda {
        syn::Fields::Named(_) => quote! {
            #struct_name_cuda {
                #(#r2c_field_initialisations)*
            }
        },
        syn::Fields::Unnamed(_) => quote! {
            #struct_name_cuda (
                #(#r2c_field_initialisations)*
            )
        },
        syn::Fields::Unit => quote! { #struct_name_cuda },
    };

    let async_borrow_completion = if r2c_field_async_completions.is_empty() {
        quote! { #crate_path::utils::r#async::Async::ready(borrow, stream) }
    } else {
        quote! {
            if #(#r2c_field_async_completions.is_none())&&* {
                #crate_path::utils::r#async::Async::ready(borrow, stream)
            } else {
                #crate_path::utils::r#async::Async::pending(
                    borrow, stream, #crate_path::utils::r#async::NoCompletion,
                )?
            }
        }
    };

    let async_restore_completion = if r2c_field_async_completions.is_empty() {
        quote! { #crate_path::utils::r#async::Async::ready(this, stream) }
    } else {
        quote! {
            if #(#r2c_field_async_completions.is_none())&&* {
                #crate_path::utils::r#async::Async::ready(this, stream)
            } else {
                #crate_path::utils::r#async::Async::<
                    _, #crate_path::utils::r#async::CompletionFnMut<Self>,
                >::pending(
                    this, stream, #crate_path::deps::alloc::boxed::Box::new(|this| {
                        #(#r2c_field_async_completion_calls)*
                        Ok(())
                    }),
                )?
            }
        }
    };

    let (impl_generics, ty_generics, where_clause) = struct_generics_cuda_async.split_for_impl();

    quote! {
        unsafe impl #impl_generics #crate_path::lend::RustToCudaAsync for #struct_name #ty_generics
            #where_clause
        {
            type CudaAllocationAsync = #combined_cuda_alloc_async_type;

            #[cfg(not(target_os = "cuda"))]
            unsafe fn borrow_async<'stream, CudaAllocType: #crate_path::alloc::CudaAlloc>(
                &self,
                alloc: CudaAllocType,
                stream: #crate_path::host::Stream<'stream>,
            ) -> #crate_path::deps::rustacuda::error::CudaResult<(
                #crate_path::utils::r#async::Async<
                    '_, 'stream,
                    #crate_path::utils::ffi::DeviceAccessible<Self::CudaRepresentation>,
                >,
                #crate_path::alloc::CombinedCudaAlloc<Self::CudaAllocationAsync, CudaAllocType>,
            )> {
                let alloc_front = #crate_path::alloc::NoCudaAlloc;
                let alloc_tail = alloc;

                #(#r2c_field_async_declarations)*

                let borrow = #rust_to_cuda_struct_construction;
                let borrow = #crate_path::utils::ffi::DeviceAccessible::from(borrow);

                let r#async = #async_borrow_completion;
                let alloc = #crate_path::alloc::CombinedCudaAlloc::new(alloc_front, alloc_tail);

                Ok((r#async, alloc))
            }

            #[cfg(not(target_os = "cuda"))]
            unsafe fn restore_async<'a, 'stream, CudaAllocType: #crate_path::alloc::CudaAlloc, CudaRestoreOwner>(
                this: #crate_path::deps::owning_ref::BoxRefMut<'a, CudaRestoreOwner, Self>,
                alloc: #crate_path::alloc::CombinedCudaAlloc<
                    Self::CudaAllocationAsync, CudaAllocType
                >,
                stream: #crate_path::host::Stream<'stream>,
            ) -> #crate_path::deps::rustacuda::error::CudaResult<(
                #crate_path::utils::r#async::Async<
                    'a, 'stream,
                    #crate_path::deps::owning_ref::BoxRefMut<'a, CudaRestoreOwner, Self>,
                    #crate_path::utils::r#async::CompletionFnMut<'a, Self>,
                >,
                CudaAllocType,
            )> {
                let (alloc_front, alloc_tail) = alloc.split();

                #(#r2c_field_async_destructors)*

                let r#async = #async_restore_completion;

                Ok((r#async, alloc_tail))
            }
        }
    }
}

pub fn cuda_as_rust_trait(
    crate_path: &syn::Path,
    struct_name: &syn::Ident,
    struct_name_cuda: &syn::Ident,
    struct_generics_cuda: &syn::Generics,
    struct_fields_cuda: &syn::Fields,
    c2r_field_initialisations: &[TokenStream],
) -> TokenStream {
    let cuda_as_rust_struct_construction = match struct_fields_cuda {
        syn::Fields::Named(_) => quote! {
            #struct_name {
                #(#c2r_field_initialisations)*
            }
        },
        syn::Fields::Unnamed(_) => quote! {
            #struct_name (
                #(#c2r_field_initialisations)*
            )
        },
        syn::Fields::Unit => quote! { #struct_name },
    };

    let (impl_generics, ty_generics, where_clause) = &struct_generics_cuda.split_for_impl();

    quote! {
        unsafe impl #impl_generics #crate_path::lend::CudaAsRust
            for #struct_name_cuda #ty_generics #where_clause
        {
            type RustRepresentation = #struct_name #ty_generics;

            #[cfg(target_os = "cuda")]
            unsafe fn as_rust(
                this: &#crate_path::utils::ffi::DeviceAccessible<Self>,
            ) -> #struct_name #ty_generics {
                #cuda_as_rust_struct_construction
            }
        }
    }
}