reinhardt-openapi-macros 0.2.0

Procedural macros for OpenAPI schema generation in Reinhardt
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
//! Procedural macros for OpenAPI schema generation in Reinhardt.
//!
//! This crate provides derive macros and attribute macros for automatic
//! OpenAPI schema generation from Rust types.
//!

#![warn(missing_docs)]

use proc_macro::TokenStream;
use quote::quote;
use syn::{Data, DeriveInput, Fields, parse_macro_input};

mod crate_paths;
mod schema;
mod serde_attrs;

use crate::crate_paths::get_reinhardt_openapi_crate;
use schema::{FieldAttributes, extract_container_attributes, extract_field_attributes};
use serde_attrs::{
	TaggingStrategy, extract_serde_enum_attrs, extract_serde_rename_all,
	extract_serde_variant_attrs,
};

/// Derive macro for automatic OpenAPI schema generation.
///
/// This macro implements the `ToSchema` trait for your struct or enum,
/// generating an OpenAPI schema based on the type's fields/variants and attributes.
///
/// # Attributes
///
/// ## Container Attributes
///
/// - `#[schema(title = "...")]` - Override the schema title (default: type name)
/// - `#[schema(description = "...")]` - Schema description (overrides doc comments)
/// - `#[schema(example = "...")]` - Example value for the entire type
/// - `#[schema(deprecated)]` - Mark the entire type as deprecated
/// - `#[schema(nullable)]` - Allow null values
///
/// ## Field Attributes (for structs)
///
/// - `#[schema(description = "...")]` - Field description (also reads doc comments)
/// - `#[schema(example = "...")]` - Example value for this field
/// - `#[schema(default)]` - Mark field as having a default value
/// - `#[schema(deprecated)]` - Mark field as deprecated
/// - `#[schema(read_only)]` - Field is read-only (GET responses only)
/// - `#[schema(write_only)]` - Field is write-only (POST/PUT requests only)
/// - `#[schema(format = "...")]` - OpenAPI format (e.g., "email", "uri", "date-time")
/// - `#[schema(minimum = N)]` - Minimum value for numbers (inclusive)
/// - `#[schema(maximum = N)]` - Maximum value for numbers (inclusive)
/// - `#[schema(exclusive_minimum = N)]` - Minimum value for numbers (exclusive)
/// - `#[schema(exclusive_maximum = N)]` - Maximum value for numbers (exclusive)
/// - `#[schema(multiple_of = N)]` - Value must be a multiple of N
/// - `#[schema(min_length = N)]` - Minimum length for strings
/// - `#[schema(max_length = N)]` - Maximum length for strings
/// - `#[schema(pattern = "...")]` - Regex pattern for string validation
/// - `#[schema(min_items = N)]` - Minimum number of array items
/// - `#[schema(max_items = N)]` - Maximum number of array items
/// - `#[schema(unique_items)]` - Array items must be unique
/// - `#[schema(nullable)]` - Field allows null values
/// - `#[schema(default_value = "...")]` - Default value (JSON string)
/// - `#[schema(title = "...")]` - Field-level title override
///
/// # Enum Support
///
/// The macro supports serde's enum tagging strategies:
///
/// - **External** (default): `{"VariantName": {...}}`
/// - **Internal**: `#[serde(tag = "type")]` -> `{"type": "VariantName", ...}`
/// - **Adjacent**: `#[serde(tag = "t", content = "c")]` -> `{"t": "VariantName", "c": {...}}`
/// - **Untagged**: `#[serde(untagged)]` -> `{...}` (no discriminator)
///
/// ## Variant Types
///
/// - **Unit variants**: Become string enum values
/// - **Newtype variants**: Use the inner type's schema
/// - **Tuple variants**: Generate array schema
/// - **Struct variants**: Generate object schema with properties
///
#[proc_macro_derive(Schema, attributes(schema))]
pub fn derive_schema(input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as DeriveInput);

	match &input.data {
		Data::Struct(data) => derive_struct_schema(&input, data),
		Data::Enum(data) => derive_enum_schema(&input, data),
		Data::Union(_) => syn::Error::new_spanned(&input, "Schema cannot be derived for unions")
			.to_compile_error()
			.into(),
	}
}

