xref: /linux/rust/pin-init/src/macros.rs (revision d7659acca7a390b5830f0b67f3aa4a5f9929ab79)
1 // SPDX-License-Identifier: Apache-2.0 OR MIT
2 
3 //! This module provides the macros that actually implement the proc-macros `pin_data` and
4 //! `pinned_drop`. It also contains `__init_internal` the implementation of the `{try_}{pin_}init!`
5 //! macros.
6 //!
7 //! These macros should never be called directly, since they expect their input to be
8 //! in a certain format which is internal. If used incorrectly, these macros can lead to UB even in
9 //! safe code! Use the public facing macros instead.
10 //!
11 //! This architecture has been chosen because the kernel does not yet have access to `syn` which
12 //! would make matters a lot easier for implementing these as proc-macros.
13 //!
14 //! # Macro expansion example
15 //!
16 //! This section is intended for readers trying to understand the macros in this module and the
17 //! `pin_init!` macros from `init.rs`.
18 //!
19 //! We will look at the following example:
20 //!
21 //! ```rust,ignore
22 //! # use kernel::init::*;
23 //! # use core::pin::Pin;
24 //! #[pin_data]
25 //! #[repr(C)]
26 //! struct Bar<T> {
27 //!     #[pin]
28 //!     t: T,
29 //!     pub x: usize,
30 //! }
31 //!
32 //! impl<T> Bar<T> {
33 //!     fn new(t: T) -> impl PinInit<Self> {
34 //!         pin_init!(Self { t, x: 0 })
35 //!     }
36 //! }
37 //!
38 //! #[pin_data(PinnedDrop)]
39 //! struct Foo {
40 //!     a: usize,
41 //!     #[pin]
42 //!     b: Bar<u32>,
43 //! }
44 //!
45 //! #[pinned_drop]
46 //! impl PinnedDrop for Foo {
47 //!     fn drop(self: Pin<&mut Self>) {
48 //!         pr_info!("{self:p} is getting dropped.");
49 //!     }
50 //! }
51 //!
52 //! let a = 42;
53 //! let initializer = pin_init!(Foo {
54 //!     a,
55 //!     b <- Bar::new(36),
56 //! });
57 //! ```
58 //!
59 //! This example includes the most common and important features of the pin-init API.
60 //!
61 //! Below you can find individual section about the different macro invocations. Here are some
62 //! general things we need to take into account when designing macros:
63 //! - use global paths, similarly to file paths, these start with the separator: `::core::panic!()`
64 //!   this ensures that the correct item is used, since users could define their own `mod core {}`
65 //!   and then their own `panic!` inside to execute arbitrary code inside of our macro.
66 //! - macro `unsafe` hygiene: we need to ensure that we do not expand arbitrary, user-supplied
67 //!   expressions inside of an `unsafe` block in the macro, because this would allow users to do
68 //!   `unsafe` operations without an associated `unsafe` block.
69 //!
70 //! ## `#[pin_data]` on `Bar`
71 //!
72 //! This macro is used to specify which fields are structurally pinned and which fields are not. It
73 //! is placed on the struct definition and allows `#[pin]` to be placed on the fields.
74 //!
75 //! Here is the definition of `Bar` from our example:
76 //!
77 //! ```rust,ignore
78 //! # use kernel::init::*;
79 //! #[pin_data]
80 //! #[repr(C)]
81 //! struct Bar<T> {
82 //!     #[pin]
83 //!     t: T,
84 //!     pub x: usize,
85 //! }
86 //! ```
87 //!
88 //! This expands to the following code:
89 //!
90 //! ```rust,ignore
91 //! // Firstly the normal definition of the struct, attributes are preserved:
92 //! #[repr(C)]
93 //! struct Bar<T> {
94 //!     t: T,
95 //!     pub x: usize,
96 //! }
97 //! // Then an anonymous constant is defined, this is because we do not want any code to access the
98 //! // types that we define inside:
99 //! const _: () = {
100 //!     // We define the pin-data carrying struct, it is a ZST and needs to have the same generics,
101 //!     // since we need to implement access functions for each field and thus need to know its
102 //!     // type.
103 //!     struct __ThePinData<T> {
104 //!         __phantom: ::core::marker::PhantomData<fn(Bar<T>) -> Bar<T>>,
105 //!     }
106 //!     // We implement `Copy` for the pin-data struct, since all functions it defines will take
107 //!     // `self` by value.
108 //!     impl<T> ::core::clone::Clone for __ThePinData<T> {
109 //!         fn clone(&self) -> Self {
110 //!             *self
111 //!         }
112 //!     }
113 //!     impl<T> ::core::marker::Copy for __ThePinData<T> {}
114 //!     // For every field of `Bar`, the pin-data struct will define a function with the same name
115 //!     // and accessor (`pub` or `pub(crate)` etc.). This function will take a pointer to the
116 //!     // field (`slot`) and a `PinInit` or `Init` depending on the projection kind of the field
117 //!     // (if pinning is structural for the field, then `PinInit` otherwise `Init`).
118 //!     #[allow(dead_code)]
119 //!     impl<T> __ThePinData<T> {
120 //!         unsafe fn t<E>(
121 //!             self,
122 //!             slot: *mut T,
123 //!             // Since `t` is `#[pin]`, this is `PinInit`.
124 //!             init: impl ::kernel::init::PinInit<T, E>,
125 //!         ) -> ::core::result::Result<(), E> {
126 //!             unsafe { ::kernel::init::PinInit::__pinned_init(init, slot) }
127 //!         }
128 //!         pub unsafe fn x<E>(
129 //!             self,
130 //!             slot: *mut usize,
131 //!             // Since `x` is not `#[pin]`, this is `Init`.
132 //!             init: impl ::kernel::init::Init<usize, E>,
133 //!         ) -> ::core::result::Result<(), E> {
134 //!             unsafe { ::kernel::init::Init::__init(init, slot) }
135 //!         }
136 //!     }
137 //!     // Implement the internal `HasPinData` trait that associates `Bar` with the pin-data struct
138 //!     // that we constructed above.
139 //!     unsafe impl<T> ::kernel::init::__internal::HasPinData for Bar<T> {
140 //!         type PinData = __ThePinData<T>;
141 //!         unsafe fn __pin_data() -> Self::PinData {
142 //!             __ThePinData {
143 //!                 __phantom: ::core::marker::PhantomData,
144 //!             }
145 //!         }
146 //!     }
147 //!     // Implement the internal `PinData` trait that marks the pin-data struct as a pin-data
148 //!     // struct. This is important to ensure that no user can implement a rogue `__pin_data`
149 //!     // function without using `unsafe`.
150 //!     unsafe impl<T> ::kernel::init::__internal::PinData for __ThePinData<T> {
151 //!         type Datee = Bar<T>;
152 //!     }
153 //!     // Now we only want to implement `Unpin` for `Bar` when every structurally pinned field is
154 //!     // `Unpin`. In other words, whether `Bar` is `Unpin` only depends on structurally pinned
155 //!     // fields (those marked with `#[pin]`). These fields will be listed in this struct, in our
156 //!     // case no such fields exist, hence this is almost empty. The two phantomdata fields exist
157 //!     // for two reasons:
158 //!     // - `__phantom`: every generic must be used, since we cannot really know which generics
159 //!     //   are used, we declare all and then use everything here once.
160 //!     // - `__phantom_pin`: uses the `'__pin` lifetime and ensures that this struct is invariant
161 //!     //   over it. The lifetime is needed to work around the limitation that trait bounds must
162 //!     //   not be trivial, e.g. the user has a `#[pin] PhantomPinned` field -- this is
163 //!     //   unconditionally `!Unpin` and results in an error. The lifetime tricks the compiler
164 //!     //   into accepting these bounds regardless.
165 //!     #[allow(dead_code)]
166 //!     struct __Unpin<'__pin, T> {
167 //!         __phantom_pin: ::core::marker::PhantomData<fn(&'__pin ()) -> &'__pin ()>,
168 //!         __phantom: ::core::marker::PhantomData<fn(Bar<T>) -> Bar<T>>,
169 //!         // Our only `#[pin]` field is `t`.
170 //!         t: T,
171 //!     }
172 //!     #[doc(hidden)]
173 //!     impl<'__pin, T> ::core::marker::Unpin for Bar<T>
174 //!     where
175 //!         __Unpin<'__pin, T>: ::core::marker::Unpin,
176 //!     {}
177 //!     // Now we need to ensure that `Bar` does not implement `Drop`, since that would give users
178 //!     // access to `&mut self` inside of `drop` even if the struct was pinned. This could lead to
179 //!     // UB with only safe code, so we disallow this by giving a trait implementation error using
180 //!     // a direct impl and a blanket implementation.
181 //!     trait MustNotImplDrop {}
182 //!     // Normally `Drop` bounds do not have the correct semantics, but for this purpose they do
183 //!     // (normally people want to know if a type has any kind of drop glue at all, here we want
184 //!     // to know if it has any kind of custom drop glue, which is exactly what this bound does).
185 //!     #[expect(drop_bounds)]
186 //!     impl<T: ::core::ops::Drop> MustNotImplDrop for T {}
187 //!     impl<T> MustNotImplDrop for Bar<T> {}
188 //!     // Here comes a convenience check, if one implemented `PinnedDrop`, but forgot to add it to
189 //!     // `#[pin_data]`, then this will error with the same mechanic as above, this is not needed
190 //!     // for safety, but a good sanity check, since no normal code calls `PinnedDrop::drop`.
191 //!     #[expect(non_camel_case_types)]
192 //!     trait UselessPinnedDropImpl_you_need_to_specify_PinnedDrop {}
193 //!     impl<
194 //!         T: ::kernel::init::PinnedDrop,
195 //!     > UselessPinnedDropImpl_you_need_to_specify_PinnedDrop for T {}
196 //!     impl<T> UselessPinnedDropImpl_you_need_to_specify_PinnedDrop for Bar<T> {}
197 //! };
198 //! ```
199 //!
200 //! ## `pin_init!` in `impl Bar`
201 //!
202 //! This macro creates an pin-initializer for the given struct. It requires that the struct is
203 //! annotated by `#[pin_data]`.
204 //!
205 //! Here is the impl on `Bar` defining the new function:
206 //!
207 //! ```rust,ignore
208 //! impl<T> Bar<T> {
209 //!     fn new(t: T) -> impl PinInit<Self> {
210 //!         pin_init!(Self { t, x: 0 })
211 //!     }
212 //! }
213 //! ```
214 //!
215 //! This expands to the following code:
216 //!
217 //! ```rust,ignore
218 //! impl<T> Bar<T> {
219 //!     fn new(t: T) -> impl PinInit<Self> {
220 //!         {
221 //!             // We do not want to allow arbitrary returns, so we declare this type as the `Ok`
222 //!             // return type and shadow it later when we insert the arbitrary user code. That way
223 //!             // there will be no possibility of returning without `unsafe`.
224 //!             struct __InitOk;
225 //!             // Get the data about fields from the supplied type.
226 //!             // - the function is unsafe, hence the unsafe block
227 //!             // - we `use` the `HasPinData` trait in the block, it is only available in that
228 //!             //   scope.
229 //!             let data = unsafe {
230 //!                 use ::kernel::init::__internal::HasPinData;
231 //!                 Self::__pin_data()
232 //!             };
233 //!             // Ensure that `data` really is of type `PinData` and help with type inference:
234 //!             let init = ::kernel::init::__internal::PinData::make_closure::<
235 //!                 _,
236 //!                 __InitOk,
237 //!                 ::core::convert::Infallible,
238 //!             >(data, move |slot| {
239 //!                 {
240 //!                     // Shadow the structure so it cannot be used to return early. If a user
241 //!                     // tries to write `return Ok(__InitOk)`, then they get a type error,
242 //!                     // since that will refer to this struct instead of the one defined
243 //!                     // above.
244 //!                     struct __InitOk;
245 //!                     // This is the expansion of `t,`, which is syntactic sugar for `t: t,`.
246 //!                     {
247 //!                         unsafe { ::core::ptr::write(::core::addr_of_mut!((*slot).t), t) };
248 //!                     }
249 //!                     // Since initialization could fail later (not in this case, since the
250 //!                     // error type is `Infallible`) we will need to drop this field if there
251 //!                     // is an error later. This `DropGuard` will drop the field when it gets
252 //!                     // dropped and has not yet been forgotten.
253 //!                     let __t_guard = unsafe {
254 //!                         ::pinned_init::__internal::DropGuard::new(::core::addr_of_mut!((*slot).t))
255 //!                     };
256 //!                     // Expansion of `x: 0,`:
257 //!                     // Since this can be an arbitrary expression we cannot place it inside
258 //!                     // of the `unsafe` block, so we bind it here.
259 //!                     {
260 //!                         let x = 0;
261 //!                         unsafe { ::core::ptr::write(::core::addr_of_mut!((*slot).x), x) };
262 //!                     }
263 //!                     // We again create a `DropGuard`.
264 //!                     let __x_guard = unsafe {
265 //!                         ::kernel::init::__internal::DropGuard::new(::core::addr_of_mut!((*slot).x))
266 //!                     };
267 //!                     // Since initialization has successfully completed, we can now forget
268 //!                     // the guards. This is not `mem::forget`, since we only have
269 //!                     // `&DropGuard`.
270 //!                     ::core::mem::forget(__x_guard);
271 //!                     ::core::mem::forget(__t_guard);
272 //!                     // Here we use the type checker to ensure that every field has been
273 //!                     // initialized exactly once, since this is `if false` it will never get
274 //!                     // executed, but still type-checked.
275 //!                     // Additionally we abuse `slot` to automatically infer the correct type
276 //!                     // for the struct. This is also another check that every field is
277 //!                     // accessible from this scope.
278 //!                     #[allow(unreachable_code, clippy::diverging_sub_expression)]
279 //!                     let _ = || {
280 //!                         unsafe {
281 //!                             ::core::ptr::write(
282 //!                                 slot,
283 //!                                 Self {
284 //!                                     // We only care about typecheck finding every field
285 //!                                     // here, the expression does not matter, just conjure
286 //!                                     // one using `panic!()`:
287 //!                                     t: ::core::panic!(),
288 //!                                     x: ::core::panic!(),
289 //!                                 },
290 //!                             );
291 //!                         };
292 //!                     };
293 //!                 }
294 //!                 // We leave the scope above and gain access to the previously shadowed
295 //!                 // `__InitOk` that we need to return.
296 //!                 Ok(__InitOk)
297 //!             });
298 //!             // Change the return type from `__InitOk` to `()`.
299 //!             let init = move |
300 //!                 slot,
301 //!             | -> ::core::result::Result<(), ::core::convert::Infallible> {
302 //!                 init(slot).map(|__InitOk| ())
303 //!             };
304 //!             // Construct the initializer.
305 //!             let init = unsafe {
306 //!                 ::kernel::init::pin_init_from_closure::<
307 //!                     _,
308 //!                     ::core::convert::Infallible,
309 //!                 >(init)
310 //!             };
311 //!             init
312 //!         }
313 //!     }
314 //! }
315 //! ```
316 //!
317 //! ## `#[pin_data]` on `Foo`
318 //!
319 //! Since we already took a look at `#[pin_data]` on `Bar`, this section will only explain the
320 //! differences/new things in the expansion of the `Foo` definition:
321 //!
322 //! ```rust,ignore
323 //! #[pin_data(PinnedDrop)]
324 //! struct Foo {
325 //!     a: usize,
326 //!     #[pin]
327 //!     b: Bar<u32>,
328 //! }
329 //! ```
330 //!
331 //! This expands to the following code:
332 //!
333 //! ```rust,ignore
334 //! struct Foo {
335 //!     a: usize,
336 //!     b: Bar<u32>,
337 //! }
338 //! const _: () = {
339 //!     struct __ThePinData {
340 //!         __phantom: ::core::marker::PhantomData<fn(Foo) -> Foo>,
341 //!     }
342 //!     impl ::core::clone::Clone for __ThePinData {
343 //!         fn clone(&self) -> Self {
344 //!             *self
345 //!         }
346 //!     }
347 //!     impl ::core::marker::Copy for __ThePinData {}
348 //!     #[allow(dead_code)]
349 //!     impl __ThePinData {
350 //!         unsafe fn b<E>(
351 //!             self,
352 //!             slot: *mut Bar<u32>,
353 //!             init: impl ::kernel::init::PinInit<Bar<u32>, E>,
354 //!         ) -> ::core::result::Result<(), E> {
355 //!             unsafe { ::kernel::init::PinInit::__pinned_init(init, slot) }
356 //!         }
357 //!         unsafe fn a<E>(
358 //!             self,
359 //!             slot: *mut usize,
360 //!             init: impl ::kernel::init::Init<usize, E>,
361 //!         ) -> ::core::result::Result<(), E> {
362 //!             unsafe { ::kernel::init::Init::__init(init, slot) }
363 //!         }
364 //!     }
365 //!     unsafe impl ::kernel::init::__internal::HasPinData for Foo {
366 //!         type PinData = __ThePinData;
367 //!         unsafe fn __pin_data() -> Self::PinData {
368 //!             __ThePinData {
369 //!                 __phantom: ::core::marker::PhantomData,
370 //!             }
371 //!         }
372 //!     }
373 //!     unsafe impl ::kernel::init::__internal::PinData for __ThePinData {
374 //!         type Datee = Foo;
375 //!     }
376 //!     #[allow(dead_code)]
377 //!     struct __Unpin<'__pin> {
378 //!         __phantom_pin: ::core::marker::PhantomData<fn(&'__pin ()) -> &'__pin ()>,
379 //!         __phantom: ::core::marker::PhantomData<fn(Foo) -> Foo>,
380 //!         b: Bar<u32>,
381 //!     }
382 //!     #[doc(hidden)]
383 //!     impl<'__pin> ::core::marker::Unpin for Foo
384 //!     where
385 //!         __Unpin<'__pin>: ::core::marker::Unpin,
386 //!     {}
387 //!     // Since we specified `PinnedDrop` as the argument to `#[pin_data]`, we expect `Foo` to
388 //!     // implement `PinnedDrop`. Thus we do not need to prevent `Drop` implementations like
389 //!     // before, instead we implement `Drop` here and delegate to `PinnedDrop`.
390 //!     impl ::core::ops::Drop for Foo {
391 //!         fn drop(&mut self) {
392 //!             // Since we are getting dropped, no one else has a reference to `self` and thus we
393 //!             // can assume that we never move.
394 //!             let pinned = unsafe { ::core::pin::Pin::new_unchecked(self) };
395 //!             // Create the unsafe token that proves that we are inside of a destructor, this
396 //!             // type is only allowed to be created in a destructor.
397 //!             let token = unsafe { ::kernel::init::__internal::OnlyCallFromDrop::new() };
398 //!             ::kernel::init::PinnedDrop::drop(pinned, token);
399 //!         }
400 //!     }
401 //! };
402 //! ```
403 //!
404 //! ## `#[pinned_drop]` on `impl PinnedDrop for Foo`
405 //!
406 //! This macro is used to implement the `PinnedDrop` trait, since that trait is `unsafe` and has an
407 //! extra parameter that should not be used at all. The macro hides that parameter.
408 //!
409 //! Here is the `PinnedDrop` impl for `Foo`:
410 //!
411 //! ```rust,ignore
412 //! #[pinned_drop]
413 //! impl PinnedDrop for Foo {
414 //!     fn drop(self: Pin<&mut Self>) {
415 //!         pr_info!("{self:p} is getting dropped.");
416 //!     }
417 //! }
418 //! ```
419 //!
420 //! This expands to the following code:
421 //!
422 //! ```rust,ignore
423 //! // `unsafe`, full path and the token parameter are added, everything else stays the same.
424 //! unsafe impl ::kernel::init::PinnedDrop for Foo {
425 //!     fn drop(self: Pin<&mut Self>, _: ::kernel::init::__internal::OnlyCallFromDrop) {
426 //!         pr_info!("{self:p} is getting dropped.");
427 //!     }
428 //! }
429 //! ```
430 //!
431 //! ## `pin_init!` on `Foo`
432 //!
433 //! Since we already took a look at `pin_init!` on `Bar`, this section will only show the expansion
434 //! of `pin_init!` on `Foo`:
435 //!
436 //! ```rust,ignore
437 //! let a = 42;
438 //! let initializer = pin_init!(Foo {
439 //!     a,
440 //!     b <- Bar::new(36),
441 //! });
442 //! ```
443 //!
444 //! This expands to the following code:
445 //!
446 //! ```rust,ignore
447 //! let a = 42;
448 //! let initializer = {
449 //!     struct __InitOk;
450 //!     let data = unsafe {
451 //!         use ::kernel::init::__internal::HasPinData;
452 //!         Foo::__pin_data()
453 //!     };
454 //!     let init = ::kernel::init::__internal::PinData::make_closure::<
455 //!         _,
456 //!         __InitOk,
457 //!         ::core::convert::Infallible,
458 //!     >(data, move |slot| {
459 //!         {
460 //!             struct __InitOk;
461 //!             {
462 //!                 unsafe { ::core::ptr::write(::core::addr_of_mut!((*slot).a), a) };
463 //!             }
464 //!             let __a_guard = unsafe {
465 //!                 ::kernel::init::__internal::DropGuard::new(::core::addr_of_mut!((*slot).a))
466 //!             };
467 //!             let init = Bar::new(36);
468 //!             unsafe { data.b(::core::addr_of_mut!((*slot).b), b)? };
469 //!             let __b_guard = unsafe {
470 //!                 ::kernel::init::__internal::DropGuard::new(::core::addr_of_mut!((*slot).b))
471 //!             };
472 //!             ::core::mem::forget(__b_guard);
473 //!             ::core::mem::forget(__a_guard);
474 //!             #[allow(unreachable_code, clippy::diverging_sub_expression)]
475 //!             let _ = || {
476 //!                 unsafe {
477 //!                     ::core::ptr::write(
478 //!                         slot,
479 //!                         Foo {
480 //!                             a: ::core::panic!(),
481 //!                             b: ::core::panic!(),
482 //!                         },
483 //!                     );
484 //!                 };
485 //!             };
486 //!         }
487 //!         Ok(__InitOk)
488 //!     });
489 //!     let init = move |
490 //!         slot,
491 //!     | -> ::core::result::Result<(), ::core::convert::Infallible> {
492 //!         init(slot).map(|__InitOk| ())
493 //!     };
494 //!     let init = unsafe {
495 //!         ::kernel::init::pin_init_from_closure::<_, ::core::convert::Infallible>(init)
496 //!     };
497 //!     init
498 //! };
499 //! ```
500 
501 pub use ::macros::paste;
502 
503 /// Creates a `unsafe impl<...> PinnedDrop for $type` block.
504 ///
505 /// See [`PinnedDrop`] for more information.
506 #[doc(hidden)]
507 #[macro_export]
508 macro_rules! __pinned_drop {
509     (
510         @impl_sig($($impl_sig:tt)*),
511         @impl_body(
512             $(#[$($attr:tt)*])*
513             fn drop($($sig:tt)*) {
514                 $($inner:tt)*
515             }
516         ),
517     ) => {
518         // SAFETY: TODO.
519         unsafe $($impl_sig)* {
520             // Inherit all attributes and the type/ident tokens for the signature.
521             $(#[$($attr)*])*
522             fn drop($($sig)*, _: $crate::init::__internal::OnlyCallFromDrop) {
523                 $($inner)*
524             }
525         }
526     }
527 }
528 
529 /// This macro first parses the struct definition such that it separates pinned and not pinned
530 /// fields. Afterwards it declares the struct and implement the `PinData` trait safely.
531 #[doc(hidden)]
532 #[macro_export]
533 macro_rules! __pin_data {
534     // Proc-macro entry point, this is supplied by the proc-macro pre-parsing.
535     (parse_input:
536         @args($($pinned_drop:ident)?),
537         @sig(
538             $(#[$($struct_attr:tt)*])*
539             $vis:vis struct $name:ident
540             $(where $($whr:tt)*)?
541         ),
542         @impl_generics($($impl_generics:tt)*),
543         @ty_generics($($ty_generics:tt)*),
544         @decl_generics($($decl_generics:tt)*),
545         @body({ $($fields:tt)* }),
546     ) => {
547         // We now use token munching to iterate through all of the fields. While doing this we
548         // identify fields marked with `#[pin]`, these fields are the 'pinned fields'. The user
549         // wants these to be structurally pinned. The rest of the fields are the
550         // 'not pinned fields'. Additionally we collect all fields, since we need them in the right
551         // order to declare the struct.
552         //
553         // In this call we also put some explaining comments for the parameters.
554         $crate::__pin_data!(find_pinned_fields:
555             // Attributes on the struct itself, these will just be propagated to be put onto the
556             // struct definition.
557             @struct_attrs($(#[$($struct_attr)*])*),
558             // The visibility of the struct.
559             @vis($vis),
560             // The name of the struct.
561             @name($name),
562             // The 'impl generics', the generics that will need to be specified on the struct inside
563             // of an `impl<$ty_generics>` block.
564             @impl_generics($($impl_generics)*),
565             // The 'ty generics', the generics that will need to be specified on the impl blocks.
566             @ty_generics($($ty_generics)*),
567             // The 'decl generics', the generics that need to be specified on the struct
568             // definition.
569             @decl_generics($($decl_generics)*),
570             // The where clause of any impl block and the declaration.
571             @where($($($whr)*)?),
572             // The remaining fields tokens that need to be processed.
573             // We add a `,` at the end to ensure correct parsing.
574             @fields_munch($($fields)* ,),
575             // The pinned fields.
576             @pinned(),
577             // The not pinned fields.
578             @not_pinned(),
579             // All fields.
580             @fields(),
581             // The accumulator containing all attributes already parsed.
582             @accum(),
583             // Contains `yes` or `` to indicate if `#[pin]` was found on the current field.
584             @is_pinned(),
585             // The proc-macro argument, this should be `PinnedDrop` or ``.
586             @pinned_drop($($pinned_drop)?),
587         );
588     };
589     (find_pinned_fields:
590         @struct_attrs($($struct_attrs:tt)*),
591         @vis($vis:vis),
592         @name($name:ident),
593         @impl_generics($($impl_generics:tt)*),
594         @ty_generics($($ty_generics:tt)*),
595         @decl_generics($($decl_generics:tt)*),
596         @where($($whr:tt)*),
597         // We found a PhantomPinned field, this should generally be pinned!
598         @fields_munch($field:ident : $($($(::)?core::)?marker::)?PhantomPinned, $($rest:tt)*),
599         @pinned($($pinned:tt)*),
600         @not_pinned($($not_pinned:tt)*),
601         @fields($($fields:tt)*),
602         @accum($($accum:tt)*),
603         // This field is not pinned.
604         @is_pinned(),
605         @pinned_drop($($pinned_drop:ident)?),
606     ) => {
607         ::core::compile_error!(concat!(
608             "The field `",
609             stringify!($field),
610             "` of type `PhantomPinned` only has an effect, if it has the `#[pin]` attribute.",
611         ));
612         $crate::__pin_data!(find_pinned_fields:
613             @struct_attrs($($struct_attrs)*),
614             @vis($vis),
615             @name($name),
616             @impl_generics($($impl_generics)*),
617             @ty_generics($($ty_generics)*),
618             @decl_generics($($decl_generics)*),
619             @where($($whr)*),
620             @fields_munch($($rest)*),
621             @pinned($($pinned)* $($accum)* $field: ::core::marker::PhantomPinned,),
622             @not_pinned($($not_pinned)*),
623             @fields($($fields)* $($accum)* $field: ::core::marker::PhantomPinned,),
624             @accum(),
625             @is_pinned(),
626             @pinned_drop($($pinned_drop)?),
627         );
628     };
629     (find_pinned_fields:
630         @struct_attrs($($struct_attrs:tt)*),
631         @vis($vis:vis),
632         @name($name:ident),
633         @impl_generics($($impl_generics:tt)*),
634         @ty_generics($($ty_generics:tt)*),
635         @decl_generics($($decl_generics:tt)*),
636         @where($($whr:tt)*),
637         // We reached the field declaration.
638         @fields_munch($field:ident : $type:ty, $($rest:tt)*),
639         @pinned($($pinned:tt)*),
640         @not_pinned($($not_pinned:tt)*),
641         @fields($($fields:tt)*),
642         @accum($($accum:tt)*),
643         // This field is pinned.
644         @is_pinned(yes),
645         @pinned_drop($($pinned_drop:ident)?),
646     ) => {
647         $crate::__pin_data!(find_pinned_fields:
648             @struct_attrs($($struct_attrs)*),
649             @vis($vis),
650             @name($name),
651             @impl_generics($($impl_generics)*),
652             @ty_generics($($ty_generics)*),
653             @decl_generics($($decl_generics)*),
654             @where($($whr)*),
655             @fields_munch($($rest)*),
656             @pinned($($pinned)* $($accum)* $field: $type,),
657             @not_pinned($($not_pinned)*),
658             @fields($($fields)* $($accum)* $field: $type,),
659             @accum(),
660             @is_pinned(),
661             @pinned_drop($($pinned_drop)?),
662         );
663     };
664     (find_pinned_fields:
665         @struct_attrs($($struct_attrs:tt)*),
666         @vis($vis:vis),
667         @name($name:ident),
668         @impl_generics($($impl_generics:tt)*),
669         @ty_generics($($ty_generics:tt)*),
670         @decl_generics($($decl_generics:tt)*),
671         @where($($whr:tt)*),
672         // We reached the field declaration.
673         @fields_munch($field:ident : $type:ty, $($rest:tt)*),
674         @pinned($($pinned:tt)*),
675         @not_pinned($($not_pinned:tt)*),
676         @fields($($fields:tt)*),
677         @accum($($accum:tt)*),
678         // This field is not pinned.
679         @is_pinned(),
680         @pinned_drop($($pinned_drop:ident)?),
681     ) => {
682         $crate::__pin_data!(find_pinned_fields:
683             @struct_attrs($($struct_attrs)*),
684             @vis($vis),
685             @name($name),
686             @impl_generics($($impl_generics)*),
687             @ty_generics($($ty_generics)*),
688             @decl_generics($($decl_generics)*),
689             @where($($whr)*),
690             @fields_munch($($rest)*),
691             @pinned($($pinned)*),
692             @not_pinned($($not_pinned)* $($accum)* $field: $type,),
693             @fields($($fields)* $($accum)* $field: $type,),
694             @accum(),
695             @is_pinned(),
696             @pinned_drop($($pinned_drop)?),
697         );
698     };
699     (find_pinned_fields:
700         @struct_attrs($($struct_attrs:tt)*),
701         @vis($vis:vis),
702         @name($name:ident),
703         @impl_generics($($impl_generics:tt)*),
704         @ty_generics($($ty_generics:tt)*),
705         @decl_generics($($decl_generics:tt)*),
706         @where($($whr:tt)*),
707         // We found the `#[pin]` attr.
708         @fields_munch(#[pin] $($rest:tt)*),
709         @pinned($($pinned:tt)*),
710         @not_pinned($($not_pinned:tt)*),
711         @fields($($fields:tt)*),
712         @accum($($accum:tt)*),
713         @is_pinned($($is_pinned:ident)?),
714         @pinned_drop($($pinned_drop:ident)?),
715     ) => {
716         $crate::__pin_data!(find_pinned_fields:
717             @struct_attrs($($struct_attrs)*),
718             @vis($vis),
719             @name($name),
720             @impl_generics($($impl_generics)*),
721             @ty_generics($($ty_generics)*),
722             @decl_generics($($decl_generics)*),
723             @where($($whr)*),
724             @fields_munch($($rest)*),
725             // We do not include `#[pin]` in the list of attributes, since it is not actually an
726             // attribute that is defined somewhere.
727             @pinned($($pinned)*),
728             @not_pinned($($not_pinned)*),
729             @fields($($fields)*),
730             @accum($($accum)*),
731             // Set this to `yes`.
732             @is_pinned(yes),
733             @pinned_drop($($pinned_drop)?),
734         );
735     };
736     (find_pinned_fields:
737         @struct_attrs($($struct_attrs:tt)*),
738         @vis($vis:vis),
739         @name($name:ident),
740         @impl_generics($($impl_generics:tt)*),
741         @ty_generics($($ty_generics:tt)*),
742         @decl_generics($($decl_generics:tt)*),
743         @where($($whr:tt)*),
744         // We reached the field declaration with visibility, for simplicity we only munch the
745         // visibility and put it into `$accum`.
746         @fields_munch($fvis:vis $field:ident $($rest:tt)*),
747         @pinned($($pinned:tt)*),
748         @not_pinned($($not_pinned:tt)*),
749         @fields($($fields:tt)*),
750         @accum($($accum:tt)*),
751         @is_pinned($($is_pinned:ident)?),
752         @pinned_drop($($pinned_drop:ident)?),
753     ) => {
754         $crate::__pin_data!(find_pinned_fields:
755             @struct_attrs($($struct_attrs)*),
756             @vis($vis),
757             @name($name),
758             @impl_generics($($impl_generics)*),
759             @ty_generics($($ty_generics)*),
760             @decl_generics($($decl_generics)*),
761             @where($($whr)*),
762             @fields_munch($field $($rest)*),
763             @pinned($($pinned)*),
764             @not_pinned($($not_pinned)*),
765             @fields($($fields)*),
766             @accum($($accum)* $fvis),
767             @is_pinned($($is_pinned)?),
768             @pinned_drop($($pinned_drop)?),
769         );
770     };
771     (find_pinned_fields:
772         @struct_attrs($($struct_attrs:tt)*),
773         @vis($vis:vis),
774         @name($name:ident),
775         @impl_generics($($impl_generics:tt)*),
776         @ty_generics($($ty_generics:tt)*),
777         @decl_generics($($decl_generics:tt)*),
778         @where($($whr:tt)*),
779         // Some other attribute, just put it into `$accum`.
780         @fields_munch(#[$($attr:tt)*] $($rest:tt)*),
781         @pinned($($pinned:tt)*),
782         @not_pinned($($not_pinned:tt)*),
783         @fields($($fields:tt)*),
784         @accum($($accum:tt)*),
785         @is_pinned($($is_pinned:ident)?),
786         @pinned_drop($($pinned_drop:ident)?),
787     ) => {
788         $crate::__pin_data!(find_pinned_fields:
789             @struct_attrs($($struct_attrs)*),
790             @vis($vis),
791             @name($name),
792             @impl_generics($($impl_generics)*),
793             @ty_generics($($ty_generics)*),
794             @decl_generics($($decl_generics)*),
795             @where($($whr)*),
796             @fields_munch($($rest)*),
797             @pinned($($pinned)*),
798             @not_pinned($($not_pinned)*),
799             @fields($($fields)*),
800             @accum($($accum)* #[$($attr)*]),
801             @is_pinned($($is_pinned)?),
802             @pinned_drop($($pinned_drop)?),
803         );
804     };
805     (find_pinned_fields:
806         @struct_attrs($($struct_attrs:tt)*),
807         @vis($vis:vis),
808         @name($name:ident),
809         @impl_generics($($impl_generics:tt)*),
810         @ty_generics($($ty_generics:tt)*),
811         @decl_generics($($decl_generics:tt)*),
812         @where($($whr:tt)*),
813         // We reached the end of the fields, plus an optional additional comma, since we added one
814         // before and the user is also allowed to put a trailing comma.
815         @fields_munch($(,)?),
816         @pinned($($pinned:tt)*),
817         @not_pinned($($not_pinned:tt)*),
818         @fields($($fields:tt)*),
819         @accum(),
820         @is_pinned(),
821         @pinned_drop($($pinned_drop:ident)?),
822     ) => {
823         // Declare the struct with all fields in the correct order.
824         $($struct_attrs)*
825         $vis struct $name <$($decl_generics)*>
826         where $($whr)*
827         {
828             $($fields)*
829         }
830 
831         // We put the rest into this const item, because it then will not be accessible to anything
832         // outside.
833         const _: () = {
834             // We declare this struct which will host all of the projection function for our type.
835             // it will be invariant over all generic parameters which are inherited from the
836             // struct.
837             $vis struct __ThePinData<$($impl_generics)*>
838             where $($whr)*
839             {
840                 __phantom: ::core::marker::PhantomData<
841                     fn($name<$($ty_generics)*>) -> $name<$($ty_generics)*>
842                 >,
843             }
844 
845             impl<$($impl_generics)*> ::core::clone::Clone for __ThePinData<$($ty_generics)*>
846             where $($whr)*
847             {
848                 fn clone(&self) -> Self { *self }
849             }
850 
851             impl<$($impl_generics)*> ::core::marker::Copy for __ThePinData<$($ty_generics)*>
852             where $($whr)*
853             {}
854 
855             // Make all projection functions.
856             $crate::__pin_data!(make_pin_data:
857                 @pin_data(__ThePinData),
858                 @impl_generics($($impl_generics)*),
859                 @ty_generics($($ty_generics)*),
860                 @where($($whr)*),
861                 @pinned($($pinned)*),
862                 @not_pinned($($not_pinned)*),
863             );
864 
865             // SAFETY: We have added the correct projection functions above to `__ThePinData` and
866             // we also use the least restrictive generics possible.
867             unsafe impl<$($impl_generics)*>
868                 $crate::init::__internal::HasPinData for $name<$($ty_generics)*>
869             where $($whr)*
870             {
871                 type PinData = __ThePinData<$($ty_generics)*>;
872 
873                 unsafe fn __pin_data() -> Self::PinData {
874                     __ThePinData { __phantom: ::core::marker::PhantomData }
875                 }
876             }
877 
878             // SAFETY: TODO.
879             unsafe impl<$($impl_generics)*>
880                 $crate::init::__internal::PinData for __ThePinData<$($ty_generics)*>
881             where $($whr)*
882             {
883                 type Datee = $name<$($ty_generics)*>;
884             }
885 
886             // This struct will be used for the unpin analysis. Since only structurally pinned
887             // fields are relevant whether the struct should implement `Unpin`.
888             #[allow(dead_code)]
889             struct __Unpin <'__pin, $($impl_generics)*>
890             where $($whr)*
891             {
892                 __phantom_pin: ::core::marker::PhantomData<fn(&'__pin ()) -> &'__pin ()>,
893                 __phantom: ::core::marker::PhantomData<
894                     fn($name<$($ty_generics)*>) -> $name<$($ty_generics)*>
895                 >,
896                 // Only the pinned fields.
897                 $($pinned)*
898             }
899 
900             #[doc(hidden)]
901             impl<'__pin, $($impl_generics)*> ::core::marker::Unpin for $name<$($ty_generics)*>
902             where
903                 __Unpin<'__pin, $($ty_generics)*>: ::core::marker::Unpin,
904                 $($whr)*
905             {}
906 
907             // We need to disallow normal `Drop` implementation, the exact behavior depends on
908             // whether `PinnedDrop` was specified as the parameter.
909             $crate::__pin_data!(drop_prevention:
910                 @name($name),
911                 @impl_generics($($impl_generics)*),
912                 @ty_generics($($ty_generics)*),
913                 @where($($whr)*),
914                 @pinned_drop($($pinned_drop)?),
915             );
916         };
917     };
918     // When no `PinnedDrop` was specified, then we have to prevent implementing drop.
919     (drop_prevention:
920         @name($name:ident),
921         @impl_generics($($impl_generics:tt)*),
922         @ty_generics($($ty_generics:tt)*),
923         @where($($whr:tt)*),
924         @pinned_drop(),
925     ) => {
926         // We prevent this by creating a trait that will be implemented for all types implementing
927         // `Drop`. Additionally we will implement this trait for the struct leading to a conflict,
928         // if it also implements `Drop`
929         trait MustNotImplDrop {}
930         #[expect(drop_bounds)]
931         impl<T: ::core::ops::Drop> MustNotImplDrop for T {}
932         impl<$($impl_generics)*> MustNotImplDrop for $name<$($ty_generics)*>
933         where $($whr)* {}
934         // We also take care to prevent users from writing a useless `PinnedDrop` implementation.
935         // They might implement `PinnedDrop` correctly for the struct, but forget to give
936         // `PinnedDrop` as the parameter to `#[pin_data]`.
937         #[expect(non_camel_case_types)]
938         trait UselessPinnedDropImpl_you_need_to_specify_PinnedDrop {}
939         impl<T: $crate::init::PinnedDrop>
940             UselessPinnedDropImpl_you_need_to_specify_PinnedDrop for T {}
941         impl<$($impl_generics)*>
942             UselessPinnedDropImpl_you_need_to_specify_PinnedDrop for $name<$($ty_generics)*>
943         where $($whr)* {}
944     };
945     // When `PinnedDrop` was specified we just implement `Drop` and delegate.
946     (drop_prevention:
947         @name($name:ident),
948         @impl_generics($($impl_generics:tt)*),
949         @ty_generics($($ty_generics:tt)*),
950         @where($($whr:tt)*),
951         @pinned_drop(PinnedDrop),
952     ) => {
953         impl<$($impl_generics)*> ::core::ops::Drop for $name<$($ty_generics)*>
954         where $($whr)*
955         {
956             fn drop(&mut self) {
957                 // SAFETY: Since this is a destructor, `self` will not move after this function
958                 // terminates, since it is inaccessible.
959                 let pinned = unsafe { ::core::pin::Pin::new_unchecked(self) };
960                 // SAFETY: Since this is a drop function, we can create this token to call the
961                 // pinned destructor of this type.
962                 let token = unsafe { $crate::init::__internal::OnlyCallFromDrop::new() };
963                 $crate::init::PinnedDrop::drop(pinned, token);
964             }
965         }
966     };
967     // If some other parameter was specified, we emit a readable error.
968     (drop_prevention:
969         @name($name:ident),
970         @impl_generics($($impl_generics:tt)*),
971         @ty_generics($($ty_generics:tt)*),
972         @where($($whr:tt)*),
973         @pinned_drop($($rest:tt)*),
974     ) => {
975         compile_error!(
976             "Wrong parameters to `#[pin_data]`, expected nothing or `PinnedDrop`, got '{}'.",
977             stringify!($($rest)*),
978         );
979     };
980     (make_pin_data:
981         @pin_data($pin_data:ident),
982         @impl_generics($($impl_generics:tt)*),
983         @ty_generics($($ty_generics:tt)*),
984         @where($($whr:tt)*),
985         @pinned($($(#[$($p_attr:tt)*])* $pvis:vis $p_field:ident : $p_type:ty),* $(,)?),
986         @not_pinned($($(#[$($attr:tt)*])* $fvis:vis $field:ident : $type:ty),* $(,)?),
987     ) => {
988         // For every field, we create a projection function according to its projection type. If a
989         // field is structurally pinned, then it must be initialized via `PinInit`, if it is not
990         // structurally pinned, then it can be initialized via `Init`.
991         //
992         // The functions are `unsafe` to prevent accidentally calling them.
993         #[allow(dead_code)]
994         #[expect(clippy::missing_safety_doc)]
995         impl<$($impl_generics)*> $pin_data<$($ty_generics)*>
996         where $($whr)*
997         {
998             $(
999                 $(#[$($p_attr)*])*
1000                 $pvis unsafe fn $p_field<E>(
1001                     self,
1002                     slot: *mut $p_type,
1003                     init: impl $crate::init::PinInit<$p_type, E>,
1004                 ) -> ::core::result::Result<(), E> {
1005                     // SAFETY: TODO.
1006                     unsafe { $crate::init::PinInit::__pinned_init(init, slot) }
1007                 }
1008             )*
1009             $(
1010                 $(#[$($attr)*])*
1011                 $fvis unsafe fn $field<E>(
1012                     self,
1013                     slot: *mut $type,
1014                     init: impl $crate::init::Init<$type, E>,
1015                 ) -> ::core::result::Result<(), E> {
1016                     // SAFETY: TODO.
1017                     unsafe { $crate::init::Init::__init(init, slot) }
1018                 }
1019             )*
1020         }
1021     };
1022 }
1023 
1024 /// The internal init macro. Do not call manually!
1025 ///
1026 /// This is called by the `{try_}{pin_}init!` macros with various inputs.
1027 ///
1028 /// This macro has multiple internal call configurations, these are always the very first ident:
1029 /// - nothing: this is the base case and called by the `{try_}{pin_}init!` macros.
1030 /// - `with_update_parsed`: when the `..Zeroable::zeroed()` syntax has been handled.
1031 /// - `init_slot`: recursively creates the code that initializes all fields in `slot`.
1032 /// - `make_initializer`: recursively create the struct initializer that guarantees that every
1033 ///   field has been initialized exactly once.
1034 #[doc(hidden)]
1035 #[macro_export]
1036 macro_rules! __init_internal {
1037     (
1038         @this($($this:ident)?),
1039         @typ($t:path),
1040         @fields($($fields:tt)*),
1041         @error($err:ty),
1042         // Either `PinData` or `InitData`, `$use_data` should only be present in the `PinData`
1043         // case.
1044         @data($data:ident, $($use_data:ident)?),
1045         // `HasPinData` or `HasInitData`.
1046         @has_data($has_data:ident, $get_data:ident),
1047         // `pin_init_from_closure` or `init_from_closure`.
1048         @construct_closure($construct_closure:ident),
1049         @munch_fields(),
1050     ) => {
1051         $crate::__init_internal!(with_update_parsed:
1052             @this($($this)?),
1053             @typ($t),
1054             @fields($($fields)*),
1055             @error($err),
1056             @data($data, $($use_data)?),
1057             @has_data($has_data, $get_data),
1058             @construct_closure($construct_closure),
1059             @zeroed(), // Nothing means default behavior.
1060         )
1061     };
1062     (
1063         @this($($this:ident)?),
1064         @typ($t:path),
1065         @fields($($fields:tt)*),
1066         @error($err:ty),
1067         // Either `PinData` or `InitData`, `$use_data` should only be present in the `PinData`
1068         // case.
1069         @data($data:ident, $($use_data:ident)?),
1070         // `HasPinData` or `HasInitData`.
1071         @has_data($has_data:ident, $get_data:ident),
1072         // `pin_init_from_closure` or `init_from_closure`.
1073         @construct_closure($construct_closure:ident),
1074         @munch_fields(..Zeroable::zeroed()),
1075     ) => {
1076         $crate::__init_internal!(with_update_parsed:
1077             @this($($this)?),
1078             @typ($t),
1079             @fields($($fields)*),
1080             @error($err),
1081             @data($data, $($use_data)?),
1082             @has_data($has_data, $get_data),
1083             @construct_closure($construct_closure),
1084             @zeroed(()), // `()` means zero all fields not mentioned.
1085         )
1086     };
1087     (
1088         @this($($this:ident)?),
1089         @typ($t:path),
1090         @fields($($fields:tt)*),
1091         @error($err:ty),
1092         // Either `PinData` or `InitData`, `$use_data` should only be present in the `PinData`
1093         // case.
1094         @data($data:ident, $($use_data:ident)?),
1095         // `HasPinData` or `HasInitData`.
1096         @has_data($has_data:ident, $get_data:ident),
1097         // `pin_init_from_closure` or `init_from_closure`.
1098         @construct_closure($construct_closure:ident),
1099         @munch_fields($ignore:tt $($rest:tt)*),
1100     ) => {
1101         $crate::__init_internal!(
1102             @this($($this)?),
1103             @typ($t),
1104             @fields($($fields)*),
1105             @error($err),
1106             @data($data, $($use_data)?),
1107             @has_data($has_data, $get_data),
1108             @construct_closure($construct_closure),
1109             @munch_fields($($rest)*),
1110         )
1111     };
1112     (with_update_parsed:
1113         @this($($this:ident)?),
1114         @typ($t:path),
1115         @fields($($fields:tt)*),
1116         @error($err:ty),
1117         // Either `PinData` or `InitData`, `$use_data` should only be present in the `PinData`
1118         // case.
1119         @data($data:ident, $($use_data:ident)?),
1120         // `HasPinData` or `HasInitData`.
1121         @has_data($has_data:ident, $get_data:ident),
1122         // `pin_init_from_closure` or `init_from_closure`.
1123         @construct_closure($construct_closure:ident),
1124         @zeroed($($init_zeroed:expr)?),
1125     ) => {{
1126         // We do not want to allow arbitrary returns, so we declare this type as the `Ok` return
1127         // type and shadow it later when we insert the arbitrary user code. That way there will be
1128         // no possibility of returning without `unsafe`.
1129         struct __InitOk;
1130         // Get the data about fields from the supplied type.
1131         //
1132         // SAFETY: TODO.
1133         let data = unsafe {
1134             use $crate::init::__internal::$has_data;
1135             // Here we abuse `paste!` to retokenize `$t`. Declarative macros have some internal
1136             // information that is associated to already parsed fragments, so a path fragment
1137             // cannot be used in this position. Doing the retokenization results in valid rust
1138             // code.
1139             $crate::init::macros::paste!($t::$get_data())
1140         };
1141         // Ensure that `data` really is of type `$data` and help with type inference:
1142         let init = $crate::init::__internal::$data::make_closure::<_, __InitOk, $err>(
1143             data,
1144             move |slot| {
1145                 {
1146                     // Shadow the structure so it cannot be used to return early.
1147                     struct __InitOk;
1148                     // If `$init_zeroed` is present we should zero the slot now and not emit an
1149                     // error when fields are missing (since they will be zeroed). We also have to
1150                     // check that the type actually implements `Zeroable`.
1151                     $({
1152                         fn assert_zeroable<T: $crate::init::Zeroable>(_: *mut T) {}
1153                         // Ensure that the struct is indeed `Zeroable`.
1154                         assert_zeroable(slot);
1155                         // SAFETY: The type implements `Zeroable` by the check above.
1156                         unsafe { ::core::ptr::write_bytes(slot, 0, 1) };
1157                         $init_zeroed // This will be `()` if set.
1158                     })?
1159                     // Create the `this` so it can be referenced by the user inside of the
1160                     // expressions creating the individual fields.
1161                     $(let $this = unsafe { ::core::ptr::NonNull::new_unchecked(slot) };)?
1162                     // Initialize every field.
1163                     $crate::__init_internal!(init_slot($($use_data)?):
1164                         @data(data),
1165                         @slot(slot),
1166                         @guards(),
1167                         @munch_fields($($fields)*,),
1168                     );
1169                     // We use unreachable code to ensure that all fields have been mentioned exactly
1170                     // once, this struct initializer will still be type-checked and complain with a
1171                     // very natural error message if a field is forgotten/mentioned more than once.
1172                     #[allow(unreachable_code, clippy::diverging_sub_expression)]
1173                     let _ = || {
1174                         $crate::__init_internal!(make_initializer:
1175                             @slot(slot),
1176                             @type_name($t),
1177                             @munch_fields($($fields)*,),
1178                             @acc(),
1179                         );
1180                     };
1181                 }
1182                 Ok(__InitOk)
1183             }
1184         );
1185         let init = move |slot| -> ::core::result::Result<(), $err> {
1186             init(slot).map(|__InitOk| ())
1187         };
1188         // SAFETY: TODO.
1189         let init = unsafe { $crate::init::$construct_closure::<_, $err>(init) };
1190         init
1191     }};
1192     (init_slot($($use_data:ident)?):
1193         @data($data:ident),
1194         @slot($slot:ident),
1195         @guards($($guards:ident,)*),
1196         @munch_fields($(..Zeroable::zeroed())? $(,)?),
1197     ) => {
1198         // Endpoint of munching, no fields are left. If execution reaches this point, all fields
1199         // have been initialized. Therefore we can now dismiss the guards by forgetting them.
1200         $(::core::mem::forget($guards);)*
1201     };
1202     (init_slot($use_data:ident): // `use_data` is present, so we use the `data` to init fields.
1203         @data($data:ident),
1204         @slot($slot:ident),
1205         @guards($($guards:ident,)*),
1206         // In-place initialization syntax.
1207         @munch_fields($field:ident <- $val:expr, $($rest:tt)*),
1208     ) => {
1209         let init = $val;
1210         // Call the initializer.
1211         //
1212         // SAFETY: `slot` is valid, because we are inside of an initializer closure, we
1213         // return when an error/panic occurs.
1214         // We also use the `data` to require the correct trait (`Init` or `PinInit`) for `$field`.
1215         unsafe { $data.$field(::core::ptr::addr_of_mut!((*$slot).$field), init)? };
1216         // Create the drop guard:
1217         //
1218         // We rely on macro hygiene to make it impossible for users to access this local variable.
1219         // We use `paste!` to create new hygiene for `$field`.
1220         $crate::init::macros::paste! {
1221             // SAFETY: We forget the guard later when initialization has succeeded.
1222             let [< __ $field _guard >] = unsafe {
1223                 $crate::init::__internal::DropGuard::new(::core::ptr::addr_of_mut!((*$slot).$field))
1224             };
1225 
1226             $crate::__init_internal!(init_slot($use_data):
1227                 @data($data),
1228                 @slot($slot),
1229                 @guards([< __ $field _guard >], $($guards,)*),
1230                 @munch_fields($($rest)*),
1231             );
1232         }
1233     };
1234     (init_slot(): // No `use_data`, so we use `Init::__init` directly.
1235         @data($data:ident),
1236         @slot($slot:ident),
1237         @guards($($guards:ident,)*),
1238         // In-place initialization syntax.
1239         @munch_fields($field:ident <- $val:expr, $($rest:tt)*),
1240     ) => {
1241         let init = $val;
1242         // Call the initializer.
1243         //
1244         // SAFETY: `slot` is valid, because we are inside of an initializer closure, we
1245         // return when an error/panic occurs.
1246         unsafe { $crate::init::Init::__init(init, ::core::ptr::addr_of_mut!((*$slot).$field))? };
1247         // Create the drop guard:
1248         //
1249         // We rely on macro hygiene to make it impossible for users to access this local variable.
1250         // We use `paste!` to create new hygiene for `$field`.
1251         $crate::init::macros::paste! {
1252             // SAFETY: We forget the guard later when initialization has succeeded.
1253             let [< __ $field _guard >] = unsafe {
1254                 $crate::init::__internal::DropGuard::new(::core::ptr::addr_of_mut!((*$slot).$field))
1255             };
1256 
1257             $crate::__init_internal!(init_slot():
1258                 @data($data),
1259                 @slot($slot),
1260                 @guards([< __ $field _guard >], $($guards,)*),
1261                 @munch_fields($($rest)*),
1262             );
1263         }
1264     };
1265     (init_slot($($use_data:ident)?):
1266         @data($data:ident),
1267         @slot($slot:ident),
1268         @guards($($guards:ident,)*),
1269         // Init by-value.
1270         @munch_fields($field:ident $(: $val:expr)?, $($rest:tt)*),
1271     ) => {
1272         {
1273             $(let $field = $val;)?
1274             // Initialize the field.
1275             //
1276             // SAFETY: The memory at `slot` is uninitialized.
1277             unsafe { ::core::ptr::write(::core::ptr::addr_of_mut!((*$slot).$field), $field) };
1278         }
1279         // Create the drop guard:
1280         //
1281         // We rely on macro hygiene to make it impossible for users to access this local variable.
1282         // We use `paste!` to create new hygiene for `$field`.
1283         $crate::init::macros::paste! {
1284             // SAFETY: We forget the guard later when initialization has succeeded.
1285             let [< __ $field _guard >] = unsafe {
1286                 $crate::init::__internal::DropGuard::new(::core::ptr::addr_of_mut!((*$slot).$field))
1287             };
1288 
1289             $crate::__init_internal!(init_slot($($use_data)?):
1290                 @data($data),
1291                 @slot($slot),
1292                 @guards([< __ $field _guard >], $($guards,)*),
1293                 @munch_fields($($rest)*),
1294             );
1295         }
1296     };
1297     (make_initializer:
1298         @slot($slot:ident),
1299         @type_name($t:path),
1300         @munch_fields(..Zeroable::zeroed() $(,)?),
1301         @acc($($acc:tt)*),
1302     ) => {
1303         // Endpoint, nothing more to munch, create the initializer. Since the users specified
1304         // `..Zeroable::zeroed()`, the slot will already have been zeroed and all field that have
1305         // not been overwritten are thus zero and initialized. We still check that all fields are
1306         // actually accessible by using the struct update syntax ourselves.
1307         // We are inside of a closure that is never executed and thus we can abuse `slot` to
1308         // get the correct type inference here:
1309         #[allow(unused_assignments)]
1310         unsafe {
1311             let mut zeroed = ::core::mem::zeroed();
1312             // We have to use type inference here to make zeroed have the correct type. This does
1313             // not get executed, so it has no effect.
1314             ::core::ptr::write($slot, zeroed);
1315             zeroed = ::core::mem::zeroed();
1316             // Here we abuse `paste!` to retokenize `$t`. Declarative macros have some internal
1317             // information that is associated to already parsed fragments, so a path fragment
1318             // cannot be used in this position. Doing the retokenization results in valid rust
1319             // code.
1320             $crate::init::macros::paste!(
1321                 ::core::ptr::write($slot, $t {
1322                     $($acc)*
1323                     ..zeroed
1324                 });
1325             );
1326         }
1327     };
1328     (make_initializer:
1329         @slot($slot:ident),
1330         @type_name($t:path),
1331         @munch_fields($(,)?),
1332         @acc($($acc:tt)*),
1333     ) => {
1334         // Endpoint, nothing more to munch, create the initializer.
1335         // Since we are in the closure that is never called, this will never get executed.
1336         // We abuse `slot` to get the correct type inference here:
1337         //
1338         // SAFETY: TODO.
1339         unsafe {
1340             // Here we abuse `paste!` to retokenize `$t`. Declarative macros have some internal
1341             // information that is associated to already parsed fragments, so a path fragment
1342             // cannot be used in this position. Doing the retokenization results in valid rust
1343             // code.
1344             $crate::init::macros::paste!(
1345                 ::core::ptr::write($slot, $t {
1346                     $($acc)*
1347                 });
1348             );
1349         }
1350     };
1351     (make_initializer:
1352         @slot($slot:ident),
1353         @type_name($t:path),
1354         @munch_fields($field:ident <- $val:expr, $($rest:tt)*),
1355         @acc($($acc:tt)*),
1356     ) => {
1357         $crate::__init_internal!(make_initializer:
1358             @slot($slot),
1359             @type_name($t),
1360             @munch_fields($($rest)*),
1361             @acc($($acc)* $field: ::core::panic!(),),
1362         );
1363     };
1364     (make_initializer:
1365         @slot($slot:ident),
1366         @type_name($t:path),
1367         @munch_fields($field:ident $(: $val:expr)?, $($rest:tt)*),
1368         @acc($($acc:tt)*),
1369     ) => {
1370         $crate::__init_internal!(make_initializer:
1371             @slot($slot),
1372             @type_name($t),
1373             @munch_fields($($rest)*),
1374             @acc($($acc)* $field: ::core::panic!(),),
1375         );
1376     };
1377 }
1378 
1379 #[doc(hidden)]
1380 #[macro_export]
1381 macro_rules! __derive_zeroable {
1382     (parse_input:
1383         @sig(
1384             $(#[$($struct_attr:tt)*])*
1385             $vis:vis struct $name:ident
1386             $(where $($whr:tt)*)?
1387         ),
1388         @impl_generics($($impl_generics:tt)*),
1389         @ty_generics($($ty_generics:tt)*),
1390         @body({
1391             $(
1392                 $(#[$($field_attr:tt)*])*
1393                 $field:ident : $field_ty:ty
1394             ),* $(,)?
1395         }),
1396     ) => {
1397         // SAFETY: Every field type implements `Zeroable` and padding bytes may be zero.
1398         #[automatically_derived]
1399         unsafe impl<$($impl_generics)*> $crate::init::Zeroable for $name<$($ty_generics)*>
1400         where
1401             $($($whr)*)?
1402         {}
1403         const _: () = {
1404             fn assert_zeroable<T: ?::core::marker::Sized + $crate::init::Zeroable>() {}
1405             fn ensure_zeroable<$($impl_generics)*>()
1406                 where $($($whr)*)?
1407             {
1408                 $(assert_zeroable::<$field_ty>();)*
1409             }
1410         };
1411     };
1412 }
1413