|
1 | | -use std::io; |
| 1 | +use std::{ |
| 2 | + collections::{BTreeSet, VecDeque}, |
| 3 | + io, |
| 4 | +}; |
2 | 5 |
|
3 | 6 | use convert_case::{Case, Casing}; |
4 | 7 | use jsoncodegen::{ |
@@ -88,20 +91,34 @@ impl From<serde_json::Value> for Java { |
88 | 91 | }; |
89 | 92 | } |
90 | 93 |
|
91 | | - // TODO: instead of iterating through type_graph.nodes |
92 | | - // and processing TypeDef::Object and TypeDef::Union, |
93 | | - // do a bfs traversal (starting from root type_id) |
94 | | - // of all TypeIds that are either |
95 | | - // TypeDef::Object or TypeDef::Union |
96 | | - // This way, the root struct will always be on top |
97 | | - // and determining the root type name is much simpler |
98 | | - // |
99 | 94 | // TODO: to avoid case-insensitive name clash with ROOT, |
100 | 95 | // try to inline the root type in the top level JsonCodeGen |
101 | | - for (type_id, type_def) in &type_graph.nodes { |
| 96 | + |
| 97 | + let mut queue = VecDeque::from([type_graph.root]); |
| 98 | + let mut visited = BTreeSet::new(); |
| 99 | + while let Some(type_id) = queue.pop_front() { |
| 100 | + if !visited.insert(type_id) { |
| 101 | + continue; |
| 102 | + } |
| 103 | + |
| 104 | + let Some(type_def) = type_graph.nodes.get(&type_id) else { |
| 105 | + continue; |
| 106 | + }; |
| 107 | + |
| 108 | + match type_def { |
| 109 | + TypeDef::Array(inner_id) | TypeDef::Optional(inner_id) => { |
| 110 | + queue.push_back(*inner_id) |
| 111 | + } |
| 112 | + TypeDef::Object(object_fields) => { |
| 113 | + queue.extend(object_fields.iter().map(|field| field.type_id)) |
| 114 | + } |
| 115 | + TypeDef::Union(inner_ids) => queue.extend(inner_ids), |
| 116 | + _ => { /* no-op */ } |
| 117 | + } |
| 118 | + |
102 | 119 | if let TypeDef::Object(object_fields) = type_def { |
103 | 120 | let class_name = name_registry |
104 | | - .assigned_name(*type_id) |
| 121 | + .assigned_name(type_id) |
105 | 122 | .map(|ident| ident.to_case(Case::Pascal)) |
106 | 123 | .unwrap_or_else(|| format!("Type{}", type_id)); |
107 | 124 |
|
@@ -149,7 +166,7 @@ impl From<serde_json::Value> for Java { |
149 | 166 |
|
150 | 167 | if let TypeDef::Union(inner_type_ids) = type_def { |
151 | 168 | let class_name = name_registry |
152 | | - .assigned_name(*type_id) |
| 169 | + .assigned_name(type_id) |
153 | 170 | .map(|ident| ident.to_case(Case::Pascal)) |
154 | 171 | .unwrap_or_else(|| format!("Type{}", type_id)); |
155 | 172 |
|
|
0 commit comments