lib.rs 19 KB

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