fastapi-macros 0.3.0

Procedural macros for fastapi_rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//! OpenAPI/JSON Schema derive macro implementation.
//!
//! This module provides the `#[derive(JsonSchema)]` macro for generating
//! OpenAPI 3.1 JSON Schema from Rust types.
//!
//! # Supported Types
//!
//! - Primitive types: String, &str, i8-i64, u8-u64, f32, f64, bool
//! - Collections: `Vec<T>`, `Option<T>`, `HashMap<K, V>`
//! - Custom structs (with nested schema generation)
//!
//! # Attributes
//!
//! - `#[schema(title = "...")]` - Set schema title
//! - `#[schema(description = "...")]` - Set schema description
//! - `#[schema(format = "...")]` - Override format (e.g., "email", "date-time")
//! - `#[schema(nullable)]` - Mark field as nullable
//! - `#[schema(skip)]` - Skip field in schema generation

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{
    Attribute, Data, DeriveInput, Expr, ExprLit, Fields, GenericArgument, Lit, Meta, MetaNameValue,
    PathArguments, Type, parse_macro_input,
};

/// Schema attributes parsed from `#[schema(...)]`.
#[derive(Default)]
struct SchemaAttrs {
    title: Option<String>,
    description: Option<String>,
    format: Option<String>,
    nullable: bool,
    skip: bool,
}

impl SchemaAttrs {
    fn from_attributes(attrs: &[Attribute]) -> Self {
        let mut result = Self::default();

        for attr in attrs {
            if !attr.path().is_ident("schema") {
                continue;
            }

            let _ = attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("title") {
                    if let Ok(value) = meta.value() {
                        if let Ok(Lit::Str(s)) = value.parse::<Lit>() {
                            result.title = Some(s.value());
                        }
                    }
                } else if meta.path.is_ident("description") {
                    if let Ok(value) = meta.value() {
                        if let Ok(Lit::Str(s)) = value.parse::<Lit>() {
                            result.description = Some(s.value());
                        }
                    }
                } else if meta.path.is_ident("format") {
                    if let Ok(value) = meta.value() {
                        if let Ok(Lit::Str(s)) = value.parse::<Lit>() {
                            result.format = Some(s.value());
                        }
                    }
                } else if meta.path.is_ident("nullable") {
                    result.nullable = true;
                } else if meta.path.is_ident("skip") {
                    result.skip = true;
                }
                Ok(())
            });
        }

        // Also check doc comments for description
        if result.description.is_none() {
            result.description = extract_doc_comment(attrs);
        }

        result
    }
}

/// Extract doc comments from attributes.
fn extract_doc_comment(attrs: &[Attribute]) -> Option<String> {
    let docs: Vec<String> = attrs
        .iter()
        .filter_map(|attr| {
            if !attr.path().is_ident("doc") {
                return None;
            }
            match &attr.meta {
                Meta::NameValue(MetaNameValue {
                    value:
                        Expr::Lit(ExprLit {
                            lit: Lit::Str(s), ..
                        }),
                    ..
                }) => Some(s.value().trim().to_string()),
                _ => None,
            }
        })
        .collect();

    if docs.is_empty() {
        None
    } else {
        Some(docs.join("\n"))
    }
}

/// Information about a struct field.
struct FieldInfo {
    name: String,
    ty: Type,
    attrs: SchemaAttrs,
    is_optional: bool,
}

/// Analyze a type to determine if it's Option<T> and extract T if so.
fn unwrap_option_type(ty: &Type) -> Option<&Type> {
    if let Type::Path(type_path) = ty {
        if let Some(segment) = type_path.path.segments.last() {
            if segment.ident == "Option" {
                if let PathArguments::AngleBracketed(args) = &segment.arguments {
                    if let Some(GenericArgument::Type(inner)) = args.args.first() {
                        return Some(inner);
                    }
                }
            }
        }
    }
    None
}

