-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathanalysis.rs
More file actions
3810 lines (3467 loc) · 158 KB
/
Copy pathanalysis.rs
File metadata and controls
3810 lines (3467 loc) · 158 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 crate::openapi::{Discriminator, OpenApiSpec, Schema, SchemaType as OpenApiSchemaType};
use crate::{GeneratorError, Result};
use serde_json::Value;
use std::collections::{BTreeMap, HashSet};
use std::path::Path;
#[derive(Debug, Clone)]
pub struct SchemaAnalysis {
/// All schemas indexed by name
pub schemas: BTreeMap<String, AnalyzedSchema>,
/// Dependency graph for generation ordering
pub dependencies: DependencyGraph,
/// Detected patterns and transformations
pub patterns: DetectedPatterns,
/// OpenAPI operations and their request/response schemas
pub operations: BTreeMap<String, OperationInfo>,
}
#[derive(Debug, Clone)]
pub struct AnalyzedSchema {
pub name: String,
pub original: Value,
pub schema_type: SchemaType,
pub dependencies: HashSet<String>,
pub nullable: bool,
pub description: Option<String>,
pub default: Option<serde_json::Value>,
}
#[derive(Debug, Clone)]
pub enum SchemaType {
/// Simple primitive type
Primitive { rust_type: String },
/// Object with properties
Object {
properties: BTreeMap<String, PropertyInfo>,
required: HashSet<String>,
additional_properties: bool,
},
/// Discriminated union (oneOf + discriminator)
DiscriminatedUnion {
discriminator_field: String,
variants: Vec<UnionVariant>,
},
/// Simple union (anyOf without discriminator)
Union { variants: Vec<SchemaRef> },
/// Array type
Array { item_type: Box<SchemaType> },
/// String enum
StringEnum { values: Vec<String> },
/// Extensible enum with known values and custom variant
ExtensibleEnum { known_values: Vec<String> },
/// Schema composition (allOf)
Composition { schemas: Vec<SchemaRef> },
/// Reference to another schema
Reference { target: String },
}
#[derive(Debug, Clone)]
pub struct PropertyInfo {
pub schema_type: SchemaType,
pub nullable: bool,
pub description: Option<String>,
pub default: Option<serde_json::Value>,
pub serde_attrs: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct UnionVariant {
pub rust_name: String,
pub type_name: String,
pub discriminator_value: String,
pub schema_ref: String,
}
#[derive(Debug, Clone)]
pub struct SchemaRef {
pub target: String,
pub nullable: bool,
}
#[derive(Debug, Clone)]
pub struct DependencyGraph {
pub edges: BTreeMap<String, HashSet<String>>,
/// Set of schemas that have recursive dependencies
pub recursive_schemas: HashSet<String>,
}
#[derive(Debug, Clone)]
pub struct DetectedPatterns {
/// Schemas that should use tagged enums (discriminated unions)
pub tagged_enum_schemas: HashSet<String>,
/// Schemas that should use untagged enums (simple unions)
pub untagged_enum_schemas: HashSet<String>,
/// Auto-detected type mappings for discriminated unions
pub type_mappings: BTreeMap<String, BTreeMap<String, String>>,
}
/// Information about an OpenAPI operation
#[derive(Debug, Clone, serde::Serialize)]
pub struct OperationInfo {
/// Operation ID
pub operation_id: String,
/// HTTP method (GET, POST, etc.)
pub method: String,
/// Path template
pub path: String,
/// Short summary from OpenAPI spec
pub summary: Option<String>,
/// Longer description from OpenAPI spec
pub description: Option<String>,
/// Request body content type and schema (if any)
pub request_body: Option<RequestBodyContent>,
/// Response schemas by status code
pub response_schemas: BTreeMap<String, String>,
/// Parameters (path, query, header)
pub parameters: Vec<ParameterInfo>,
/// Whether this operation supports streaming
pub supports_streaming: bool,
/// Stream parameter name if applicable
pub stream_parameter: Option<String>,
}
/// Content type and schema for a request body
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "kind")]
pub enum RequestBodyContent {
Json { schema_name: String },
FormUrlEncoded { schema_name: String },
Multipart,
OctetStream,
TextPlain,
}
impl RequestBodyContent {
/// Get the schema name if this content type has one
pub fn schema_name(&self) -> Option<&str> {
match self {
Self::Json { schema_name } | Self::FormUrlEncoded { schema_name } => Some(schema_name),
_ => None,
}
}
}
/// Information about an operation parameter
#[derive(Debug, Clone, serde::Serialize)]
pub struct ParameterInfo {
/// Parameter name
pub name: String,
/// Parameter location (path, query, header, cookie)
pub location: String,
/// Whether the parameter is required
pub required: bool,
/// Schema reference for the parameter type
pub schema_ref: Option<String>,
/// Rust type for this parameter
pub rust_type: String,
/// Description from OpenAPI spec
pub description: Option<String>,
/// String enum values when the parameter's inline schema is a string with
/// `enum` or `const`. When set, `rust_type` is the synthetic enum type
/// name (e.g. `GetItemTheConstant`) and the client generator emits an
/// inline enum so the parameter is constrained to the declared values.
/// See issue #10 follow-up.
#[serde(skip_serializing_if = "Option::is_none")]
pub enum_values: Option<Vec<String>>,
}
impl Default for DependencyGraph {
fn default() -> Self {
Self::new()
}
}
impl DependencyGraph {
pub fn new() -> Self {
Self {
edges: BTreeMap::new(),
recursive_schemas: HashSet::new(),
}
}
pub fn add_dependency(&mut self, from: String, to: String) {
self.edges.entry(from).or_default().insert(to);
}
/// Get topological sort order for generation
pub fn topological_sort(&mut self) -> Result<Vec<String>> {
// First, detect and handle recursive dependencies
self.detect_recursive_schemas();
// Create a temporary graph without self-referencing edges for sorting
let mut temp_edges = self.edges.clone();
for (schema, deps) in &mut temp_edges {
deps.remove(schema); // Remove self-references
}
let mut visited = HashSet::new();
let mut temp_visited = HashSet::new();
let mut result = Vec::new();
// Visit all nodes using the temporary graph in sorted order for deterministic output
let mut all_nodes: Vec<_> = temp_edges.keys().collect();
all_nodes.sort();
for node in all_nodes {
if !visited.contains(node) {
self.visit_node_recursive(
node,
&temp_edges,
&mut visited,
&mut temp_visited,
&mut result,
)?;
}
}
result.reverse();
Ok(result)
}
fn detect_recursive_schemas(&mut self) {
for (schema, deps) in &self.edges {
if deps.contains(schema) {
// Direct self-reference
self.recursive_schemas.insert(schema.clone());
} else {
// Check for indirect cycles
if self.has_cycle_from(schema, schema, &mut HashSet::new()) {
self.recursive_schemas.insert(schema.clone());
}
}
}
// Also detect mutual recursion (like GraphNode <-> GraphEdge)
for (schema, deps) in &self.edges {
for dep in deps {
if let Some(dep_deps) = self.edges.get(dep) {
if dep_deps.contains(schema) {
// Mutual recursion detected
self.recursive_schemas.insert(schema.clone());
self.recursive_schemas.insert(dep.clone());
}
}
}
}
}
fn has_cycle_from(&self, start: &str, current: &str, visited: &mut HashSet<String>) -> bool {
if visited.contains(current) {
return false; // Already checked this path
}
visited.insert(current.to_string());
if let Some(deps) = self.edges.get(current) {
for dep in deps {
if dep == start {
return true; // Found cycle back to start
}
if self.has_cycle_from(start, dep, visited) {
return true;
}
}
}
false
}
#[allow(clippy::only_used_in_recursion)]
fn visit_node_recursive(
&self,
node: &str,
temp_edges: &BTreeMap<String, HashSet<String>>,
visited: &mut HashSet<String>,
temp_visited: &mut HashSet<String>,
result: &mut Vec<String>,
) -> Result<()> {
if temp_visited.contains(node) {
// This should not happen with cycle-free temp graph, but just in case
return Ok(());
}
if visited.contains(node) {
return Ok(());
}
temp_visited.insert(node.to_string());
if let Some(dependencies) = temp_edges.get(node) {
// Sort dependencies for deterministic topological order
let mut sorted_deps: Vec<_> = dependencies.iter().collect();
sorted_deps.sort();
for dep in sorted_deps {
self.visit_node_recursive(dep, temp_edges, visited, temp_visited, result)?;
}
}
temp_visited.remove(node);
visited.insert(node.to_string());
result.push(node.to_string());
Ok(())
}
}
/// Merge schema extension files into the main OpenAPI specification
/// Uses simple recursive JSON object merging
pub fn merge_schema_extensions(
main_spec: Value,
extension_paths: &[impl AsRef<Path>],
) -> Result<Value> {
let mut result = main_spec;
for path in extension_paths {
let extension = load_extension_file(path.as_ref())?;
result = merge_json_objects_with_replacements(result, extension)?;
}
Ok(result)
}
/// Load an extension file and parse as JSON
fn load_extension_file(path: &Path) -> Result<Value> {
let content = std::fs::read_to_string(path).map_err(|e| GeneratorError::FileError {
message: format!("Failed to read file {}: {}", path.display(), e),
})?;
serde_json::from_str(&content).map_err(GeneratorError::ParseError)
}
/// Merge JSON objects with explicit replacement support
fn merge_json_objects_with_replacements(main: Value, extension: Value) -> Result<Value> {
// Extract replacement rules from the extension
let replacements = extract_replacement_rules(&extension);
// Perform the merge with replacement awareness
Ok(merge_json_objects_with_rules(
main,
extension,
&replacements,
))
}
/// Extract x-replacements rules from extension
fn extract_replacement_rules(
extension: &Value,
) -> std::collections::HashMap<String, (String, String)> {
let mut rules = std::collections::HashMap::new();
if let Some(x_replacements) = extension.get("x-replacements") {
if let Some(x_replacements_obj) = x_replacements.as_object() {
for (schema_name, replacement_rule) in x_replacements_obj {
if let Some(rule_obj) = replacement_rule.as_object() {
if let (Some(replace), Some(with)) = (
rule_obj.get("replace").and_then(|v| v.as_str()),
rule_obj.get("with").and_then(|v| v.as_str()),
) {
rules.insert(schema_name.clone(), (replace.to_string(), with.to_string()));
// println!("📋 Replacement rule: In {}, replace {} with {}", schema_name, replace, with);
}
}
}
}
}
rules
}
/// Check if a variant should be replaced based on explicit replacement rules
fn should_replace_variant(
schema_name: &str,
extension_refs: &[String],
replacements: &std::collections::HashMap<String, (String, String)>,
) -> bool {
// Check all replacement rules
for (replace_schema, with_schema) in replacements.values() {
if schema_name == replace_schema {
// This schema should be replaced - check if the replacement schema is in extensions
let replacement_exists = extension_refs.iter().any(|ext_ref| {
let ext_schema_name = ext_ref.split('/').next_back().unwrap_or("");
ext_schema_name == with_schema
});
if replacement_exists {
return true;
}
}
}
// Fallback to exact name match for complete replacement
extension_refs.iter().any(|ext_ref| {
let ext_schema_name = ext_ref.split('/').next_back().unwrap_or("");
schema_name == ext_schema_name
})
}
/// Recursively merge two JSON values with replacement rules
/// Objects are merged by combining properties
/// Arrays are merged by concatenating
/// Primitives in the extension override the main value
fn merge_json_objects_with_rules(
main: Value,
extension: Value,
replacements: &std::collections::HashMap<String, (String, String)>,
) -> Value {
match (main, extension) {
// Both objects - merge properties
(Value::Object(mut main_obj), Value::Object(ext_obj)) => {
// Special handling for schema objects with oneOf/anyOf variants.
// Detect which keyword the MAIN spec uses so we preserve it after merging.
let main_union_keyword = if main_obj.contains_key("oneOf") {
Some("oneOf")
} else if main_obj.contains_key("anyOf") {
Some("anyOf")
} else {
None
};
if let (Some(main_variants), Some(ext_variants)) = (
extract_schema_variants(&Value::Object(main_obj.clone())),
extract_schema_variants(&Value::Object(ext_obj.clone())),
) {
let union_key = main_union_keyword.unwrap_or("oneOf");
println!(
"🔍 Merging union schemas ({union_key}): {} main variants, {} extension variants",
main_variants.len(),
ext_variants.len()
);
// Merge the variant arrays, preserving the original union keyword
// First, collect main variants, but filter out any that will be replaced by extension
let mut merged_variants = Vec::new();
let extension_refs: Vec<String> = ext_variants
.iter()
.filter_map(|v| v.get("$ref").and_then(|r| r.as_str()))
.map(|s| s.to_string())
.collect();
// Add main variants that aren't being replaced
for main_variant in main_variants {
if let Some(main_ref) = main_variant.get("$ref").and_then(|r| r.as_str()) {
// Check if this main variant should be replaced by an extension variant
let schema_name = main_ref.split('/').next_back().unwrap_or("");
let should_replace =
should_replace_variant(schema_name, &extension_refs, replacements);
if should_replace {
println!("🔄 REPLACING {} (explicit rule)", schema_name);
}
if !should_replace {
merged_variants.push(main_variant);
}
} else {
// Keep non-ref variants
merged_variants.push(main_variant);
}
}
// Add all extension variants
for ext_variant in ext_variants {
merged_variants.push(ext_variant);
}
// Remove old oneOf/anyOf keys and add merged variants under the original keyword
main_obj.remove("oneOf");
main_obj.remove("anyOf");
main_obj.insert(union_key.to_string(), Value::Array(merged_variants));
// Merge other properties normally
for (key, ext_value) in ext_obj {
if key != "oneOf" && key != "anyOf" {
match main_obj.get(&key) {
Some(main_value) => {
let merged_value = merge_json_objects_with_rules(
main_value.clone(),
ext_value,
replacements,
);
main_obj.insert(key, merged_value);
}
None => {
main_obj.insert(key, ext_value);
}
}
}
}
return Value::Object(main_obj);
}
// Normal object merging
for (key, ext_value) in ext_obj {
match main_obj.get(&key) {
Some(main_value) => {
// Key exists in both - recursively merge
let merged_value = merge_json_objects_with_rules(
main_value.clone(),
ext_value,
replacements,
);
main_obj.insert(key, merged_value);
}
None => {
// Key only in extension - add it
main_obj.insert(key, ext_value);
}
}
}
Value::Object(main_obj)
}
// Both arrays - concatenate
(Value::Array(mut main_arr), Value::Array(ext_arr)) => {
main_arr.extend(ext_arr);
Value::Array(main_arr)
}
// Extension overrides main for all other cases
(_, extension) => extension,
}
}
/// Extract schema variants from oneOf or anyOf properties
fn extract_schema_variants(obj: &Value) -> Option<Vec<Value>> {
if let Value::Object(map) = obj {
if let Some(Value::Array(variants)) = map.get("oneOf") {
return Some(variants.clone());
}
if let Some(Value::Array(variants)) = map.get("anyOf") {
return Some(variants.clone());
}
}
None
}
pub struct SchemaAnalyzer {
schemas: BTreeMap<String, Schema>,
resolved_cache: BTreeMap<String, AnalyzedSchema>,
openapi_spec: Value,
current_schema_name: Option<String>,
component_parameters: BTreeMap<String, crate::openapi::Parameter>,
}
impl SchemaAnalyzer {
pub fn new(openapi_spec: Value) -> Result<Self> {
let spec: OpenApiSpec =
serde_json::from_value(openapi_spec.clone()).map_err(GeneratorError::ParseError)?;
let schemas = Self::extract_schemas(&spec)?;
let component_parameters = spec
.components
.as_ref()
.and_then(|c| c.parameters.as_ref())
.cloned()
.unwrap_or_default();
Ok(Self {
schemas,
resolved_cache: BTreeMap::new(),
openapi_spec,
current_schema_name: None,
component_parameters,
})
}
/// Create a new analyzer with schema extensions merged in
pub fn new_with_extensions(
openapi_spec: Value,
extension_paths: &[std::path::PathBuf],
) -> Result<Self> {
let merged_spec = merge_schema_extensions(openapi_spec, extension_paths)?;
Self::new(merged_spec)
}
/// Generate a context-aware name for inline types, arrays, and variants
/// This provides better naming than generic names like UnionArray1, InlineVariant2, etc.
fn generate_context_aware_name(
&self,
base_context: &str,
type_hint: &str,
index: usize,
schema: Option<&Schema>,
) -> String {
// First, try to infer a better name from the schema structure
if let Some(schema) = schema {
// For arrays, check if we can derive name from items
if type_hint == "Array"
&& matches!(schema.schema_type(), Some(OpenApiSchemaType::Array))
{
if let Some(items_schema) = &schema.details().items {
// Check for specific item types
if let Some(item_type) = items_schema.schema_type() {
match item_type {
OpenApiSchemaType::Object => {
return format!("{base_context}ItemArray");
}
OpenApiSchemaType::String => {
return format!("{base_context}StringArray");
}
_ => {}
}
}
}
}
}
// Generate context-aware name based on type hint
match type_hint {
"Array" => {
// For arrays, always use context name instead of generic numbering
format!("{base_context}Array")
}
"Variant" | "InlineVariant" => {
// For variants, include index only if > 0 to keep first variant clean
if index == 0 {
format!("{base_context}{type_hint}")
} else {
format!("{}{}{}", base_context, type_hint, index + 1)
}
}
_ => {
// Default case
format!("{base_context}{type_hint}{index}")
}
}
}
/// Convert a string to PascalCase, handling underscores and hyphens
fn to_pascal_case(&self, s: &str) -> String {
s.split(['_', '-'])
.filter(|part| !part.is_empty())
.map(|part| {
let mut chars = part.chars();
match chars.next() {
None => String::new(),
Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
}
})
.collect()
}
fn extract_schemas(spec: &OpenApiSpec) -> Result<BTreeMap<String, Schema>> {
let schemas = spec
.components
.as_ref()
.and_then(|c| c.schemas.as_ref())
.ok_or_else(|| {
GeneratorError::InvalidSchema("No schemas found in OpenAPI spec".to_string())
})?;
// Convert BTreeMap to BTreeMap for deterministic iteration order
Ok(schemas
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect())
}
pub fn analyze(&mut self) -> Result<SchemaAnalysis> {
let mut analysis = SchemaAnalysis {
schemas: BTreeMap::new(),
dependencies: DependencyGraph::new(),
patterns: DetectedPatterns {
tagged_enum_schemas: HashSet::new(),
untagged_enum_schemas: HashSet::new(),
type_mappings: BTreeMap::new(),
},
operations: BTreeMap::new(),
};
// First pass: detect patterns
self.detect_patterns(&mut analysis.patterns)?;
// Second pass: analyze each schema
let schema_names: Vec<String> = self.schemas.keys().cloned().collect();
for schema_name in schema_names {
let analyzed = self.analyze_schema(&schema_name)?;
// Build dependency graph
for dep in &analyzed.dependencies {
analysis
.dependencies
.add_dependency(schema_name.clone(), dep.clone());
}
analysis.schemas.insert(schema_name, analyzed);
}
// Third pass: include any inline schemas that were generated during analysis
// BTreeMap maintains sorted order, so iteration is deterministic
for (inline_name, inline_schema) in &self.resolved_cache {
if !analysis.schemas.contains_key(inline_name) {
// Add the inline schema first
analysis
.schemas
.insert(inline_name.clone(), inline_schema.clone());
// Build dependency graph for inline schema's own dependencies
for dep in &inline_schema.dependencies {
analysis
.dependencies
.add_dependency(inline_name.clone(), dep.clone());
}
// Check if any existing schemas depend on this inline schema
// We need to check ALL schemas, not just the ones already in analysis.schemas,
// because parent schemas might have been analyzed but their dependencies
// on inline schemas might not have been added to the dependency graph yet
let mut schemas_to_update = Vec::new();
for (schema_name, schema) in &analysis.schemas {
// Skip self-reference
if schema_name == inline_name {
continue;
}
if schema.dependencies.contains(inline_name) {
// The parent schema depends on this inline schema
schemas_to_update.push(schema_name.clone());
}
}
// Add the dependencies to the graph
for schema_name in schemas_to_update {
analysis
.dependencies
.add_dependency(schema_name, inline_name.clone());
}
}
}
// Fourth pass: analyze OpenAPI operations
self.analyze_operations(&mut analysis)?;
// Fifth pass: include any inline schemas generated during operation analysis
// (e.g., inline response types)
for (inline_name, inline_schema) in &self.resolved_cache {
if !analysis.schemas.contains_key(inline_name) {
analysis
.schemas
.insert(inline_name.clone(), inline_schema.clone());
// Build dependency graph for inline schema's dependencies
for dep in &inline_schema.dependencies {
analysis
.dependencies
.add_dependency(inline_name.clone(), dep.clone());
}
}
}
Ok(analysis)
}
fn detect_patterns(&self, patterns: &mut DetectedPatterns) -> Result<()> {
for (schema_name, schema) in &self.schemas {
// Detect discriminated unions
if self.is_discriminated_union(schema) {
patterns.tagged_enum_schemas.insert(schema_name.clone());
// Extract type mappings for this union
if let Some(mappings) = self.extract_type_mappings(schema)? {
patterns.type_mappings.insert(schema_name.clone(), mappings);
}
}
// Detect simple unions
else if self.is_simple_union(schema) {
patterns.untagged_enum_schemas.insert(schema_name.clone());
}
}
Ok(())
}
fn is_discriminated_union(&self, schema: &Schema) -> bool {
// Check for explicit discriminator
if schema.is_discriminated_union() {
return true;
}
// Auto-detect from union patterns with any common const field
if let Some(variants) = schema.union_variants() {
return variants.len() > 2 && self.detect_discriminator_field(variants).is_some();
}
false
}
fn all_variants_have_const_field(&self, variants: &[Schema], field_name: &str) -> bool {
variants.iter().all(|variant| {
if let Some(ref_str) = variant.reference() {
// $ref variant: resolve and check the referenced schema
if let Some(schema_name) = self.extract_schema_name(ref_str) {
if let Some(schema) = self.schemas.get(schema_name) {
return self.has_const_discriminator_field(schema, field_name);
}
}
} else {
// Inline variant: check properties directly
return self.has_const_discriminator_field(variant, field_name);
}
false
})
}
/// Scan all variants to find any common property that has a const/single-enum value
/// across all variants. Returns the field name if found.
/// Prioritizes "type" if it matches (most common convention).
fn detect_discriminator_field(&self, variants: &[Schema]) -> Option<String> {
if variants.is_empty() {
return None;
}
// Collect candidate field names from the first variant
let first_variant = &variants[0];
let first_schema = if let Some(ref_str) = first_variant.reference() {
let schema_name = self.extract_schema_name(ref_str)?;
self.schemas.get(schema_name)?
} else {
first_variant
};
let properties = first_schema.details().properties.as_ref()?;
let mut candidates: Vec<String> = Vec::new();
for (field_name, field_schema) in properties {
let details = field_schema.details();
let is_const = details.const_value.is_some()
|| details.enum_values.as_ref().is_some_and(|v| v.len() == 1)
|| details.extra.contains_key("const");
if is_const {
candidates.push(field_name.clone());
}
}
if candidates.is_empty() {
return None;
}
// Prioritize "type" if it's among candidates
candidates.sort_by(|a, b| {
if a == "type" {
std::cmp::Ordering::Less
} else if b == "type" {
std::cmp::Ordering::Greater
} else {
a.cmp(b)
}
});
// Check each candidate against all variants
for candidate in &candidates {
if self.all_variants_have_const_field(variants, candidate) {
return Some(candidate.clone());
}
}
None
}
fn has_const_discriminator_field(&self, schema: &Schema, field_name: &str) -> bool {
if let Some(properties) = &schema.details().properties {
if let Some(field) = properties.get(field_name) {
// Check for const value (OpenAPI 3.1 style)
if field.details().const_value.is_some() {
return true;
}
// Check if it's an enum field with a single value
if let Some(enum_vals) = &field.details().enum_values {
return enum_vals.len() == 1;
}
// Fallback: check extra fields for const
return field.details().extra.contains_key("const");
}
}
false
}
fn is_simple_union(&self, schema: &Schema) -> bool {
if let Some(variants) = schema.union_variants() {
// Simple union: multiple types but not nullable pattern
if variants.len() > 1 && !schema.is_nullable_pattern() {
let has_refs = variants.iter().any(|v| v.is_reference());
return has_refs;
}
}
false
}
fn extract_type_mappings(&self, schema: &Schema) -> Result<Option<BTreeMap<String, String>>> {
let variants = schema.union_variants().ok_or_else(|| {
GeneratorError::InvalidSchema("No variants found for discriminated union".to_string())
})?;
// Get the discriminator field name from the schema
let discriminator_field = if let Some(discriminator) = schema.discriminator() {
discriminator.property_name.clone()
} else if let Some(detected) = self.detect_discriminator_field(variants) {
detected
} else {
"type".to_string() // fallback to "type" for auto-detected discriminated unions
};
let mut mappings = BTreeMap::new();
for variant in variants {
if let Some(ref_str) = variant.reference() {
if let Some(type_name) = self.extract_schema_name(ref_str) {
if let Some(variant_schema) = self.schemas.get(type_name) {
if let Some(discriminator_value) = self
.extract_discriminator_value_for_field(
variant_schema,
&discriminator_field,
)
{
mappings.insert(type_name.to_string(), discriminator_value);
}
}
}
}
}
if mappings.is_empty() {
Ok(None)
} else {
Ok(Some(mappings))
}
}
#[allow(dead_code)]
fn extract_discriminator_value(&self, schema: &Schema) -> Option<String> {
self.extract_discriminator_value_for_field(schema, "type")
}
fn extract_discriminator_value_for_field(
&self,
schema: &Schema,
field_name: &str,
) -> Option<String> {
if let Some(properties) = &schema.details().properties {
if let Some(type_field) = properties.get(field_name) {
// Check for const value first (highest priority)
if let Some(const_value) = &type_field.details().const_value {
if let Some(value) = const_value.as_str() {
return Some(value.to_string());
}
}
// Check for enum with single value
if let Some(enum_values) = &type_field.details().enum_values {
if enum_values.len() == 1 {
return enum_values[0].as_str().map(|s| s.to_string());
}
}
// Check for const value in extra fields
if let Some(const_value) = type_field.details().extra.get("const") {
return const_value.as_str().map(|s| s.to_string());
}
// Check for x-stainless-const with default value
if let Some(stainless_const) = type_field.details().extra.get("x-stainless-const") {
if stainless_const.as_bool() == Some(true) {
if let Some(default_value) = &type_field.details().default {
if let Some(value) = default_value.as_str() {
return Some(value.to_string());
}
}
}
}
}
}
None
}
fn get_any_reference<'a>(&self, schema: &'a Schema) -> Option<&'a str> {
schema.reference().or_else(|| schema.recursive_reference())
}
fn extract_schema_name<'a>(&self, ref_str: &'a str) -> Option<&'a str> {
if ref_str == "#" {
return None; // Special case for self-reference
}
let parts: Vec<&str> = ref_str.split('/').collect();
// Standard pattern: #/components/schemas/{SchemaName}[/deeper/path]
// parts[0]="#", parts[1]="components", parts[2]="schemas", parts[3]="SchemaName"
if parts.len() >= 4 && parts[0] == "#" && parts[2] == "schemas" {
return Some(parts[3]);
}
// Fallback for other ref patterns: use last segment,
// but only if it looks like a schema name (not a bare number)
let last = parts.last()?;
if last.is_empty() || last.chars().all(|c| c.is_ascii_digit()) {
None
} else {
Some(last)
}
}
fn analyze_schema(&mut self, schema_name: &str) -> Result<AnalyzedSchema> {
// Check cache first
if let Some(cached) = self.resolved_cache.get(schema_name) {
return Ok(cached.clone());