macros.rs 56 KB

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