/// Generate schema for struct types
fn derive_struct_schema(input: &DeriveInput, data: &syn::DataStruct) -> TokenStream {
	let name = &input.ident;
	let generics = &input.generics;
	let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

	let fields = match &data.fields {
		Fields::Named(fields) => &fields.named,
		_ => {
			return syn::Error::new_spanned(
				input,
				"Schema can only be derived for structs with named fields",
			)
			.to_compile_error()
			.into();
		}
	};

	// Extract container-level attributes
	let struct_name = name.to_string();
	let container_attrs = match extract_container_attributes(&input.attrs) {
		Ok(attrs) => attrs,
		Err(err) => return err.to_compile_error().into(),
	};

	// Extract container-level rename_all for field name transformation
	// Fixes #835
	let rename_all = extract_serde_rename_all(&input.attrs);

	// Generate schema for each field
	let mut field_schemas = Vec::new();
	let mut required_fields = Vec::new();
	// Fixes #839: Track flattened fields for allOf generation
	let mut flatten_schemas = Vec::new();

	for field in fields {
		let field_name = field.ident.as_ref().unwrap();
		let field_name_str = field_name.to_string();
		let field_type = &field.ty;

		// Extract field attributes
		let attrs = match extract_field_attributes(&field.attrs) {
			Ok(attrs) => attrs,
			Err(err) => return err.to_compile_error().into(),
		};

		// Fixes #837: Validate mutual exclusion of read_only and write_only
		if attrs.read_only && attrs.write_only {
			return syn::Error::new_spanned(
				field,
				"A field cannot be both read_only and write_only",
			)
			.to_compile_error()
			.into();
		}

		// Fixes #836: Skip fields with serde skip attributes
		if attrs.skip || attrs.skip_serializing || attrs.skip_deserializing {
			continue;
		}

		// Fixes #839: Handle flattened fields separately
		if attrs.flatten {
			let schema_builder = build_field_schema(field_type, &attrs);
			flatten_schemas.push(schema_builder);
			continue;
		}

		// Use renamed property name if available (from #[serde(rename)] or #[schema(rename)])
		// Fixes #835: Apply rename_all if no explicit rename is set
		let property_name = attrs
			.rename
			.clone()
			.unwrap_or_else(|| apply_rename_all(&field_name_str, rename_all.as_deref()));

		// Check if field is Option<T> (makes it optional)
		// Fixes #838: Also consider default attribute for required fields
		let is_option = is_option_type(field_type);
		if !is_option && !attrs.default {
			required_fields.push(property_name.clone());
		}

		// Build field schema with attributes
		let schema_builder = build_field_schema(field_type, &attrs);

		field_schemas.push(quote! {
			builder = builder.property(#property_name, #schema_builder);
		});
	}

	// Add required fields
	let required_builder = if !required_fields.is_empty() {
		quote! {
			#(builder = builder.required(#required_fields);)*
		}
	} else {
		quote! {}
	};

	// Get dynamic crate path
	let openapi_crate = get_reinhardt_openapi_crate();

	// Generate container attribute modifications
	let container_mods = generate_container_modifications(&container_attrs, &openapi_crate);

	// Fixes #839: Generate allOf if there are flattened fields
	let schema_body = if !flatten_schemas.is_empty() {
		quote! {
			use #openapi_crate::Schema;
			use #openapi_crate::utoipa::openapi::schema::{AllOfBuilder, ObjectBuilder, SchemaType, Type};

			// Build the main object schema with regular properties
			let mut builder = ObjectBuilder::new()
				.schema_type(SchemaType::Type(Type::Object));

			#(#field_schemas)*
			#required_builder

			let main_schema = Schema::Object(builder.build());

			// Combine with flattened schemas using allOf
			let mut all_of_builder = AllOfBuilder::new();
			all_of_builder = all_of_builder.item(#openapi_crate::RefOr::T(main_schema));
			#(all_of_builder = all_of_builder.item(#openapi_crate::RefOr::T(#flatten_schemas));)*

			let mut schema = Schema::AllOf(all_of_builder.build());
			#container_mods
			schema
		}
	} else {
		quote! {
			use #openapi_crate::Schema;
			use #openapi_crate::utoipa::openapi::schema::{ObjectBuilder, SchemaType, Type};

			let mut builder = ObjectBuilder::new()
				.schema_type(SchemaType::Type(Type::Object));

			#(#field_schemas)*
			#required_builder

			let mut schema = Schema::Object(builder.build());
			#container_mods
			schema
		}
	};

	// Generate inventory registration only for non-generic types
	// Generic types cannot be registered at compile time since they don't have a concrete type
	let inventory_registration = if generics.params.is_empty() {
		quote! {
			// Automatic schema registration via inventory
			// This allows the framework to discover all schemas at compile time
			::inventory::submit! {
				#openapi_crate::SchemaRegistration::new(
					#struct_name,
					#name::schema
				)
			}
		}
	} else {
		quote! {}
	};

	let expanded = quote! {
		impl #impl_generics #openapi_crate::ToSchema for #name #ty_generics #where_clause {
			fn schema() -> #openapi_crate::Schema {
				#schema_body
			}

			fn schema_name() -> Option<String> {
				Some(#struct_name.to_string())
			}
		}

		#inventory_registration
	};

	TokenStream::from(expanded)
}