/// Generate schema code for a type.
#[allow(clippy::too_many_lines)]
fn generate_type_schema(ty: &Type, attrs: &SchemaAttrs) -> TokenStream2 {
    // Check if it's Option<T>
    if let Some(inner) = unwrap_option_type(ty) {
        let inner_schema = generate_type_schema(inner, &SchemaAttrs::default());
        return quote! {
            {
                let mut schema = #inner_schema;
                if let fastapi_openapi::Schema::Primitive(ref mut p) = schema {
                    p.nullable = true;
                }
                schema
            }
        };
    }

    // Handle format override from attributes
    if let Some(ref format) = attrs.format {
        let nullable = attrs.nullable;
        return quote! {
            fastapi_openapi::Schema::Primitive(fastapi_openapi::PrimitiveSchema {
                schema_type: fastapi_openapi::SchemaType::String,
                format: Some(#format.to_string()),
                nullable: #nullable,
            })
        };
    }

    // Check for known types
    if let Type::Path(type_path) = ty {
        if let Some(segment) = type_path.path.segments.last() {
            let ident_str = segment.ident.to_string();

            return match ident_str.as_str() {
                // String types
                "String" | "str" => quote! {
                    fastapi_openapi::Schema::string()
                },

                // Integer types
                "i8" => quote! {
                    fastapi_openapi::Schema::integer(Some("int8"))
                },
                "i16" => quote! {
                    fastapi_openapi::Schema::integer(Some("int16"))
                },
                "i32" => quote! {
                    fastapi_openapi::Schema::integer(Some("int32"))
                },
                "i64" | "isize" => quote! {
                    fastapi_openapi::Schema::integer(Some("int64"))
                },
                "u8" => quote! {
                    fastapi_openapi::Schema::integer(Some("uint8"))
                },
                "u16" => quote! {
                    fastapi_openapi::Schema::integer(Some("uint16"))
                },
                "u32" => quote! {
                    fastapi_openapi::Schema::integer(Some("uint32"))
                },
                "u64" | "usize" => quote! {
                    fastapi_openapi::Schema::integer(Some("uint64"))
                },

                // Float types
                "f32" => quote! {
                    fastapi_openapi::Schema::number(Some("float"))
                },
                "f64" => quote! {
                    fastapi_openapi::Schema::number(Some("double"))
                },

                // Boolean
                "bool" => quote! {
                    fastapi_openapi::Schema::boolean()
                },

                // Vec<T>
                "Vec" => {
                    if let PathArguments::AngleBracketed(args) = &segment.arguments {
                        if let Some(GenericArgument::Type(inner)) = args.args.first() {
                            let inner_schema = generate_type_schema(inner, &SchemaAttrs::default());
                            return quote! {
                                fastapi_openapi::Schema::array(#inner_schema)
                            };
                        }
                    }
                    // Fallback for Vec without type args
                    quote! {
                        fastapi_openapi::Schema::array(fastapi_openapi::Schema::Boolean(true))
                    }
                }

                // HashMap<K, V>
                "HashMap" | "BTreeMap" => {
                    if let PathArguments::AngleBracketed(args) = &segment.arguments {
                        let mut args_iter = args.args.iter();
                        let _key = args_iter.next(); // Skip key type (assumed to be string)
                        if let Some(GenericArgument::Type(value_ty)) = args_iter.next() {
                            let value_schema =
                                generate_type_schema(value_ty, &SchemaAttrs::default());
                            return quote! {
                                fastapi_openapi::Schema::Object(fastapi_openapi::ObjectSchema {
                                    title: None,
                                    description: None,
                                    properties: std::collections::HashMap::new(),
                                    required: Vec::new(),
                                    additional_properties: Some(Box::new(#value_schema)),
                                })
                            };
                        }
                    }
                    // Fallback
                    quote! {
                        fastapi_openapi::Schema::Object(fastapi_openapi::ObjectSchema::default())
                    }
                }

                // Other types - use JsonSchema trait if implemented, otherwise reference
                _ => {
                    // For custom types, try to call their JsonSchema implementation
                    quote! {
                        <#ty as fastapi_openapi::JsonSchema>::schema()
                    }
                }
            };
        }
    }

    // Fallback: try to use the type's JsonSchema implementation
    quote! {
        <#ty as fastapi_openapi::JsonSchema>::schema()
    }
}

#[allow(clippy::too_many_lines)]
pub fn derive_json_schema_impl(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;
    let name_str = name.to_string();

    // Parse struct-level attributes
    let struct_attrs = SchemaAttrs::from_attributes(&input.attrs);
    let title = struct_attrs.title.as_ref().map_or_else(
        || quote! { Some(#name_str.to_string()) },
        |t| quote! { Some(#t.to_string()) },
    );
    let description = struct_attrs
        .description
        .as_ref()
        .map_or_else(|| quote! { None }, |d| quote! { Some(#d.to_string()) });

    // Handle struct data
    let fields = match &input.data {
        Data::Struct(data) => match &data.fields {
            Fields::Named(fields) => fields
                .named
                .iter()
                .filter_map(|f| {
                    let attrs = SchemaAttrs::from_attributes(&f.attrs);
                    if attrs.skip {
                        return None;
                    }
                    let field_name = f.ident.as_ref()?.to_string();
                    let is_optional = unwrap_option_type(&f.ty).is_some();
                    Some(FieldInfo {
                        name: field_name,
                        ty: f.ty.clone(),
                        attrs,
                        is_optional,
                    })
                })
                .collect::<Vec<_>>(),
            Fields::Unnamed(_) => {
                // Tuple structs - not supported for object schema
                return quote! {
                    compile_error!("JsonSchema derive does not support tuple structs");
                }
                .into();
            }
            Fields::Unit => Vec::new(),
        },
        Data::Enum(data) => {
            // Check if all variants are unit variants (simple string enum)
            let is_simple_enum = data.variants.iter().all(|v| v.fields.is_empty());

            if is_simple_enum {
                // Simple string enum: use "enum" keyword in schema
                let variant_names: Vec<String> =
                    data.variants.iter().map(|v| v.ident.to_string()).collect();

                let expanded = quote! {
                    impl fastapi_openapi::JsonSchema for #name {
                        fn schema() -> fastapi_openapi::Schema {
                            fastapi_openapi::Schema::string_enum(vec![#(#variant_names.to_string()),*])
                        }

                        fn schema_name() -> Option<&'static str> {
                            Some(#name_str)
                        }
                    }
                };
                return TokenStream::from(expanded);
            }

            // Complex enum with data: use oneOf with discriminator
            let variant_schemas: Vec<TokenStream2> = data
                .variants
                .iter()
                .map(|v| {
                    let variant_name = v.ident.to_string();
                    let variant_attrs = SchemaAttrs::from_attributes(&v.attrs);
                    let variant_description = variant_attrs
                        .description
                        .as_ref()
                        .map_or_else(|| quote! { None }, |d| quote! { Some(#d.to_string()) });

                    match &v.fields {
                        Fields::Unit => {
                            // Unit variant: just a const value
                            quote! {
                                fastapi_openapi::Schema::Object(fastapi_openapi::ObjectSchema {
                                    title: Some(#variant_name.to_string()),
                                    description: #variant_description,
                                    properties: {
                                        let mut props = std::collections::HashMap::new();
                                        props.insert("type".to_string(),
                                            fastapi_openapi::Schema::Primitive(fastapi_openapi::PrimitiveSchema {
                                                schema_type: fastapi_openapi::SchemaType::String,
                                                format: None,
                                                nullable: false,
                                            }));
                                        props
                                    },
                                    required: vec!["type".to_string()],
                                    additional_properties: None,
                                })
                            }
                        }
                        Fields::Named(fields) => {
                            // Struct variant: object with properties
                            let field_insertions: Vec<TokenStream2> = fields.named.iter()
                                .filter_map(|f| {
                                    let field_name = f.ident.as_ref()?.to_string();
                                    let field_attrs = SchemaAttrs::from_attributes(&f.attrs);
                                    if field_attrs.skip {
                                        return None;
                                    }
                                    let schema_code = generate_type_schema(&f.ty, &field_attrs);
                                    Some(quote! {
                                        props.insert(#field_name.to_string(), #schema_code);
                                    })
                                })
                                .collect();

                            let required: Vec<String> = fields.named.iter()
                                .filter_map(|f| {
                                    let field_name = f.ident.as_ref()?.to_string();
                                    if unwrap_option_type(&f.ty).is_some() {
                                        None
                                    } else {
                                        Some(field_name)
                                    }
                                })
                                .collect();

                            quote! {
                                fastapi_openapi::Schema::Object(fastapi_openapi::ObjectSchema {
                                    title: Some(#variant_name.to_string()),
                                    description: #variant_description,
                                    properties: {
                                        let mut props = std::collections::HashMap::new();
                                        props.insert("type".to_string(),
                                            fastapi_openapi::Schema::Primitive(fastapi_openapi::PrimitiveSchema {
                                                schema_type: fastapi_openapi::SchemaType::String,
                                                format: None,
                                                nullable: false,
                                            }));
                                        #(#field_insertions)*
                                        props
                                    },
                                    required: {
                                        let mut req = vec!["type".to_string()];
                                        req.extend(vec![#(#required.to_string()),*]);
                                        req
                                    },
                                    additional_properties: None,
                                })
                            }
                        }
                        Fields::Unnamed(fields) => {
                            // Tuple variant: if single field, use that type; else use array
                            if fields.unnamed.len() == 1 {
                                let ty = &fields.unnamed.first().unwrap().ty;
                                let inner_schema = generate_type_schema(ty, &SchemaAttrs::default());
                                quote! {
                                    fastapi_openapi::Schema::Object(fastapi_openapi::ObjectSchema {
                                        title: Some(#variant_name.to_string()),
                                        description: #variant_description,
                                        properties: {
                                            let mut props = std::collections::HashMap::new();
                                            props.insert("type".to_string(),
                                                fastapi_openapi::Schema::Primitive(fastapi_openapi::PrimitiveSchema {
                                                    schema_type: fastapi_openapi::SchemaType::String,
                                                    format: None,
                                                    nullable: false,
                                                }));
                                            props.insert("data".to_string(), #inner_schema);
                                            props
                                        },
                                        required: vec!["type".to_string(), "data".to_string()],
                                        additional_properties: None,
                                    })
                                }
                            } else {
                                // Multiple fields - use prefixItems (JSON Schema tuple validation)
                                let field_count = fields.unnamed.len();
                                let field_schemas: Vec<TokenStream2> = fields.unnamed.iter()
                                    .map(|f| generate_type_schema(&f.ty, &SchemaAttrs::default()))
                                    .collect();
                                quote! {
                                    fastapi_openapi::Schema::Object(fastapi_openapi::ObjectSchema {
                                        title: Some(#variant_name.to_string()),
                                        description: #variant_description,
                                        properties: {
                                            let mut props = std::collections::HashMap::new();
                                            props.insert("type".to_string(),
                                                fastapi_openapi::Schema::Primitive(fastapi_openapi::PrimitiveSchema {
                                                    schema_type: fastapi_openapi::SchemaType::String,
                                                    format: None,
                                                    nullable: false,
                                                }));
                                            props.insert("data".to_string(),
                                                fastapi_openapi::Schema::Array(fastapi_openapi::ArraySchema {
                                                    items: Box::new(fastapi_openapi::Schema::one_of(vec![#(#field_schemas),*])),
                                                    min_items: Some(#field_count),
                                                    max_items: Some(#field_count),
                                                }));
                                            props
                                        },
                                        required: vec!["type".to_string(), "data".to_string()],
                                        additional_properties: None,
                                    })
                                }
                            }
                        }
                    }
                })
                .collect();

            let expanded = quote! {
                impl fastapi_openapi::JsonSchema for #name {
                    fn schema() -> fastapi_openapi::Schema {
                        fastapi_openapi::Schema::one_of(vec![#(#variant_schemas),*])
                    }

                    fn schema_name() -> Option<&'static str> {
                        Some(#name_str)
                    }
                }
            };
            return TokenStream::from(expanded);
        }
        Data::Union(_) => {
            return quote! {
                compile_error!("JsonSchema derive does not support unions");
            }
            .into();
        }
    };

    // Generate property insertions
    let property_insertions: Vec<TokenStream2> = fields
        .iter()
        .map(|field| {
            let field_name = &field.name;
            let schema_code = generate_type_schema(&field.ty, &field.attrs);
            quote! {
                properties.insert(#field_name.to_string(), #schema_code);
            }
        })
        .collect();

    // Generate required field names (non-optional fields)
    let required_fields: Vec<&str> = fields
        .iter()
        .filter(|f| !f.is_optional)
        .map(|f| f.name.as_str())
        .collect();

    let expanded = quote! {
        impl fastapi_openapi::JsonSchema for #name {
            fn schema() -> fastapi_openapi::Schema {
                let mut properties = std::collections::HashMap::new();
                #(#property_insertions)*

                let required = vec![#(#required_fields.to_string()),*];

                fastapi_openapi::Schema::Object(fastapi_openapi::ObjectSchema {
                    title: #title,
                    description: #description,
                    properties,
                    required,
                    additional_properties: None,
                })
            }

            fn schema_name() -> Option<&'static str> {
                Some(#name_str)
            }
        }
    };

    TokenStream::from(expanded)
}