lib.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. extern crate proc_macro;
  2. use anchor_syn::Overrides;
  3. use quote::{quote, ToTokens};
  4. use syn::{
  5. parenthesized,
  6. parse::{Parse, ParseStream},
  7. parse_macro_input,
  8. token::{Comma, Paren},
  9. Ident, LitStr,
  10. };
  11. mod id;
  12. /// An attribute for a data structure representing a Solana account.
  13. ///
  14. /// `#[account]` generates trait implementations for the following traits:
  15. ///
  16. /// - [`AccountSerialize`](./trait.AccountSerialize.html)
  17. /// - [`AccountDeserialize`](./trait.AccountDeserialize.html)
  18. /// - [`AnchorSerialize`](./trait.AnchorSerialize.html)
  19. /// - [`AnchorDeserialize`](./trait.AnchorDeserialize.html)
  20. /// - [`Clone`](https://doc.rust-lang.org/std/clone/trait.Clone.html)
  21. /// - [`Discriminator`](./trait.Discriminator.html)
  22. /// - [`Owner`](./trait.Owner.html)
  23. ///
  24. /// When implementing account serialization traits the first 8 bytes are
  25. /// reserved for a unique account discriminator, self described by the first 8
  26. /// bytes of the SHA256 of the account's Rust ident.
  27. ///
  28. /// As a result, any calls to `AccountDeserialize`'s `try_deserialize` will
  29. /// check this discriminator. If it doesn't match, an invalid account was given,
  30. /// and the account deserialization will exit with an error.
  31. ///
  32. /// # Args
  33. ///
  34. /// - `discriminator`: Override the default 8-byte discriminator
  35. ///
  36. /// **Usage:** `discriminator = <CONST_EXPR>`
  37. ///
  38. /// All constant expressions are supported.
  39. ///
  40. /// **Examples:**
  41. ///
  42. /// - `discriminator = 0` (shortcut for `[0]`)
  43. /// - `discriminator = [1, 2, 3, 4]`
  44. /// - `discriminator = b"hi"`
  45. /// - `discriminator = MY_DISC`
  46. /// - `discriminator = get_disc(...)`
  47. ///
  48. /// # Zero Copy Deserialization
  49. ///
  50. /// **WARNING**: Zero copy deserialization is an experimental feature. It's
  51. /// recommended to use it only when necessary, i.e., when you have extremely
  52. /// large accounts that cannot be Borsh deserialized without hitting stack or
  53. /// heap limits.
  54. ///
  55. /// ## Usage
  56. ///
  57. /// To enable zero-copy-deserialization, one can pass in the `zero_copy`
  58. /// argument to the macro as follows:
  59. ///
  60. /// ```ignore
  61. /// #[account(zero_copy)]
  62. /// ```
  63. ///
  64. /// This can be used to conveniently implement
  65. /// [`ZeroCopy`](./trait.ZeroCopy.html) so that the account can be used
  66. /// with [`AccountLoader`](./accounts/account_loader/struct.AccountLoader.html).
  67. ///
  68. /// Other than being more efficient, the most salient benefit this provides is
  69. /// the ability to define account types larger than the max stack or heap size.
  70. /// When using borsh, the account has to be copied and deserialized into a new
  71. /// data structure and thus is constrained by stack and heap limits imposed by
  72. /// the BPF VM. With zero copy deserialization, all bytes from the account's
  73. /// backing `RefCell<&mut [u8]>` are simply re-interpreted as a reference to
  74. /// the data structure. No allocations or copies necessary. Hence the ability
  75. /// to get around stack and heap limitations.
  76. ///
  77. /// To facilitate this, all fields in an account must be constrained to be
  78. /// "plain old data", i.e., they must implement
  79. /// [`Pod`](https://docs.rs/bytemuck/latest/bytemuck/trait.Pod.html). Please review the
  80. /// [`safety`](https://docs.rs/bytemuck/latest/bytemuck/trait.Pod.html#safety)
  81. /// section before using.
  82. ///
  83. /// Using `zero_copy` requires adding the following to your `cargo.toml` file:
  84. /// `bytemuck = { version = "1.4.0", features = ["derive", "min_const_generics"]}`
  85. #[proc_macro_attribute]
  86. pub fn account(
  87. args: proc_macro::TokenStream,
  88. input: proc_macro::TokenStream,
  89. ) -> proc_macro::TokenStream {
  90. let args = parse_macro_input!(args as AccountArgs);
  91. let namespace = args.namespace.unwrap_or_default();
  92. let is_zero_copy = args.zero_copy.is_some();
  93. let unsafe_bytemuck = args.zero_copy.unwrap_or_default();
  94. let account_strct = parse_macro_input!(input as syn::ItemStruct);
  95. let account_name = &account_strct.ident;
  96. let account_name_str = account_name.to_string();
  97. let (impl_gen, type_gen, where_clause) = account_strct.generics.split_for_impl();
  98. let discriminator = args
  99. .overrides
  100. .and_then(|ov| ov.discriminator)
  101. .unwrap_or_else(|| {
  102. // Namespace the discriminator to prevent collisions.
  103. let discriminator_preimage = if namespace.is_empty() {
  104. format!("account:{account_name}")
  105. } else {
  106. format!("{namespace}:{account_name}")
  107. };
  108. let mut discriminator = [0u8; 8];
  109. discriminator.copy_from_slice(
  110. &anchor_syn::hash::hash(discriminator_preimage.as_bytes()).to_bytes()[..8],
  111. );
  112. let discriminator: proc_macro2::TokenStream =
  113. format!("{discriminator:?}").parse().unwrap();
  114. quote! { &#discriminator }
  115. });
  116. let disc = if account_strct.generics.lt_token.is_some() {
  117. quote! { #account_name::#type_gen::DISCRIMINATOR }
  118. } else {
  119. quote! { #account_name::DISCRIMINATOR }
  120. };
  121. let owner_impl = {
  122. if namespace.is_empty() {
  123. quote! {
  124. #[automatically_derived]
  125. impl #impl_gen anchor_lang::Owner for #account_name #type_gen #where_clause {
  126. fn owner() -> Pubkey {
  127. crate::ID
  128. }
  129. }
  130. }
  131. } else {
  132. quote! {}
  133. }
  134. };
  135. let unsafe_bytemuck_impl = {
  136. if unsafe_bytemuck {
  137. quote! {
  138. #[automatically_derived]
  139. unsafe impl #impl_gen anchor_lang::__private::bytemuck::Pod for #account_name #type_gen #where_clause {}
  140. #[automatically_derived]
  141. unsafe impl #impl_gen anchor_lang::__private::bytemuck::Zeroable for #account_name #type_gen #where_clause {}
  142. }
  143. } else {
  144. quote! {}
  145. }
  146. };
  147. let bytemuck_derives = {
  148. if !unsafe_bytemuck {
  149. quote! {
  150. #[zero_copy]
  151. }
  152. } else {
  153. quote! {
  154. #[zero_copy(unsafe)]
  155. }
  156. }
  157. };
  158. proc_macro::TokenStream::from({
  159. if is_zero_copy {
  160. quote! {
  161. #bytemuck_derives
  162. #account_strct
  163. #unsafe_bytemuck_impl
  164. #[automatically_derived]
  165. impl #impl_gen anchor_lang::ZeroCopy for #account_name #type_gen #where_clause {}
  166. #[automatically_derived]
  167. impl #impl_gen anchor_lang::Discriminator for #account_name #type_gen #where_clause {
  168. const DISCRIMINATOR: &'static [u8] = #discriminator;
  169. }
  170. // This trait is useful for clients deserializing accounts.
  171. // It's expected on-chain programs deserialize via zero-copy.
  172. #[automatically_derived]
  173. impl #impl_gen anchor_lang::AccountDeserialize for #account_name #type_gen #where_clause {
  174. fn try_deserialize(buf: &mut &[u8]) -> anchor_lang::Result<Self> {
  175. if buf.len() < #disc.len() {
  176. return Err(anchor_lang::error::ErrorCode::AccountDiscriminatorNotFound.into());
  177. }
  178. let given_disc = &buf[..#disc.len()];
  179. if #disc != given_disc {
  180. return Err(anchor_lang::error!(anchor_lang::error::ErrorCode::AccountDiscriminatorMismatch).with_account_name(#account_name_str));
  181. }
  182. Self::try_deserialize_unchecked(buf)
  183. }
  184. fn try_deserialize_unchecked(buf: &mut &[u8]) -> anchor_lang::Result<Self> {
  185. let data: &[u8] = &buf[#disc.len()..];
  186. // Re-interpret raw bytes into the POD data structure.
  187. let account = anchor_lang::__private::bytemuck::from_bytes(data);
  188. // Copy out the bytes into a new, owned data structure.
  189. Ok(*account)
  190. }
  191. }
  192. #owner_impl
  193. }
  194. } else {
  195. quote! {
  196. #[derive(AnchorSerialize, AnchorDeserialize, Clone)]
  197. #account_strct
  198. #[automatically_derived]
  199. impl #impl_gen anchor_lang::AccountSerialize for #account_name #type_gen #where_clause {
  200. fn try_serialize<W: std::io::Write>(&self, writer: &mut W) -> anchor_lang::Result<()> {
  201. if writer.write_all(#disc).is_err() {
  202. return Err(anchor_lang::error::ErrorCode::AccountDidNotSerialize.into());
  203. }
  204. if AnchorSerialize::serialize(self, writer).is_err() {
  205. return Err(anchor_lang::error::ErrorCode::AccountDidNotSerialize.into());
  206. }
  207. Ok(())
  208. }
  209. }
  210. #[automatically_derived]
  211. impl #impl_gen anchor_lang::AccountDeserialize for #account_name #type_gen #where_clause {
  212. fn try_deserialize(buf: &mut &[u8]) -> anchor_lang::Result<Self> {
  213. if buf.len() < #disc.len() {
  214. return Err(anchor_lang::error::ErrorCode::AccountDiscriminatorNotFound.into());
  215. }
  216. let given_disc = &buf[..#disc.len()];
  217. if #disc != given_disc {
  218. return Err(anchor_lang::error!(anchor_lang::error::ErrorCode::AccountDiscriminatorMismatch).with_account_name(#account_name_str));
  219. }
  220. Self::try_deserialize_unchecked(buf)
  221. }
  222. fn try_deserialize_unchecked(buf: &mut &[u8]) -> anchor_lang::Result<Self> {
  223. let mut data: &[u8] = &buf[#disc.len()..];
  224. AnchorDeserialize::deserialize(&mut data)
  225. .map_err(|_| anchor_lang::error::ErrorCode::AccountDidNotDeserialize.into())
  226. }
  227. }
  228. #[automatically_derived]
  229. impl #impl_gen anchor_lang::Discriminator for #account_name #type_gen #where_clause {
  230. const DISCRIMINATOR: &'static [u8] = #discriminator;
  231. }
  232. #owner_impl
  233. }
  234. }
  235. })
  236. }
  237. #[derive(Debug, Default)]
  238. struct AccountArgs {
  239. /// `bool` is for deciding whether to use `unsafe` e.g. `Some(true)` for `zero_copy(unsafe)`
  240. zero_copy: Option<bool>,
  241. /// Account namespace override, `account` if not specified
  242. namespace: Option<String>,
  243. /// Named overrides
  244. overrides: Option<Overrides>,
  245. }
  246. impl Parse for AccountArgs {
  247. fn parse(input: ParseStream) -> syn::Result<Self> {
  248. let mut parsed = Self::default();
  249. let args = input.parse_terminated::<_, Comma>(AccountArg::parse)?;
  250. for arg in args {
  251. match arg {
  252. AccountArg::ZeroCopy { is_unsafe } => {
  253. parsed.zero_copy.replace(is_unsafe);
  254. }
  255. AccountArg::Namespace(ns) => {
  256. parsed.namespace.replace(ns);
  257. }
  258. AccountArg::Overrides(ov) => {
  259. parsed.overrides.replace(ov);
  260. }
  261. }
  262. }
  263. Ok(parsed)
  264. }
  265. }
  266. enum AccountArg {
  267. ZeroCopy { is_unsafe: bool },
  268. Namespace(String),
  269. Overrides(Overrides),
  270. }
  271. impl Parse for AccountArg {
  272. fn parse(input: ParseStream) -> syn::Result<Self> {
  273. // Namespace
  274. if let Ok(ns) = input.parse::<LitStr>() {
  275. return Ok(Self::Namespace(
  276. ns.to_token_stream().to_string().replace('\"', ""),
  277. ));
  278. }
  279. // Zero copy
  280. if input.fork().parse::<Ident>()? == "zero_copy" {
  281. input.parse::<Ident>()?;
  282. let is_unsafe = if input.peek(Paren) {
  283. let content;
  284. parenthesized!(content in input);
  285. let content = content.parse::<proc_macro2::TokenStream>()?;
  286. if content.to_string().as_str().trim() != "unsafe" {
  287. return Err(syn::Error::new(
  288. syn::spanned::Spanned::span(&content),
  289. "Expected `unsafe`",
  290. ));
  291. }
  292. true
  293. } else {
  294. false
  295. };
  296. return Ok(Self::ZeroCopy { is_unsafe });
  297. };
  298. // Overrides
  299. input.parse::<Overrides>().map(Self::Overrides)
  300. }
  301. }
  302. #[proc_macro_derive(ZeroCopyAccessor, attributes(accessor))]
  303. pub fn derive_zero_copy_accessor(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
  304. let account_strct = parse_macro_input!(item as syn::ItemStruct);
  305. let account_name = &account_strct.ident;
  306. let (impl_gen, ty_gen, where_clause) = account_strct.generics.split_for_impl();
  307. let fields = match &account_strct.fields {
  308. syn::Fields::Named(n) => n,
  309. _ => panic!("Fields must be named"),
  310. };
  311. let methods: Vec<proc_macro2::TokenStream> = fields
  312. .named
  313. .iter()
  314. .filter_map(|field: &syn::Field| {
  315. field
  316. .attrs
  317. .iter()
  318. .find(|attr| anchor_syn::parser::tts_to_string(&attr.path) == "accessor")
  319. .map(|attr| {
  320. let mut tts = attr.tokens.clone().into_iter();
  321. let g_stream = match tts.next().expect("Must have a token group") {
  322. proc_macro2::TokenTree::Group(g) => g.stream(),
  323. _ => panic!("Invalid syntax"),
  324. };
  325. let accessor_ty = match g_stream.into_iter().next() {
  326. Some(token) => token,
  327. _ => panic!("Missing accessor type"),
  328. };
  329. let field_name = field.ident.as_ref().unwrap();
  330. let get_field: proc_macro2::TokenStream =
  331. format!("get_{field_name}").parse().unwrap();
  332. let set_field: proc_macro2::TokenStream =
  333. format!("set_{field_name}").parse().unwrap();
  334. quote! {
  335. pub fn #get_field(&self) -> #accessor_ty {
  336. anchor_lang::__private::ZeroCopyAccessor::get(&self.#field_name)
  337. }
  338. pub fn #set_field(&mut self, input: &#accessor_ty) {
  339. self.#field_name = anchor_lang::__private::ZeroCopyAccessor::set(input);
  340. }
  341. }
  342. })
  343. })
  344. .collect();
  345. proc_macro::TokenStream::from(quote! {
  346. #[automatically_derived]
  347. impl #impl_gen #account_name #ty_gen #where_clause {
  348. #(#methods)*
  349. }
  350. })
  351. }
  352. /// A data structure that can be used as an internal field for a zero copy
  353. /// deserialized account, i.e., a struct marked with `#[account(zero_copy)]`.
  354. ///
  355. /// `#[zero_copy]` is just a convenient alias for
  356. ///
  357. /// ```ignore
  358. /// #[derive(Copy, Clone)]
  359. /// #[derive(bytemuck::Zeroable)]
  360. /// #[derive(bytemuck::Pod)]
  361. /// #[repr(C)]
  362. /// struct MyStruct {...}
  363. /// ```
  364. #[proc_macro_attribute]
  365. pub fn zero_copy(
  366. args: proc_macro::TokenStream,
  367. item: proc_macro::TokenStream,
  368. ) -> proc_macro::TokenStream {
  369. let mut is_unsafe = false;
  370. for arg in args.into_iter() {
  371. match arg {
  372. proc_macro::TokenTree::Ident(ident) => {
  373. if ident.to_string() == "unsafe" {
  374. // `#[zero_copy(unsafe)]` maintains the old behaviour
  375. //
  376. // ```ignore
  377. // #[derive(Copy, Clone)]
  378. // #[repr(packed)]
  379. // struct MyStruct {...}
  380. // ```
  381. is_unsafe = true;
  382. } else {
  383. // TODO: how to return a compile error with a span (can't return prase error because expected type TokenStream)
  384. panic!("expected single ident `unsafe`");
  385. }
  386. }
  387. _ => {
  388. panic!("expected single ident `unsafe`");
  389. }
  390. }
  391. }
  392. let account_strct = parse_macro_input!(item as syn::ItemStruct);
  393. // Takes the first repr. It's assumed that more than one are not on the
  394. // struct.
  395. let attr = account_strct
  396. .attrs
  397. .iter()
  398. .find(|attr| anchor_syn::parser::tts_to_string(&attr.path) == "repr");
  399. let repr = match attr {
  400. // Users might want to manually specify repr modifiers e.g. repr(C, packed)
  401. Some(_attr) => quote! {},
  402. None => {
  403. if is_unsafe {
  404. quote! {#[repr(packed)]}
  405. } else {
  406. quote! {#[repr(C)]}
  407. }
  408. }
  409. };
  410. let mut has_pod_attr = false;
  411. let mut has_zeroable_attr = false;
  412. for attr in account_strct.attrs.iter() {
  413. let token_string = attr.tokens.to_string();
  414. if token_string.contains("bytemuck :: Pod") {
  415. has_pod_attr = true;
  416. }
  417. if token_string.contains("bytemuck :: Zeroable") {
  418. has_zeroable_attr = true;
  419. }
  420. }
  421. // Once the Pod derive macro is expanded the compiler has to use the local crate's
  422. // bytemuck `::bytemuck::Pod` anyway, so we're no longer using the privately
  423. // exported anchor bytemuck `__private::bytemuck`, so that there won't be any
  424. // possible disparity between the anchor version and the local crate's version.
  425. let pod = if has_pod_attr || is_unsafe {
  426. quote! {}
  427. } else {
  428. quote! {#[derive(::bytemuck::Pod)]}
  429. };
  430. let zeroable = if has_zeroable_attr || is_unsafe {
  431. quote! {}
  432. } else {
  433. quote! {#[derive(::bytemuck::Zeroable)]}
  434. };
  435. let ret = quote! {
  436. #[derive(anchor_lang::__private::ZeroCopyAccessor, Copy, Clone)]
  437. #repr
  438. #pod
  439. #zeroable
  440. #account_strct
  441. };
  442. #[cfg(feature = "idl-build")]
  443. {
  444. let derive_unsafe = if is_unsafe {
  445. // Not a real proc-macro but exists in order to pass the serialization info
  446. quote! { #[derive(bytemuck::Unsafe)] }
  447. } else {
  448. quote! {}
  449. };
  450. let zc_struct = syn::parse2(quote! {
  451. #derive_unsafe
  452. #ret
  453. })
  454. .unwrap();
  455. let idl_build_impl = anchor_syn::idl::impl_idl_build_struct(&zc_struct);
  456. return proc_macro::TokenStream::from(quote! {
  457. #ret
  458. #idl_build_impl
  459. });
  460. }
  461. #[allow(unreachable_code)]
  462. proc_macro::TokenStream::from(ret)
  463. }
  464. /// Convenience macro to define a static public key.
  465. ///
  466. /// Input: a single literal base58 string representation of a Pubkey.
  467. #[proc_macro]
  468. pub fn pubkey(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
  469. let pk = parse_macro_input!(input as id::Pubkey);
  470. proc_macro::TokenStream::from(quote! {#pk})
  471. }
  472. /// Defines the program's ID. This should be used at the root of all Anchor
  473. /// based programs.
  474. #[proc_macro]
  475. pub fn declare_id(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
  476. #[cfg(feature = "idl-build")]
  477. let address = input.clone().to_string();
  478. let id = parse_macro_input!(input as id::Id);
  479. let ret = quote! { #id };
  480. #[cfg(feature = "idl-build")]
  481. {
  482. let idl_print = anchor_syn::idl::gen_idl_print_fn_address(address);
  483. return proc_macro::TokenStream::from(quote! {
  484. #ret
  485. #idl_print
  486. });
  487. }
  488. #[allow(unreachable_code)]
  489. proc_macro::TokenStream::from(ret)
  490. }