/// Generate schema for enum types
fn derive_enum_schema(input: &DeriveInput, data: &syn::DataEnum) -> TokenStream {
	let name = &input.ident;
	let generics = &input.generics;
	let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
	let enum_name = name.to_string();

	// Extract container-level attributes
	let container_attrs = match extract_container_attributes(&input.attrs) {
		Ok(attrs) => attrs,
		Err(err) => return err.to_compile_error().into(),
	};

	// Extract serde enum attributes for tagging strategy
	let serde_attrs = extract_serde_enum_attrs(&input.attrs);
	let tagging = serde_attrs.tagging_strategy();

	// Get dynamic crate path
	let openapi_crate = get_reinhardt_openapi_crate();

	// Check if all variants are unit variants (simple string enum)
	let all_unit_variants = data
		.variants
		.iter()
		.all(|v| matches!(v.fields, Fields::Unit));

	// Generate container attribute modifications
	let container_mods = generate_container_modifications(&container_attrs, &openapi_crate);

	let schema_body = if all_unit_variants && matches!(tagging, TaggingStrategy::External) {
		// Simple string enum: generate string schema with enum values
		let base = generate_simple_enum_schema(data, &openapi_crate, &serde_attrs);
		quote! {
			let mut schema = { #base };
			#container_mods
			schema
		}
	} else {
		// Complex enum: use EnumSchemaBuilder
		let base = generate_complex_enum_schema(data, &openapi_crate, &enum_name, &tagging);
		quote! {
			let mut schema = { #base };
			#container_mods
			schema
		}
	};

	// Generate inventory registration only for non-generic types
	let inventory_registration = if generics.params.is_empty() {
		quote! {
			::inventory::submit! {
				#openapi_crate::SchemaRegistration::new(
					#enum_name,
					#name::schema
				)
			}
		}
	} else {
		quote! {}
	};

	let expanded = quote! {
		impl #impl_generics #openapi_crate::ToSchema for #name #ty_generics #where_clause {
			fn schema() -> #openapi_crate::Schema {
				#schema_body
			}

			fn schema_name() -> Option<String> {
				Some(#enum_name.to_string())
			}
		}

		#inventory_registration
	};

	TokenStream::from(expanded)
}

