Skip to content

Commit 48d9e7e

Browse files
committed
implement bfs for java codegen so root will be at top
1 parent ea3daf1 commit 48d9e7e

1 file changed

Lines changed: 29 additions & 12 deletions

File tree

codegen-java/src/lib.rs

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
use std::io;
1+
use std::{
2+
collections::{BTreeSet, VecDeque},
3+
io,
4+
};
25

36
use convert_case::{Case, Casing};
47
use jsoncodegen::{
@@ -88,20 +91,34 @@ impl From<serde_json::Value> for Java {
8891
};
8992
}
9093

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-
//
9994
// TODO: to avoid case-insensitive name clash with ROOT,
10095
// 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+
102119
if let TypeDef::Object(object_fields) = type_def {
103120
let class_name = name_registry
104-
.assigned_name(*type_id)
121+
.assigned_name(type_id)
105122
.map(|ident| ident.to_case(Case::Pascal))
106123
.unwrap_or_else(|| format!("Type{}", type_id));
107124

@@ -149,7 +166,7 @@ impl From<serde_json::Value> for Java {
149166

150167
if let TypeDef::Union(inner_type_ids) = type_def {
151168
let class_name = name_registry
152-
.assigned_name(*type_id)
169+
.assigned_name(type_id)
153170
.map(|ident| ident.to_case(Case::Pascal))
154171
.unwrap_or_else(|| format!("Type{}", type_id));
155172

0 commit comments

Comments
 (0)