-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathschema.rs
More file actions
2716 lines (2515 loc) · 111 KB
/
schema.rs
File metadata and controls
2716 lines (2515 loc) · 111 KB
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
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::{BTreeMap, HashMap};
use syn::{Fields, Type};
use vespera_core::schema::{Reference, Schema, SchemaRef, SchemaType};
/// Strips the `r#` prefix from raw identifiers.
/// E.g., `r#type` becomes `type`.
pub fn strip_raw_prefix(ident: &str) -> &str {
ident.strip_prefix("r#").unwrap_or(ident)
}
pub fn extract_rename_all(attrs: &[syn::Attribute]) -> Option<String> {
for attr in attrs {
if attr.path().is_ident("serde") {
// Try using parse_nested_meta for robust parsing
let mut found_rename_all = None;
let _ = attr.parse_nested_meta(|meta| {
if meta.path.is_ident("rename_all")
&& let Ok(value) = meta.value()
&& let Ok(syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(s),
..
})) = value.parse::<syn::Expr>()
{
found_rename_all = Some(s.value());
}
Ok(())
});
if found_rename_all.is_some() {
return found_rename_all;
}
// Fallback: manual token parsing for complex attribute combinations
let tokens = match attr.meta.require_list() {
Ok(t) => t,
Err(_) => continue,
};
let token_str = tokens.tokens.to_string();
// Look for rename_all = "..." pattern
if let Some(start) = token_str.find("rename_all") {
let remaining = &token_str[start + "rename_all".len()..];
if let Some(equals_pos) = remaining.find('=') {
let value_part = remaining[equals_pos + 1..].trim();
// Extract string value - find the closing quote
if let Some(quote_start) = value_part.find('"') {
let after_quote = &value_part[quote_start + 1..];
if let Some(quote_end) = after_quote.find('"') {
let value = &after_quote[..quote_end];
return Some(value.to_string());
}
}
}
}
}
}
None
}
pub fn extract_field_rename(attrs: &[syn::Attribute]) -> Option<String> {
for attr in attrs {
if attr.path().is_ident("serde")
&& let syn::Meta::List(meta_list) = &attr.meta
{
// Use parse_nested_meta to parse nested attributes
let mut found_rename = None;
let _ = attr.parse_nested_meta(|meta| {
if meta.path.is_ident("rename")
&& let Ok(value) = meta.value()
&& let Ok(syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(s),
..
})) = value.parse::<syn::Expr>()
{
found_rename = Some(s.value());
}
Ok(())
});
if let Some(rename_value) = found_rename {
return Some(rename_value);
}
// Fallback: manual token parsing for complex attribute combinations
let tokens = meta_list.tokens.to_string();
// Look for pattern: rename = "value" (with proper word boundaries)
if let Some(start) = tokens.find("rename") {
// Avoid false positives from rename_all
if tokens[start..].starts_with("rename_all") {
continue;
}
// Check that "rename" is a standalone word (not part of another word)
let before = if start > 0 { &tokens[..start] } else { "" };
let after_start = start + "rename".len();
let after = if after_start < tokens.len() {
&tokens[after_start..]
} else {
""
};
let before_char = before.chars().last().unwrap_or(' ');
let after_char = after.chars().next().unwrap_or(' ');
// Check if rename is a standalone word (preceded by space/comma/paren, followed by space/equals)
if (before_char == ' ' || before_char == ',' || before_char == '(')
&& (after_char == ' ' || after_char == '=')
{
// Find the equals sign and extract the quoted value
if let Some(equals_pos) = after.find('=') {
let value_part = &after[equals_pos + 1..].trim();
// Extract string value (remove quotes)
if let Some(quote_start) = value_part.find('"') {
let after_quote = &value_part[quote_start + 1..];
if let Some(quote_end) = after_quote.find('"') {
let value = &after_quote[..quote_end];
return Some(value.to_string());
}
}
}
}
}
}
}
None
}
/// Extract skip attribute from field attributes
/// Returns true if #[serde(skip)] is present
pub(super) fn extract_skip(attrs: &[syn::Attribute]) -> bool {
for attr in attrs {
if attr.path().is_ident("serde")
&& let syn::Meta::List(meta_list) = &attr.meta
{
let tokens = meta_list.tokens.to_string();
// Check for "skip" (not part of skip_serializing_if or skip_deserializing)
if tokens.contains("skip") {
// Make sure it's not skip_serializing_if or skip_deserializing
if !tokens.contains("skip_serializing_if") && !tokens.contains("skip_deserializing")
{
// Check if it's a standalone "skip"
let skip_pos = tokens.find("skip");
if let Some(pos) = skip_pos {
let before = if pos > 0 { &tokens[..pos] } else { "" };
let after = &tokens[pos + "skip".len()..];
// Check if skip is not part of another word
let before_char = before.chars().last().unwrap_or(' ');
let after_char = after.chars().next().unwrap_or(' ');
if (before_char == ' ' || before_char == ',' || before_char == '(')
&& (after_char == ' ' || after_char == ',' || after_char == ')')
{
return true;
}
}
}
}
}
}
false
}
/// Extract skip_serializing_if attribute from field attributes
/// Returns true if #[serde(skip_serializing_if = "...")] is present
pub fn extract_skip_serializing_if(attrs: &[syn::Attribute]) -> bool {
for attr in attrs {
if attr.path().is_ident("serde")
&& let syn::Meta::List(meta_list) = &attr.meta
{
let mut found = false;
let _ = attr.parse_nested_meta(|meta| {
if meta.path.is_ident("skip_serializing_if") {
found = true;
}
Ok(())
});
if found {
return true;
}
// Fallback: check tokens string for complex attribute combinations
let tokens = meta_list.tokens.to_string();
if tokens.contains("skip_serializing_if") {
return true;
}
}
}
false
}
/// Extract default attribute from field attributes
/// Returns:
/// - Some(None) if #[serde(default)] is present (no function)
/// - Some(Some(function_name)) if #[serde(default = "function_name")] is present
/// - None if no default attribute is present
pub fn extract_default(attrs: &[syn::Attribute]) -> Option<Option<String>> {
for attr in attrs {
if attr.path().is_ident("serde")
&& let syn::Meta::List(meta_list) = &attr.meta
{
let mut found_default: Option<Option<String>> = None;
let _ = attr.parse_nested_meta(|meta| {
if meta.path.is_ident("default") {
// Check if it has a value (default = "function_name")
if let Ok(value) = meta.value() {
if let Ok(syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(s),
..
})) = value.parse::<syn::Expr>()
{
found_default = Some(Some(s.value()));
}
} else {
// Just "default" without value
found_default = Some(None);
}
}
Ok(())
});
if let Some(default_value) = found_default {
return Some(default_value);
}
// Fallback: manual token parsing for complex attribute combinations
let tokens = meta_list.tokens.to_string();
if let Some(start) = tokens.find("default") {
let remaining = &tokens[start + "default".len()..];
if remaining.trim_start().starts_with('=') {
// default = "function_name"
let after_equals = remaining
.trim_start()
.strip_prefix('=')
.unwrap_or("")
.trim_start();
// Extract string value - find opening and closing quotes
if let Some(quote_start) = after_equals.find('"') {
let after_quote = &after_equals[quote_start + 1..];
if let Some(quote_end) = after_quote.find('"') {
let function_name = &after_quote[..quote_end];
return Some(Some(function_name.to_string()));
}
}
} else {
// Just "default" without = (standalone)
let before = if start > 0 { &tokens[..start] } else { "" };
let after = &remaining;
let before_char = before.chars().last().unwrap_or(' ');
let after_char = after.chars().next().unwrap_or(' ');
if (before_char == ' ' || before_char == ',' || before_char == '(')
&& (after_char == ' ' || after_char == ',' || after_char == ')')
{
return Some(None);
}
}
}
}
}
None
}
pub fn rename_field(field_name: &str, rename_all: Option<&str>) -> String {
// "lowercase", "UPPERCASE", "PascalCase", "camelCase", "snake_case", "SCREAMING_SNAKE_CASE", "kebab-case", "SCREAMING-KEBAB-CASE"
match rename_all {
Some("camelCase") => {
// Convert snake_case or PascalCase to camelCase
let mut result = String::new();
let mut capitalize_next = false;
let mut in_first_word = true;
let chars: Vec<char> = field_name.chars().collect();
for (i, &ch) in chars.iter().enumerate() {
if ch == '_' {
capitalize_next = true;
in_first_word = false;
} else if in_first_word {
// In first word: lowercase until we hit a word boundary
// Word boundary: uppercase char followed by lowercase (e.g., "XMLParser" -> "P" starts new word)
let next_is_lower = chars.get(i + 1).is_some_and(|c| c.is_lowercase());
if ch.is_uppercase() && next_is_lower && i > 0 {
// This uppercase starts a new word (e.g., 'P' in "XMLParser")
in_first_word = false;
result.push(ch);
} else {
// Still in first word, lowercase it
result.push(ch.to_lowercase().next().unwrap_or(ch));
}
} else if capitalize_next {
result.push(ch.to_uppercase().next().unwrap_or(ch));
capitalize_next = false;
} else {
result.push(ch);
}
}
result
}
Some("snake_case") => {
// Convert camelCase to snake_case
let mut result = String::new();
for (i, ch) in field_name.chars().enumerate() {
if ch.is_uppercase() && i > 0 {
result.push('_');
}
result.push(ch.to_lowercase().next().unwrap_or(ch));
}
result
}
Some("kebab-case") => {
// Convert snake_case or Camel/PascalCase to kebab-case (lowercase with hyphens)
let mut result = String::new();
for (i, ch) in field_name.chars().enumerate() {
if ch.is_uppercase() {
if i > 0 && !result.ends_with('-') {
result.push('-');
}
result.push(ch.to_lowercase().next().unwrap_or(ch));
} else if ch == '_' {
result.push('-');
} else {
result.push(ch);
}
}
result
}
Some("PascalCase") => {
// Convert snake_case to PascalCase
let mut result = String::new();
let mut capitalize_next = true;
for ch in field_name.chars() {
if ch == '_' {
capitalize_next = true;
} else if capitalize_next {
result.push(ch.to_uppercase().next().unwrap_or(ch));
capitalize_next = false;
} else {
result.push(ch);
}
}
result
}
Some("lowercase") => {
// Convert to lowercase
field_name.to_lowercase()
}
Some("UPPERCASE") => {
// Convert to UPPERCASE
field_name.to_uppercase()
}
Some("SCREAMING_SNAKE_CASE") => {
// Convert to SCREAMING_SNAKE_CASE
// If already in SCREAMING_SNAKE_CASE format, return as is
if field_name.chars().all(|c| c.is_uppercase() || c == '_') && field_name.contains('_')
{
return field_name.to_string();
}
// First convert to snake_case if needed, then uppercase
let mut snake_case = String::new();
for (i, ch) in field_name.chars().enumerate() {
if ch.is_uppercase() && i > 0 && !snake_case.ends_with('_') {
snake_case.push('_');
}
if ch != '_' && ch != '-' {
snake_case.push(ch.to_lowercase().next().unwrap_or(ch));
} else if ch == '_' {
snake_case.push('_');
}
}
snake_case.to_uppercase()
}
Some("SCREAMING-KEBAB-CASE") => {
// Convert to SCREAMING-KEBAB-CASE
// First convert to kebab-case if needed, then uppercase
let mut kebab_case = String::new();
for (i, ch) in field_name.chars().enumerate() {
if ch.is_uppercase()
&& i > 0
&& !kebab_case.ends_with('-')
&& !kebab_case.ends_with('_')
{
kebab_case.push('-');
}
if ch == '_' {
kebab_case.push('-');
} else if ch != '-' {
kebab_case.push(ch.to_lowercase().next().unwrap_or(ch));
} else {
kebab_case.push('-');
}
}
kebab_case.to_uppercase()
}
_ => field_name.to_string(),
}
}
pub fn parse_enum_to_schema(
enum_item: &syn::ItemEnum,
known_schemas: &HashMap<String, String>,
struct_definitions: &HashMap<String, String>,
) -> Schema {
// Extract rename_all attribute from enum
let rename_all = extract_rename_all(&enum_item.attrs);
// Check if all variants are unit variants
let all_unit = enum_item
.variants
.iter()
.all(|v| matches!(v.fields, syn::Fields::Unit));
if all_unit {
// Simple enum with string values
let mut enum_values = Vec::new();
for variant in &enum_item.variants {
let variant_name = strip_raw_prefix(&variant.ident.to_string()).to_string();
// Check for variant-level rename attribute first (takes precedence)
let enum_value = if let Some(renamed) = extract_field_rename(&variant.attrs) {
renamed
} else {
// Apply rename_all transformation if present
rename_field(&variant_name, rename_all.as_deref())
};
enum_values.push(serde_json::Value::String(enum_value));
}
Schema {
schema_type: Some(SchemaType::String),
r#enum: if enum_values.is_empty() {
None
} else {
Some(enum_values)
},
..Schema::string()
}
} else {
// Enum with data - use oneOf
let mut one_of_schemas = Vec::new();
for variant in &enum_item.variants {
let variant_name = strip_raw_prefix(&variant.ident.to_string()).to_string();
// Check for variant-level rename attribute first (takes precedence)
let variant_key = if let Some(renamed) = extract_field_rename(&variant.attrs) {
renamed
} else {
// Apply rename_all transformation if present
rename_field(&variant_name, rename_all.as_deref())
};
let variant_schema = match &variant.fields {
syn::Fields::Unit => {
// Unit variant: {"const": "VariantName"}
Schema {
r#enum: Some(vec![serde_json::Value::String(variant_key)]),
..Schema::string()
}
}
syn::Fields::Unnamed(fields_unnamed) => {
// Tuple variant: {"VariantName": <inner_type>}
// For single field: {"VariantName": <type>}
// For multiple fields: {"VariantName": [<type1>, <type2>, ...]}
if fields_unnamed.unnamed.len() == 1 {
// Single field tuple variant
let inner_type = &fields_unnamed.unnamed[0].ty;
let inner_schema =
parse_type_to_schema_ref(inner_type, known_schemas, struct_definitions);
let mut properties = BTreeMap::new();
properties.insert(variant_key.clone(), inner_schema);
Schema {
properties: Some(properties),
required: Some(vec![variant_key]),
..Schema::object()
}
} else {
// Multiple fields tuple variant - serialize as array
// serde serializes tuple variants as: {"VariantName": [value1, value2, ...]}
// For OpenAPI 3.1, we use prefixItems to represent tuple arrays
let mut tuple_item_schemas = Vec::new();
for field in &fields_unnamed.unnamed {
let field_schema = parse_type_to_schema_ref(
&field.ty,
known_schemas,
struct_definitions,
);
tuple_item_schemas.push(field_schema);
}
let tuple_len = tuple_item_schemas.len();
// Create array schema with prefixItems for tuple arrays (OpenAPI 3.1)
let array_schema = Schema {
prefix_items: Some(tuple_item_schemas),
min_items: Some(tuple_len),
max_items: Some(tuple_len),
items: None, // Do not use prefixItems and items together
..Schema::new(SchemaType::Array)
};
let mut properties = BTreeMap::new();
properties.insert(
variant_key.clone(),
SchemaRef::Inline(Box::new(array_schema)),
);
Schema {
properties: Some(properties),
required: Some(vec![variant_key]),
..Schema::object()
}
}
}
syn::Fields::Named(fields_named) => {
// Struct variant: {"VariantName": {field1: type1, field2: type2, ...}}
let mut variant_properties = BTreeMap::new();
let mut variant_required = Vec::new();
let variant_rename_all = extract_rename_all(&variant.attrs);
for field in &fields_named.named {
let rust_field_name = field
.ident
.as_ref()
.map(|i| strip_raw_prefix(&i.to_string()).to_string())
.unwrap_or_else(|| "unknown".to_string());
// Check for field-level rename attribute first (takes precedence)
let field_name = if let Some(renamed) = extract_field_rename(&field.attrs) {
renamed
} else {
// Apply rename_all transformation if present
rename_field(
&rust_field_name,
variant_rename_all.as_deref().or(rename_all.as_deref()),
)
};
let field_type = &field.ty;
let schema_ref =
parse_type_to_schema_ref(field_type, known_schemas, struct_definitions);
variant_properties.insert(field_name.clone(), schema_ref);
// Check if field is Option<T>
let is_optional = matches!(
field_type,
Type::Path(type_path)
if type_path
.path
.segments
.first()
.map(|s| s.ident == "Option")
.unwrap_or(false)
);
if !is_optional {
variant_required.push(field_name);
}
}
// Wrap struct variant in an object with the variant name as key
let inner_struct_schema = Schema {
properties: if variant_properties.is_empty() {
None
} else {
Some(variant_properties)
},
required: if variant_required.is_empty() {
None
} else {
Some(variant_required)
},
..Schema::object()
};
let mut properties = BTreeMap::new();
properties.insert(
variant_key.clone(),
SchemaRef::Inline(Box::new(inner_struct_schema)),
);
Schema {
properties: Some(properties),
required: Some(vec![variant_key]),
..Schema::object()
}
}
};
one_of_schemas.push(SchemaRef::Inline(Box::new(variant_schema)));
}
Schema {
schema_type: None, // oneOf doesn't have a single type
one_of: if one_of_schemas.is_empty() {
None
} else {
Some(one_of_schemas)
},
..Schema::new(SchemaType::Object)
}
}
}
pub fn parse_struct_to_schema(
struct_item: &syn::ItemStruct,
known_schemas: &HashMap<String, String>,
struct_definitions: &HashMap<String, String>,
) -> Schema {
let mut properties = BTreeMap::new();
let mut required = Vec::new();
// Extract rename_all attribute from struct
let rename_all = extract_rename_all(&struct_item.attrs);
match &struct_item.fields {
Fields::Named(fields_named) => {
for field in &fields_named.named {
// Check if field should be skipped
if extract_skip(&field.attrs) {
continue;
}
let rust_field_name = field
.ident
.as_ref()
.map(|i| strip_raw_prefix(&i.to_string()).to_string())
.unwrap_or_else(|| "unknown".to_string());
// Check for field-level rename attribute first (takes precedence)
let field_name = if let Some(renamed) = extract_field_rename(&field.attrs) {
renamed
} else {
// Apply rename_all transformation if present
rename_field(&rust_field_name, rename_all.as_deref())
};
let field_type = &field.ty;
let mut schema_ref =
parse_type_to_schema_ref(field_type, known_schemas, struct_definitions);
// Check for default attribute
let has_default = extract_default(&field.attrs).is_some();
// Check for skip_serializing_if attribute
let has_skip_serializing_if = extract_skip_serializing_if(&field.attrs);
// If default or skip_serializing_if is present, mark field as optional (not required)
// and set default value if it's a simple default (not a function)
if has_default || has_skip_serializing_if {
// For default = "function_name", we'll handle it in openapi_generator
// For now, just mark as optional
if let SchemaRef::Inline(ref mut _schema) = schema_ref {
// Default will be set later in openapi_generator if it's a function
// For simple default, we could set it here, but serde handles it
}
} else {
// Check if field is Option<T>
let is_optional = matches!(
field_type,
Type::Path(type_path)
if type_path
.path
.segments
.first()
.map(|s| s.ident == "Option")
.unwrap_or(false)
);
if !is_optional {
required.push(field_name.clone());
}
}
properties.insert(field_name, schema_ref);
}
}
Fields::Unnamed(_) => {
// Tuple structs are not supported for now
}
Fields::Unit => {
// Unit structs have no fields
}
}
Schema {
schema_type: Some(SchemaType::Object),
properties: if properties.is_empty() {
None
} else {
Some(properties)
},
required: if required.is_empty() {
None
} else {
Some(required)
},
..Schema::object()
}
}
fn substitute_type(ty: &Type, generic_params: &[String], concrete_types: &[&Type]) -> Type {
match ty {
Type::Path(type_path) => {
let path = &type_path.path;
if path.segments.is_empty() {
return ty.clone();
}
// Check if this is a direct generic parameter (e.g., just "T" with no arguments)
if path.segments.len() == 1 {
let segment = &path.segments[0];
let ident_str = segment.ident.to_string();
if let syn::PathArguments::None = &segment.arguments {
// Direct generic parameter substitution
if let Some(index) = generic_params.iter().position(|p| p == &ident_str)
&& let Some(concrete_ty) = concrete_types.get(index) {
return (*concrete_ty).clone();
}
}
}
// For types with generic arguments (e.g., Vec<T>, Option<T>, HashMap<K, V>),
// recursively substitute the type arguments
let mut new_segments = syn::punctuated::Punctuated::new();
for segment in &path.segments {
let new_arguments = match &segment.arguments {
syn::PathArguments::AngleBracketed(args) => {
let mut new_args = syn::punctuated::Punctuated::new();
for arg in &args.args {
let new_arg = match arg {
syn::GenericArgument::Type(inner_ty) => syn::GenericArgument::Type(
substitute_type(inner_ty, generic_params, concrete_types),
),
other => other.clone(),
};
new_args.push(new_arg);
}
syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
colon2_token: args.colon2_token,
lt_token: args.lt_token,
args: new_args,
gt_token: args.gt_token,
})
}
other => other.clone(),
};
new_segments.push(syn::PathSegment {
ident: segment.ident.clone(),
arguments: new_arguments,
});
}
Type::Path(syn::TypePath {
qself: type_path.qself.clone(),
path: syn::Path {
leading_colon: path.leading_colon,
segments: new_segments,
},
})
}
Type::Reference(type_ref) => {
// Handle &T, &mut T
Type::Reference(syn::TypeReference {
and_token: type_ref.and_token,
lifetime: type_ref.lifetime.clone(),
mutability: type_ref.mutability,
elem: Box::new(substitute_type(
&type_ref.elem,
generic_params,
concrete_types,
)),
})
}
Type::Slice(type_slice) => {
// Handle [T]
Type::Slice(syn::TypeSlice {
bracket_token: type_slice.bracket_token,
elem: Box::new(substitute_type(
&type_slice.elem,
generic_params,
concrete_types,
)),
})
}
Type::Array(type_array) => {
// Handle [T; N]
Type::Array(syn::TypeArray {
bracket_token: type_array.bracket_token,
elem: Box::new(substitute_type(
&type_array.elem,
generic_params,
concrete_types,
)),
semi_token: type_array.semi_token,
len: type_array.len.clone(),
})
}
Type::Tuple(type_tuple) => {
// Handle (T1, T2, ...)
let new_elems = type_tuple
.elems
.iter()
.map(|elem| substitute_type(elem, generic_params, concrete_types))
.collect();
Type::Tuple(syn::TypeTuple {
paren_token: type_tuple.paren_token,
elems: new_elems,
})
}
_ => ty.clone(),
}
}
pub(super) fn is_primitive_type(ty: &Type) -> bool {
match ty {
Type::Path(type_path) => {
let path = &type_path.path;
if path.segments.len() == 1 {
let ident = path.segments[0].ident.to_string();
matches!(
ident.as_str(),
"i8" | "i16"
| "i32"
| "i64"
| "u8"
| "u16"
| "u32"
| "u64"
| "f32"
| "f64"
| "bool"
| "String"
| "str"
)
} else {
false
}
}
_ => false,
}
}
pub fn parse_type_to_schema_ref(
ty: &Type,
known_schemas: &HashMap<String, String>,
struct_definitions: &HashMap<String, String>,
) -> SchemaRef {
parse_type_to_schema_ref_with_schemas(ty, known_schemas, struct_definitions)
}
pub(super) fn parse_type_to_schema_ref_with_schemas(
ty: &Type,
known_schemas: &HashMap<String, String>,
struct_definitions: &HashMap<String, String>,
) -> SchemaRef {
match ty {
Type::Path(type_path) => {
let path = &type_path.path;
if path.segments.is_empty() {
return SchemaRef::Inline(Box::new(Schema::new(SchemaType::Object)));
}
// Get the last segment as the type name (handles paths like crate::TestStruct)
let segment = path.segments.last().unwrap();
let ident_str = segment.ident.to_string();
// Handle generic types
if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
match ident_str.as_str() {
"Vec" | "Option" => {
if let Some(syn::GenericArgument::Type(inner_ty)) = args.args.first() {
let inner_schema = parse_type_to_schema_ref(
inner_ty,
known_schemas,
struct_definitions,
);
if ident_str == "Vec" {
return SchemaRef::Inline(Box::new(Schema::array(inner_schema)));
} else {
// Option<T> -> nullable schema
match inner_schema {
SchemaRef::Inline(mut schema) => {
schema.nullable = Some(true);
return SchemaRef::Inline(schema);
}
SchemaRef::Ref(reference) => {
// Wrap reference in an inline schema to attach nullable flag
return SchemaRef::Inline(Box::new(Schema {
ref_path: Some(reference.ref_path),
schema_type: None,
nullable: Some(true),
..Schema::new(SchemaType::Object)
}));
}
}
}
}
}
"HashMap" | "BTreeMap" => {
// HashMap<K, V> or BTreeMap<K, V> -> object with additionalProperties
// K is typically String, we use V as the value type
if args.args.len() >= 2
&& let (
Some(syn::GenericArgument::Type(_key_ty)),
Some(syn::GenericArgument::Type(value_ty)),
) = (args.args.get(0), args.args.get(1))
{
let value_schema = parse_type_to_schema_ref(
value_ty,
known_schemas,
struct_definitions,
);
// Convert SchemaRef to serde_json::Value for additional_properties
let additional_props_value = match value_schema {
SchemaRef::Ref(ref_ref) => {
serde_json::json!({ "$ref": ref_ref.ref_path })
}
SchemaRef::Inline(schema) => {
serde_json::to_value(&*schema).unwrap_or(serde_json::json!({}))
}
};
return SchemaRef::Inline(Box::new(Schema {
schema_type: Some(SchemaType::Object),
additional_properties: Some(additional_props_value),
..Schema::object()
}));
}
}
_ => {}
}
}
// Handle primitive types
match ident_str.as_str() {
"i8" | "i16" | "i32" | "i64" | "u8" | "u16" | "u32" | "u64" => {
SchemaRef::Inline(Box::new(Schema::integer()))
}
"f32" | "f64" => SchemaRef::Inline(Box::new(Schema::number())),
"bool" => SchemaRef::Inline(Box::new(Schema::boolean())),
"String" | "str" => SchemaRef::Inline(Box::new(Schema::string())),
// Date-time types from chrono crate
"DateTime" | "NaiveDateTime" => SchemaRef::Inline(Box::new(Schema {
format: Some("date-time".to_string()),
..Schema::string()
})),
"NaiveDate" => SchemaRef::Inline(Box::new(Schema {
format: Some("date".to_string()),
..Schema::string()
})),
"NaiveTime" => SchemaRef::Inline(Box::new(Schema {
format: Some("time".to_string()),
..Schema::string()
})),
// Date-time types from time crate
"OffsetDateTime" | "PrimitiveDateTime" => SchemaRef::Inline(Box::new(Schema {
format: Some("date-time".to_string()),
..Schema::string()
})),
"Date" => SchemaRef::Inline(Box::new(Schema {
format: Some("date".to_string()),
..Schema::string()
})),
"Time" => SchemaRef::Inline(Box::new(Schema {
format: Some("time".to_string()),
..Schema::string()
})),
// Duration types
"Duration" => SchemaRef::Inline(Box::new(Schema {
format: Some("duration".to_string()),
..Schema::string()
})),
// Standard library types that should not be referenced
// Note: HashMap and BTreeMap are handled above in generic types
"Vec" | "Option" | "Result" | "Json" | "Path" | "Query" | "Header" => {
// These are not schema types, return object schema
SchemaRef::Inline(Box::new(Schema::new(SchemaType::Object)))
}
_ => {
// Check if this is a known schema (struct with Schema derive)
// Use just the type name (handles both crate::TestStruct and TestStruct)
let type_name = ident_str.clone();
if known_schemas.contains_key(&type_name) {
// Check if this is a generic type with type parameters
if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
// This is a concrete generic type like GenericStruct<String>
// Inline the schema by substituting generic parameters with concrete types
if let Some(base_def) = struct_definitions.get(&type_name)
&& let Ok(mut parsed) = syn::parse_str::<syn::ItemStruct>(base_def)
{
// Extract generic parameter names from the struct definition
let generic_params: Vec<String> = parsed
.generics
.params
.iter()
.filter_map(|param| {
if let syn::GenericParam::Type(type_param) = param {
Some(type_param.ident.to_string())