/// Generate code to apply container-level attributes to a schema
///
/// Handles both `Schema::Object` and `Schema::AllOf` variants, so container
/// attributes work correctly for flattened structs that produce AllOf schemas.
fn generate_container_modifications(
	attrs: &schema::ContainerAttributes,
	openapi_crate: &proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
	let mut mods = Vec::new();

	if let Some(ref title) = attrs.title {
		mods.push(quote! {
			match schema {
				Schema::Object(ref mut obj) => {
					obj.title = Some(#title.to_string());
				}
				Schema::AllOf(ref mut all_of) => {
					all_of.title = Some(#title.to_string());
				}
				_ => {}
			}
		});
	}

	if let Some(ref description) = attrs.description {
		mods.push(quote! {
			match schema {
				Schema::Object(ref mut obj) => {
					obj.description = Some(#description.to_string());
				}
				Schema::AllOf(ref mut all_of) => {
					all_of.description = Some(#description.to_string());
				}
				_ => {}
			}
		});
	}

	if let Some(ref example) = attrs.example {
		// Parse the example string as JSON; fall back to a JSON string if invalid
		mods.push(quote! {
			let example_value: serde_json::Value = serde_json::from_str(#example)
				.unwrap_or_else(|_| serde_json::json!(#example));
			match schema {
				Schema::Object(ref mut obj) => {
					obj.example = Some(example_value);
				}
				Schema::AllOf(ref mut all_of) => {
					all_of.example = Some(example_value);
				}
				_ => {}
			}
		});
	}

	if attrs.deprecated {
		mods.push(quote! {
			match schema {
				Schema::Object(ref mut obj) => {
					obj.deprecated = Some(#openapi_crate::utoipa::openapi::Deprecated::True);
				}
				// AllOf does not have a deprecated field in utoipa;
				// wrap in a single-item AllOf with deprecated on the inner object
				_ => {}
			}
		});
	}

	if attrs.nullable {
		mods.push(quote! {
			{
				use #openapi_crate::utoipa::openapi::schema::{SchemaType, Type};
				match schema {
					Schema::Object(ref mut obj) => {
						// Preserve the existing type and add Null
						let existing_type = std::mem::replace(
							&mut obj.schema_type,
							SchemaType::AnyValue,
						);
						match existing_type {
							SchemaType::Type(t) => {
								obj.schema_type = SchemaType::from_iter([t, Type::Null]);
							}
							other => {
								obj.schema_type = other;
							}
						}
					}
					Schema::AllOf(ref mut all_of) => {
						// AllOf nullable: set schema_type to include Null
						let existing_type = std::mem::replace(
							&mut all_of.schema_type,
							SchemaType::AnyValue,
						);
						match existing_type {
							SchemaType::AnyValue => {
								all_of.schema_type = SchemaType::from_iter([Type::Object, Type::Null]);
							}
							SchemaType::Type(t) => {
								all_of.schema_type = SchemaType::from_iter([t, Type::Null]);
							}
							other => {
								all_of.schema_type = other;
							}
						}
					}
					_ => {}
				}
			}
		});
	}

	if mods.is_empty() {
		quote! {}
	} else {
		quote! {
			#(#mods)*
		}
	}
}

/// Generate schema for simple unit-variant enums (string enum)
fn generate_simple_enum_schema(
	data: &syn::DataEnum,
	openapi_crate: &proc_macro2::TokenStream,
	serde_attrs: &serde_attrs::SerdeEnumAttrs,
) -> proc_macro2::TokenStream {
	let variant_names: Vec<String> = data
		.variants
		.iter()
		.filter_map(|v| {
			let variant_attrs = extract_serde_variant_attrs(&v.attrs);
			if variant_attrs.skip {
				return None;
			}
			// Apply rename if present, considering rename_all strategy
			let name = variant_attrs.rename.unwrap_or_else(|| {
				apply_rename_all(&v.ident.to_string(), serde_attrs.rename_all.as_deref())
			});
			Some(name)
		})
		.collect();

	quote! {
		use #openapi_crate::Schema;
		use #openapi_crate::utoipa::openapi::schema::{ObjectBuilder, SchemaType, Type};

		Schema::Object(
			ObjectBuilder::new()
				.schema_type(SchemaType::Type(Type::String))
				.enum_values(Some(vec![#(serde_json::Value::String(#variant_names.to_string())),*]))
				.build()
		)
	}
}

/// Generate schema for complex enums using EnumSchemaBuilder
fn generate_complex_enum_schema(
	data: &syn::DataEnum,
	openapi_crate: &proc_macro2::TokenStream,
	enum_name: &str,
	tagging: &TaggingStrategy,
) -> proc_macro2::TokenStream {
	// Generate tagging strategy expression
	let tagging_expr = match tagging {
		TaggingStrategy::External => quote! {
			#openapi_crate::EnumTagging::External
		},
		TaggingStrategy::Internal { tag } => quote! {
			#openapi_crate::EnumTagging::Internal { tag: #tag.to_string() }
		},
		TaggingStrategy::Adjacent { tag, content } => quote! {
			#openapi_crate::EnumTagging::Adjacent {
				tag: #tag.to_string(),
				content: #content.to_string(),
			}
		},
		TaggingStrategy::Untagged => quote! {
			#openapi_crate::EnumTagging::Untagged
		},
	};

	// Generate variant schemas
	let variant_additions: Vec<proc_macro2::TokenStream> = data
		.variants
		.iter()
		.filter_map(|variant| {
			let variant_attrs = extract_serde_variant_attrs(&variant.attrs);
			if variant_attrs.skip {
				return None;
			}

			let variant_name = variant_attrs
				.rename
				.clone()
				.unwrap_or_else(|| variant.ident.to_string());

			let variant_schema = generate_variant_schema(&variant.fields, openapi_crate);

			Some(quote! {
				builder = builder.variant(#variant_name, #variant_schema);
			})
		})
		.collect();

	quote! {
		use #openapi_crate::{EnumSchemaBuilder, Schema, SchemaExt};

		let mut builder = EnumSchemaBuilder::new(#enum_name)
			.tagging(#tagging_expr);

		#(#variant_additions)*

		builder.build()
	}
}

/// Generate schema for a single variant's fields
fn generate_variant_schema(
	fields: &Fields,
	openapi_crate: &proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
	match fields {
		Fields::Unit => {
			// Unit variant: empty object or null
			quote! {
				#openapi_crate::Schema::object()
			}
		}
		Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
			// Newtype variant: use inner type's schema
			let inner_type = &fields.unnamed.first().unwrap().ty;
			quote! {
				<#inner_type as #openapi_crate::ToSchema>::schema()
			}
		}
		Fields::Unnamed(fields) => {
			// Tuple variant: array of inner types
			let type_schemas: Vec<proc_macro2::TokenStream> = fields
				.unnamed
				.iter()
				.map(|f| {
					let ty = &f.ty;
					quote! {
						#openapi_crate::RefOr::T(<#ty as #openapi_crate::ToSchema>::schema())
					}
				})
				.collect();

			quote! {
				{
					use #openapi_crate::utoipa::openapi::schema::{ArrayBuilder, SchemaType, Type};
					#openapi_crate::Schema::Array(
						ArrayBuilder::new()
							.schema_type(SchemaType::Type(Type::Array))
							.prefix_items(vec![#(#type_schemas),*])
							.build()
					)
				}
			}
		}
		Fields::Named(fields) => {
			// Struct variant: object with properties
			let mut property_additions = Vec::new();
			let mut required_additions = Vec::new();

			for field in &fields.named {
				let field_name = field.ident.as_ref().unwrap();
				let field_name_str = field_name.to_string();
				let field_type = &field.ty;

				// Check for serde rename on field
				let field_attrs = extract_field_attributes(&field.attrs).unwrap_or_default();
				let property_name = field_attrs.rename.unwrap_or(field_name_str);

				// Check if required
				let is_option = is_option_type(field_type);
				if !is_option {
					required_additions.push(quote! {
						builder = builder.required(#property_name);
					});
				}

				property_additions.push(quote! {
					builder = builder.property(
						#property_name,
						<#field_type as #openapi_crate::ToSchema>::schema()
					);
				});
			}

			quote! {
				{
					use #openapi_crate::utoipa::openapi::schema::{ObjectBuilder, SchemaType, Type};
					let mut builder = ObjectBuilder::new()
						.schema_type(SchemaType::Type(Type::Object));
					#(#property_additions)*
					#(#required_additions)*
					#openapi_crate::Schema::Object(builder.build())
				}
			}
		}
	}
}

/// Apply rename_all transformation to a variant name
fn apply_rename_all(name: &str, rename_all: Option<&str>) -> String {
	match rename_all {
		Some("lowercase") => name.to_lowercase(),
		Some("UPPERCASE") => name.to_uppercase(),
		Some("camelCase") => to_camel_case(name),
		Some("snake_case") => to_snake_case(name),
		Some("SCREAMING_SNAKE_CASE") => to_snake_case(name).to_uppercase(),
		Some("kebab-case") => to_snake_case(name).replace('_', "-"),
		Some("SCREAMING-KEBAB-CASE") => to_snake_case(name).to_uppercase().replace('_', "-"),
		Some("PascalCase") | None => name.to_string(),
		Some(_) => name.to_string(),
	}
}

/// Convert PascalCase to camelCase
fn to_camel_case(s: &str) -> String {
	let mut result = String::new();
	for (i, c) in s.chars().enumerate() {
		if i == 0 {
			result.extend(c.to_lowercase());
		} else {
			result.push(c);
		}
	}
	result
}

/// Convert PascalCase to snake_case
/// Fixes #833: Handle consecutive uppercase correctly (e.g., "XMLParser" -> "xmlparser")
///
/// This follows serde's behavior where consecutive uppercase letters are treated
/// as a single word (e.g., "XMLParser" -> "xmlparser", not "x_m_l_parser").
fn to_snake_case(s: &str) -> String {
	let mut result = String::new();
	let chars: Vec<char> = s.chars().collect();

	for (i, c) in chars.iter().enumerate() {
		if c.is_uppercase() {
			// Only insert underscore before uppercase if:
			// 1. Not the first character AND
			// 2. Previous character is lowercase OR
			// 3. (Not the last character AND next character is lowercase)
			// This handles: "HttpRequest" -> "http_request"
			// But not: "XMLParser" -> "x_m_l_parser" (becomes "xmlparser")
			if i > 0 {
				let prev_is_lowercase = chars[i - 1].is_lowercase();
				let next_is_lowercase = i + 1 < chars.len() && chars[i + 1].is_lowercase();

				if prev_is_lowercase || next_is_lowercase {
					result.push('_');
				}
			}
			result.extend(c.to_lowercase());
		} else {
			result.push(*c);
		}
	}
	result
}

/// Helper function to check if a type is `Option<T>`
fn is_option_type(ty: &syn::Type) -> bool {
	if let syn::Type::Path(type_path) = ty
		&& let Some(segment) = type_path.path.segments.last()
	{
		return segment.ident == "Option";
	}
	false
}

/// Build schema for a field type with attributes
fn build_field_schema(field_type: &syn::Type, attrs: &FieldAttributes) -> proc_macro2::TokenStream {
	let openapi_crate = get_reinhardt_openapi_crate();
	let base_schema = quote! {
		<#field_type as #openapi_crate::ToSchema>::schema()
	};

	// If no attributes, return base schema
	if attrs.is_empty() {
		return base_schema;
	}

	// Build schema with attributes applied
	let mut modifications = Vec::new();

	if let Some(ref title) = attrs.title {
		modifications.push(quote! {
			if let Schema::Object(ref mut obj) = schema {
				obj.title = Some(#title.to_string());
			}
		});
	}

	if let Some(ref description) = attrs.description {
		modifications.push(quote! {
			if let Schema::Object(ref mut obj) = schema {
				obj.description = Some(#description.to_string());
			}
		});
	}

	if let Some(ref example) = attrs.example {
		// Parse the example string as JSON; fall back to a JSON string if invalid
		modifications.push(quote! {
			if let Schema::Object(ref mut obj) = schema {
				obj.example = Some(
					serde_json::from_str(#example)
						.unwrap_or_else(|_| serde_json::json!(#example))
				);
			}
		});
	}

	if let Some(ref format) = attrs.format {
		modifications.push(quote! {
			if let Schema::Object(ref mut obj) = schema {
				obj.format = Some(#openapi_crate::utoipa::openapi::schema::SchemaFormat::Custom(#format.to_string()));
			}
		});
	}

	if attrs.read_only {
		modifications.push(quote! {
			if let Schema::Object(ref mut obj) = schema {
				obj.read_only = Some(true);
			}
		});
	}

	if attrs.write_only {
		modifications.push(quote! {
			if let Schema::Object(ref mut obj) = schema {
				obj.write_only = Some(true);
			}
		});
	}

	if attrs.deprecated {
		modifications.push(quote! {
			if let Schema::Object(ref mut obj) = schema {
				obj.deprecated = Some(#openapi_crate::utoipa::openapi::Deprecated::True);
			}
		});
	}

	if let Some(min) = attrs.minimum {
		modifications.push(quote! {
			if let Schema::Object(ref mut obj) = schema {
				obj.minimum = Some(#openapi_crate::utoipa::Number::from(#min as f64));
			}
		});
	}

	if let Some(max) = attrs.maximum {
		modifications.push(quote! {
			if let Schema::Object(ref mut obj) = schema {
				obj.maximum = Some(#openapi_crate::utoipa::Number::from(#max as f64));
			}
		});
	}

	if let Some(ex_min) = attrs.exclusive_minimum {
		modifications.push(quote! {
			if let Schema::Object(ref mut obj) = schema {
				obj.exclusive_minimum = Some(#openapi_crate::utoipa::Number::from(#ex_min as f64));
			}
		});
	}

	if let Some(ex_max) = attrs.exclusive_maximum {
		modifications.push(quote! {
			if let Schema::Object(ref mut obj) = schema {
				obj.exclusive_maximum = Some(#openapi_crate::utoipa::Number::from(#ex_max as f64));
			}
		});
	}

	if let Some(mul) = attrs.multiple_of {
		modifications.push(quote! {
			if let Schema::Object(ref mut obj) = schema {
				obj.multiple_of = Some(#openapi_crate::utoipa::Number::from(#mul));
			}
		});
	}

	if let Some(min_len) = attrs.min_length {
		modifications.push(quote! {
			if let Schema::Object(ref mut obj) = schema {
				obj.min_length = Some(#min_len);
			}
		});
	}

	if let Some(max_len) = attrs.max_length {
		modifications.push(quote! {
			if let Schema::Object(ref mut obj) = schema {
				obj.max_length = Some(#max_len);
			}
		});
	}

	if let Some(ref pattern) = attrs.pattern {
		modifications.push(quote! {
			if let Schema::Object(ref mut obj) = schema {
				obj.pattern = Some(#pattern.to_string());
			}
		});
	}

	if let Some(min_items) = attrs.min_items {
		modifications.push(quote! {
			if let Schema::Array(ref mut arr) = schema {
				arr.min_items = Some(#min_items);
			}
		});
	}

	if let Some(max_items) = attrs.max_items {
		modifications.push(quote! {
			if let Schema::Array(ref mut arr) = schema {
				arr.max_items = Some(#max_items);
			}
		});
	}

	if attrs.unique_items {
		modifications.push(quote! {
			if let Schema::Array(ref mut arr) = schema {
				arr.unique_items = true;
			}
		});
	}

	if attrs.nullable {
		modifications.push(quote! {
			use #openapi_crate::utoipa::openapi::schema::{SchemaType, Type};
			match schema {
				Schema::Object(ref mut obj) => {
					// Preserve the existing type and add Null
					let existing_type = std::mem::replace(
						&mut obj.schema_type,
						SchemaType::AnyValue,
					);
					match existing_type {
						SchemaType::Type(t) => {
							obj.schema_type = SchemaType::from_iter([t, Type::Null]);
						}
						other => {
							obj.schema_type = other;
						}
					}
				}
				Schema::Array(ref mut arr) => {
					// Preserve the existing array type and add Null
					let existing_type = std::mem::replace(
						&mut arr.schema_type,
						SchemaType::AnyValue,
					);
					match existing_type {
						SchemaType::Type(t) => {
							arr.schema_type = SchemaType::from_iter([t, Type::Null]);
						}
						other => {
							arr.schema_type = other;
						}
					}
				}
				Schema::AllOf(ref mut all_of) => {
					// AllOf nullable: set schema_type to include Null
					let existing_type = std::mem::replace(
						&mut all_of.schema_type,
						SchemaType::AnyValue,
					);
					match existing_type {
						SchemaType::AnyValue => {
							all_of.schema_type = SchemaType::from_iter([Type::Object, Type::Null]);
						}
						SchemaType::Type(t) => {
							all_of.schema_type = SchemaType::from_iter([t, Type::Null]);
						}
						other => {
							all_of.schema_type = other;
						}
					}
				}
				_ => {}
			}
		});
	}

	if let Some(ref default_value) = attrs.default_value {
		modifications.push(quote! {
			if let Schema::Object(ref mut obj) = schema {
				obj.default = Some(serde_json::json!(#default_value));
			}
		});
	}

	if modifications.is_empty() {
		base_schema
	} else {
		quote! {
			{
				use #openapi_crate::Schema;
				let mut schema = #base_schema;
				#(#modifications)*
				schema
			}
		}
	}
}