Skip to main content

talus_sui_move_derive/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use proc_macro::TokenStream;
4
5mod abilities;
6mod args;
7mod expand;
8mod util;
9
10/// Marker attribute for Move module namespaces.
11///
12/// This attribute currently leaves the module unchanged. It makes declarations easier to read and
13/// leaves room for future tooling.
14///
15/// # Example
16/// ```rust,no_run
17/// use talus_sui_move_derive::{move_module, move_struct};
18///
19/// #[move_module(address = "0x1", name = "vault")]
20/// mod vault {
21///     #[talus_sui_move_derive::move_struct(address = "0x1", module = "vault", abilities = "copy, store")]
22///     pub struct Counter {
23///         pub value: u64,
24///     }
25/// }
26///
27/// fn main() {}
28/// ```
29#[proc_macro_attribute]
30pub fn move_module(_args: TokenStream, input: TokenStream) -> TokenStream {
31    input
32}
33
34/// Define a Rust struct that represents a Move struct and derive `talus-sui-move` traits.
35///
36/// The attribute arguments define the Move address/module/name plus ability surface, and allow
37/// marking type parameters as phantom.
38///
39/// The macro generates:
40/// - `impl talus_sui_move::MoveType` and `impl talus_sui_move::MoveStruct`
41/// - Ability marker impls (`HasKey`, `HasStore`, `HasCopy`, `HasDrop`)
42/// - `serde` derives (via `talus_sui_move::__private`, so downstream crates don't need direct `serde`)
43/// - Optional injected `PhantomData` fields (see `phantoms = "..."`)
44///
45/// # Supported input
46/// - Structs with named fields only (`struct X { ... }`)
47///
48/// # Arguments
49/// - `address = "0x..."` (required): Move address
50/// - `address_fn = "path::to::fn"` (optional): Rust function returning the Move address to use
51///   when building `StructTag`s; `address` remains the default/documented address
52/// - `module = "..."` (required): Move module name
53/// - `name = "..."` (optional): override Move struct name (defaults to Rust name)
54/// - `abilities = "key, store, copy, drop"` (optional): Move abilities separated by commas
55/// - `phantoms = "T, U"` (optional): phantom type parameters separated by commas
56/// - `type_abilities = "T: store, copy; U: drop"` (optional): ability expectations for type params
57/// - `uid_type = "path::to::UID"` (optional): override which package type counts as `UID`
58///   for `key` enforcement
59///
60/// # Example
61/// ```rust,no_run
62/// use std::marker::PhantomData;
63/// use talus_sui_move::prelude::Address;
64/// use talus_sui_move_derive::move_struct;
65///
66/// /// Local package declaration for `0x2::object::ID`.
67/// ///
68/// /// Framework types are ordinary Move declarations from the type kernel perspective. In
69/// /// production this shape should come from generated package bindings rather than from
70/// /// `talus-sui-move` itself.
71/// #[move_struct(address = "0x2", module = "object", abilities = "copy, drop, store")]
72/// pub struct ID {
73///     pub bytes: Address,
74/// }
75///
76/// /// Local package declaration for `0x2::object::UID`.
77/// ///
78/// /// A `key` object is recognized by an `id` field whose type is a `UID` shape defined by a package.
79/// #[move_struct(address = "0x2", module = "object", abilities = "store")]
80/// pub struct UID {
81///     pub id: ID,
82/// }
83///
84/// #[move_struct(
85///     address = "0x1",
86///     module = "vault",
87///     abilities = "key, store",
88///     phantoms = "T",
89///     type_abilities = "T: store"
90/// )]
91/// pub struct Vault<T> {
92///     pub id: UID,
93///     pub balance: Vec<T>,
94/// }
95///
96/// let _value = Vault::<u64> {
97///     id: UID {
98///         id: ID {
99///             bytes: Address::new([0u8; 32]),
100///         },
101///     },
102///     balance: vec![1, 2, 3],
103///     phantom_t: PhantomData,
104/// };
105/// ```
106#[proc_macro_attribute]
107pub fn move_struct(attr: TokenStream, item: TokenStream) -> TokenStream {
108    let args = syn::parse_macro_input!(attr as args::MoveStructArgs);
109    let input = syn::parse_macro_input!(item as syn::DeriveInput);
110
111    match expand::expand_move_struct(args, input) {
112        Ok(tokens) => tokens.into(),
113        Err(err) => err.to_compile_error().into(),
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use super::args::MoveStructArgs;
120    use std::collections::BTreeMap;
121
122    #[test]
123    fn parse_args() {
124        let args: MoveStructArgs = syn::parse_quote!(
125            address = "0x1",
126            address_fn = "crate::package",
127            module = "vault",
128            abilities = "key, store",
129            phantoms = "T",
130            type_abilities = "T: store, copy"
131        );
132        assert_eq!(args.address.as_deref(), Some("0x1"));
133        assert_eq!(
134            args.address_fn
135                .as_ref()
136                .map(|path| quote::ToTokens::to_token_stream(path).to_string()),
137            Some("crate :: package".to_string())
138        );
139        assert_eq!(args.module.as_deref(), Some("vault"));
140        assert_eq!(args.name, None);
141        assert_eq!(args.abilities, vec!["key".to_string(), "store".to_string()]);
142        assert_eq!(args.phantoms, vec!["T".to_string()]);
143
144        let mut expected = BTreeMap::new();
145        expected.insert(
146            "T".to_string(),
147            vec!["store".to_string(), "copy".to_string()],
148        );
149        assert_eq!(args.type_abilities, expected);
150    }
151}