Skip to main content

gurafi_macros/
lib.rs

1//! Procedural macros for `gurafi`.
2//!
3//! These macros let Rust types drive the GraphQL type system:
4//!
5//! - [`macro@Object`] registers a Rust struct as a GraphQL object type.
6//! - [`macro@Input`] registers a Rust struct as a field's arguments, or as a named input object
7//!   when it carries `#[graphql(name = "...")]`.
8//! - [`macro@Args`] is an alias for [`macro@Input`] that says the type is only a field's
9//!   arguments.
10//! - [`macro@Enum`] registers a Rust enum as a GraphQL enum.
11//! - [`macro@Scalar`] registers a newtype as a custom scalar delegating to its inner type.
12//! - [`macro@Union`] registers a Rust enum as a GraphQL union of object types.
13//! - [`macro@ErrorUnion`] declares the typed errors a `field_result_union` exposes.
14//!
15//! Every macro emits all of the trait implementations `gurafi` needs, so a derive is the
16//! whole registration: there is no second list of fields to keep in sync. Unsupported shapes
17//! (generic types, tuple structs for [`macro@Input`], enums with data for [`macro@Enum`])
18//! produce a `compile_error!` with an explanation instead of a confusing trait bound failure.
19
20#![doc(
21    html_favicon_url = "https://raw.githubusercontent.com/specta-rs/gurafi/main/docs/favicon.svg",
22    html_logo_url = "https://raw.githubusercontent.com/specta-rs/gurafi/main/assets/app-icon.svg"
23)]
24#![forbid(unsafe_code)]
25#![warn(missing_docs)]
26
27mod attr;
28mod enums;
29mod error_union;
30mod input;
31mod object;
32mod scalar;
33mod union;
34mod util;
35
36use proc_macro::TokenStream;
37use syn::{DeriveInput, parse_macro_input};
38
39/// Derive a GraphQL object type.
40///
41/// The Rust type name becomes the GraphQL type name; override it with
42/// `#[graphql(name = "...")]`. A doc comment on the type becomes its description, and
43/// `#[graphql(description = "...")]` overrides the comment.
44///
45/// Fields are *not* derived. An object's GraphQL fields are declared explicitly on the
46/// schema builder with `field`, `field_result`, `field_async`, `field_result_async` or
47/// `expose`, so every field's resolver and access rules live in one place.
48///
49/// ```ignore
50/// use gurafi::Object;
51///
52/// #[derive(Object)]
53/// #[graphql(description = "A long-necked animal.")]
54/// struct Giraffe {
55///     name: String,
56/// }
57/// ```
58#[proc_macro_derive(Object, attributes(graphql))]
59pub fn derive_object(input: TokenStream) -> TokenStream {
60    let input = parse_macro_input!(input as DeriveInput);
61    object::expand(input)
62        .unwrap_or_else(syn::Error::into_compile_error)
63        .into()
64}
65
66/// Derive a GraphQL input type.
67///
68/// # Arguments by default
69///
70/// Without a name, the type is **args-only**: its fields become a field's arguments
71/// (`A: InputObject`) and no input object is registered in the schema. This is what an
72/// arguments struct should be — `friends(limit: 10, after: "...")` rather than a leaked
73/// `FriendsArgs` input type.
74///
75/// A type that is also used nested inside another input object must be named:
76///
77/// ```ignore
78/// use gurafi::Input;
79///
80/// #[derive(Input)]
81/// struct FriendsArgs {
82///     #[graphql(description = "Max results", default = 10)]
83///     limit: i32,
84///     after: Option<String>,
85/// }
86///
87/// #[derive(Input)]
88/// #[graphql(name = "FilterInput")]
89/// struct Filter {
90///     prefix: Option<String>,
91/// }
92///
93/// #[derive(Input)]
94/// struct SearchArgs {
95///     filter: Option<Filter>, // requires FilterInput to exist
96/// }
97/// ```
98///
99/// Attribute support:
100///
101/// - `#[graphql(name = "...")]` makes the type a reusable named input object, or renames one of
102///   its fields.
103/// - `#[graphql(description = "...")]` (or a doc comment) sets a description.
104/// - `#[graphql(default = expr)]` sets a default value, typed as the field's Rust type.
105/// - `#[graphql(default_with = "path")]` computes the default by calling `path()`.
106/// - `#[graphql(deprecated)]` / `#[graphql(deprecated = "reason")]` deprecates a field.
107/// - `#[graphql(validate = "path")]` runs `path(&value)` after coercion. On the type it receives
108///   `&Self`; on a field it receives `&FieldType`. The function returns
109///   `Result<(), gql::GraphQLError>` and its error becomes a field error.
110/// - `#[graphql(one_of)]` marks a named input as a `@oneOf` input. Every field must be
111///   `Option<T>` and no field may have a default.
112///
113/// `Option<T>` fields are optional; every other field without a default is required.
114#[proc_macro_derive(Input, attributes(graphql))]
115pub fn derive_input(input: TokenStream) -> TokenStream {
116    let input = parse_macro_input!(input as DeriveInput);
117    input::expand(input)
118        .unwrap_or_else(syn::Error::into_compile_error)
119        .into()
120}
121
122/// Derive a field's arguments type.
123///
124/// This is an alias for [`macro@Input`] in its default, args-only form. It exists to make the
125/// intent obvious at the declaration site; if the type later needs to be a reusable named input
126/// object, add `#[graphql(name = "...")]` and the behaviour is identical to [`macro@Input`].
127#[proc_macro_derive(Args, attributes(graphql))]
128pub fn derive_args(input: TokenStream) -> TokenStream {
129    let input = parse_macro_input!(input as DeriveInput);
130    input::expand(input)
131        .unwrap_or_else(syn::Error::into_compile_error)
132        .into()
133}
134
135/// Derive a GraphQL enum.
136///
137/// GraphQL enum values are usually `SCREAMING_CASE`; the Rust variant name is used verbatim
138/// unless `#[graphql(name = "...")]` overrides it. Variants must be unit variants.
139///
140/// ```ignore
141/// use gurafi::Enum;
142///
143/// #[derive(Enum)]
144/// enum Color {
145///     #[graphql(name = "RED")]
146///     Red,
147///     Blue,
148/// }
149/// ```
150#[proc_macro_derive(Enum, attributes(graphql))]
151pub fn derive_enum(input: TokenStream) -> TokenStream {
152    let input = parse_macro_input!(input as DeriveInput);
153    enums::expand(input)
154        .unwrap_or_else(syn::Error::into_compile_error)
155        .into()
156}
157
158/// Derive a custom GraphQL scalar from a newtype.
159///
160/// The newtype delegates to its inner type's input and value conversions, which is how a
161/// validated wrapper (a date, a UUID, an email address) becomes a scalar without writing any
162/// conversions by hand.
163///
164/// ```ignore
165/// use gurafi::Scalar;
166///
167/// #[derive(Scalar, Clone)]
168/// #[graphql(name = "Date", description = "An ISO-8601 date.")]
169/// struct Date(String);
170/// ```
171#[proc_macro_derive(Scalar, attributes(graphql))]
172pub fn derive_scalar(input: TokenStream) -> TokenStream {
173    let input = parse_macro_input!(input as DeriveInput);
174    scalar::expand(input)
175        .unwrap_or_else(syn::Error::into_compile_error)
176        .into()
177}
178
179/// Derive a GraphQL union from an enum of object models.
180///
181/// Each variant must be a newtype variant whose inner type derives [`macro@Object`]. The union
182/// itself is still declared on the schema with `schema.union(...)`, so its members and members'
183/// fields stay visible where the rest of the schema is defined.
184///
185/// ```ignore
186/// use gurafi::{Object, Union};
187///
188/// #[derive(Object)]
189/// struct User {
190///     name: String,
191/// }
192///
193/// #[derive(Object)]
194/// struct Post {
195///     title: String,
196/// }
197///
198/// #[derive(Union)]
199/// enum SearchResult {
200///     User(User),
201///     Post(Post),
202/// }
203/// ```
204#[proc_macro_derive(Union, attributes(graphql))]
205pub fn derive_union(input: TokenStream) -> TokenStream {
206    let input = parse_macro_input!(input as DeriveInput);
207    union::expand(input)
208        .unwrap_or_else(syn::Error::into_compile_error)
209        .into()
210}
211
212/// Derive the typed errors of a result-union field.
213///
214/// The enum is not itself a GraphQL type. It describes how a `field_result_union` field turns
215/// each Rust error variant into a GraphQL object payload, and the generated result union uses
216/// those payloads as members. Every variant must hold exactly one object model:
217///
218/// ```ignore
219/// use gurafi::{ErrorUnion, Object};
220///
221/// #[derive(Object)]
222/// struct NotFoundError {
223///     message: String,
224/// }
225///
226/// #[derive(Object)]
227/// struct ConflictError {
228///     field: String,
229/// }
230///
231/// #[derive(ErrorUnion)]
232/// enum CreateUserError {
233///     NotFound(NotFoundError),
234///     Conflict(ConflictError),
235/// }
236/// ```
237///
238/// The payload objects must still be registered with `schema.object::<M>(...)`. Missing
239/// registration is a schema build error that names the missing payload. Generic enums, unit
240/// variants, struct variants and tuple variants with zero or several fields are compile errors.
241#[proc_macro_derive(ErrorUnion)]
242pub fn derive_error_union(input: TokenStream) -> TokenStream {
243    let input = parse_macro_input!(input as DeriveInput);
244    error_union::expand(input)
245        .unwrap_or_else(syn::Error::into_compile_error)
246        .into()
247}