Skip to main content

specta_macros/
lib.rs

1//! Easily export your Rust types to other languages
2//!
3//! This crate contains the macro which are reexported by the `specta` crate.
4//! You shouldn't need to use this crate directly.
5//! Checkout [Specta](https://docs.rs/specta).
6#![doc(
7    html_logo_url = "https://github.com/specta-rs/specta/raw/main/.github/logo-128.png",
8    html_favicon_url = "https://github.com/specta-rs/specta/raw/main/.github/logo-128.png"
9)]
10
11#[cfg(feature = "DO_NOT_USE_function")]
12mod specta;
13mod r#type;
14mod utils;
15
16use quote::quote;
17use syn::{Error, LitStr, Type, parse_macro_input};
18
19/// Implements `specta::Type` for a given struct or enum.
20///
21/// # Attributes
22///
23/// `Type` supports `#[specta(...)]` attributes on containers, variants, and fields.
24/// It also understands selected Rust and Serde attributes.
25///
26/// ## `#[specta(...)]` container attributes
27///
28/// These can be used on the struct or enum deriving `Type`.
29///
30/// - `#[specta(type = T)]` overrides the generated type definition with `T`.
31///   `T` may be a path or Rust type, such as `String`, `Vec<T>`, or `(String, i32)`.
32/// - `#[specta(crate = path::to::specta)]` uses a custom path to the `specta` crate.
33///   The target must re-export the `specta` crate wholesale (for example with
34///   `pub use specta;`): the generated code resolves both `Type` and the internal
35///   marker keys through that path, so a partial re-export will not compile.
36/// - `#[specta(inline)]` or `#[specta(inline = true)]` inlines this type where it is referenced.
37///   Use `#[specta(inline = false)]` to disable it.
38/// - `#[specta(remote = path::ToType)]` implements `Type` for a remote type instead of the
39///   local derive input name.
40/// - `#[specta(collect)]` or `#[specta(collect = true)]` enables collection for this type when
41///   the `collect` feature is used. Use `#[specta(collect = false)]` to prevent collection.
42/// - `#[specta(skip_attr = "attr_name")]` ignores attributes named `attr_name` while parsing and
43///   while collecting runtime attributes. This may be repeated.
44/// - `#[specta(transparent)]` or `#[specta(transparent = true)]` treats a struct as its single
45///   non-skipped field. Use `#[specta(transparent = false)]` to disable it.
46/// - `#[specta(bound = "T: Type")]` replaces the automatically inferred `Type` bounds.
47///   Use `#[specta(bound = "")]` to emit no inferred bounds.
48///
49/// `#[specta(type = ...)]` cannot be combined with `#[specta(transparent)]`.
50/// `#[specta(transparent)]` is only valid on structs with exactly one non-skipped field.
51///
52/// ## `#[specta(...)]` variant attributes
53///
54/// These can be used on enum variants.
55///
56/// - `#[specta(type = T)]` or `#[specta(r#type = T)]` overrides the generated variant payload
57///   type with `T`.
58/// - `#[specta(skip)]` or `#[specta(skip = true)]` marks the variant as skipped.
59///   Use `#[specta(skip = false)]` to disable it.
60/// - `#[specta(inline)]` or `#[specta(inline = true)]` inlines the first unnamed field of the
61///   variant. Use `#[specta(inline = false)]` to disable it.
62///
63/// ## `#[specta(...)]` field attributes
64///
65/// These can be used on struct fields and enum variant fields.
66///
67/// - `#[specta(type = T)]` overrides the generated field type with `T`.
68/// - `#[specta(inline)]` or `#[specta(inline = true)]` inlines the field type.
69///   Use `#[specta(inline = false)]` to disable it.
70/// - `#[specta(skip)]` or `#[specta(skip = true)]` skips generating the field type.
71///   Use `#[specta(skip = false)]` to disable it.
72/// - `#[specta(optional)]` or `#[specta(optional = true)]` marks the field as optional.
73///   This is commonly used with `Option<T>` to export `{ a?: T | null }` instead of
74///   `{ a: T | null }`.
75/// - `#[specta(default)]` or `#[specta(default = true)]` is an alias for `optional`.
76///
77/// ## Rust attributes
78///
79/// These are read on containers, variants, and fields.
80///
81/// - `#[doc = "..."]` is exported as documentation.
82/// - `#[deprecated]` marks the item as deprecated.
83/// - `#[deprecated = "..."]` marks the item as deprecated with a note.
84/// - `#[deprecated(note = "...")]` marks the item as deprecated with a note.
85/// - `#[deprecated(since = "...", note = "...")]` marks the item as deprecated with a version
86///   and note.
87///
88/// `#[repr(transparent)]` is also accepted on containers as an alias for
89/// `#[specta(transparent)]`.
90///
91/// ## Serde attributes
92///
93/// Specta can read selected `#[serde(...)]` attributes. Prefer Serde attributes when the same
94/// behavior should apply to Serde and Specta.
95///
96/// These are always understood by the derive macro:
97///
98/// - Container: `#[serde(transparent)]` acts like `#[specta(transparent)]`.
99/// - Field: `#[serde(skip)]` acts like `#[specta(skip)]`.
100/// - Variant: `#[serde(skip)]` acts like `#[specta(skip)]`.
101///
102/// With the `serde` feature enabled, the following Serde attributes are also preserved as
103/// runtime attributes.
104/// To apply these attributes during export, use
105/// [`specta_serde::Format`](https://docs.rs/specta-serde/latest/specta_serde/struct.Format.html)
106/// or
107/// [`specta_serde::FormatPhases`](https://docs.rs/specta-serde/latest/specta_serde/struct.FormatPhases.html).
108/// See the [`specta-serde` docs](https://docs.rs/specta-serde) for details.
109///
110/// Container attributes:
111///
112/// - `#[serde(rename = "...")]`
113/// - `#[serde(rename(serialize = "..."))]`
114/// - `#[serde(rename(deserialize = "..."))]`
115/// - `#[serde(rename_all = "...")]`
116/// - `#[serde(rename_all(serialize = "..."))]`
117/// - `#[serde(rename_all(deserialize = "..."))]`
118/// - `#[serde(rename_all_fields = "...")]`
119/// - `#[serde(rename_all_fields(serialize = "..."))]`
120/// - `#[serde(rename_all_fields(deserialize = "..."))]`
121/// - `#[serde(tag = "...")]`
122/// - `#[serde(content = "...")]`
123/// - `#[serde(untagged)]`
124/// - `#[serde(default)]` or `#[serde(default = "...")]`
125/// - `#[serde(transparent)]`
126/// - `#[serde(from = "T")]`
127/// - `#[serde(try_from = "T")]`
128/// - `#[serde(into = "T")]`
129/// - `#[serde(variant_identifier)]`
130/// - `#[serde(field_identifier)]`
131///
132/// Variant attributes:
133///
134/// - `#[serde(rename = "...")]`
135/// - `#[serde(rename(serialize = "..."))]`
136/// - `#[serde(rename(deserialize = "..."))]`
137/// - `#[serde(alias = "...")]`
138/// - `#[serde(rename_all = "...")]`
139/// - `#[serde(rename_all(serialize = "..."))]`
140/// - `#[serde(rename_all(deserialize = "..."))]`
141/// - `#[serde(skip)]`
142/// - `#[serde(skip_serializing)]`
143/// - `#[serde(skip_deserializing)]`
144/// - `#[serde(serialize_with = "...")]`
145/// - `#[serde(deserialize_with = "...")]`
146/// - `#[serde(with = "...")]`
147/// - `#[serde(other)]`
148/// - `#[serde(untagged)]`
149///
150/// Field attributes:
151///
152/// - `#[serde(rename = "...")]`
153/// - `#[serde(rename(serialize = "..."))]`
154/// - `#[serde(rename(deserialize = "..."))]`
155/// - `#[serde(alias = "...")]`
156/// - `#[serde(default)]` or `#[serde(default = "...")]`
157/// - `#[serde(flatten)]`
158/// - `#[serde(skip)]`
159/// - `#[serde(skip_serializing)]`
160/// - `#[serde(skip_deserializing)]`
161/// - `#[serde(skip_serializing_if = "...")]`
162/// - `#[serde(serialize_with = "...")]`
163/// - `#[serde(deserialize_with = "...")]`
164/// - `#[serde(with = "...")]`
165///
166/// Supported rename casing values are:
167///
168/// - `"lowercase"`
169/// - `"UPPERCASE"`
170/// - `"PascalCase"`
171/// - `"camelCase"`
172/// - `"snake_case"`
173/// - `"SCREAMING_SNAKE_CASE"`
174/// - `"kebab-case"`
175/// - `"SCREAMING-KEBAB-CASE"`
176///
177/// ## Example
178///
179/// ```ignore
180/// use specta::Type;
181///
182/// // Use it on structs
183/// #[derive(Type)]
184/// pub struct MyCustomStruct {
185///     pub name: String,
186/// }
187///
188/// #[derive(Type)]
189/// pub struct MyCustomStruct2(String, i32, bool);
190///
191/// // Use it on enums
192/// #[derive(Type)]
193/// pub enum MyCustomType {
194///     VariantOne,
195///     VariantTwo(String, i32),
196///     VariantThree { name: String, age: i32 },
197/// }
198/// ```
199///
200/// ## Known limitations
201///
202///  - Const generics will not be exported within user-defined types which define const generics
203///  - Associated constants or types can't be used
204///
205#[proc_macro_derive(Type, attributes(specta))]
206pub fn derive_type(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
207    r#type::derive(input).unwrap_or_else(|err| err.into_compile_error().into())
208}
209
210/// Parses a string literal into a Rust type token stream.
211///
212/// This is an internal helper proc macro used by Specta macros to turn a
213/// literal like `"Option<String>"` into a Rust type at compile time.
214#[proc_macro]
215pub fn parse_type_from_lit(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
216    let lit = parse_macro_input!(input as LitStr);
217
218    match syn::parse_str::<Type>(&lit.value()) {
219        Ok(ty) => quote!(#ty).into(),
220        Err(err) => Error::new_spanned(lit, format!("invalid type literal: {err}"))
221            .to_compile_error()
222            .into(),
223    }
224}
225
226/// Prepares a function to have its types extracted using `specta::function::fn_datatype!`
227///
228/// ## Example
229///
230/// ```ignore
231/// #[specta::specta]
232/// fn my_function(arg1: i32, arg2: bool) -> &'static str {
233///     "Hello World"
234/// }
235/// ```
236#[proc_macro_attribute]
237#[cfg(feature = "DO_NOT_USE_function")]
238pub fn specta(
239    attr: proc_macro::TokenStream,
240    item: proc_macro::TokenStream,
241) -> proc_macro::TokenStream {
242    specta::attribute(attr, item).unwrap_or_else(|err| err.into_compile_error().into())
243}