1use std::collections::{BTreeMap, BTreeSet};
9
10use serde_json::{Value, json};
11
12use super::docs::{Doc, Docs};
13use super::foreign::{TypeMapping, TypeTable};
14use super::naming;
15use super::wire_names::WireNames;
16use super::{Gap, graphql_attrs, serde_attrs};
17
18pub type Subst = BTreeMap<String, (Value, String)>;
21
22pub struct Resolver<'a> {
28 docs: Vec<Doc<'a>>,
30 cur: usize,
34 table: &'a TypeTable,
35 pub components: BTreeMap<String, Value>,
37 stems: BTreeMap<String, String>,
42 owners: BTreeMap<String, String>,
47 pub gaps: Vec<Gap>,
48 pub aux_resolved: BTreeSet<String>,
51 stack: BTreeSet<String>,
53}
54
55impl<'a> Resolver<'a> {
56 pub fn new(docs: impl Into<Docs<'a>>, table: &'a TypeTable) -> Result<Self, String> {
59 let docs = docs.into();
60 let mut open = vec![Doc::open(docs.primary())?];
61 open.extend(docs.aux().iter().filter_map(|d| Doc::open(d).ok()));
62 let walkable: BTreeSet<String> = open
63 .iter()
64 .flat_map(Doc::walkable)
65 .map(String::clone)
66 .collect();
67 Ok(Self {
68 stems: naming::stems(&walkable),
69 docs: open,
70 cur: 0,
71 table,
72 components: BTreeMap::new(),
73 owners: BTreeMap::new(),
74 gaps: Vec::new(),
75 aux_resolved: BTreeSet::new(),
76 stack: BTreeSet::new(),
77 })
78 }
79
80 pub(super) fn item(&self, id: &Value) -> Option<&'a Value> {
81 self.docs[self.cur].item(id)
82 }
83
84 pub(super) fn is_graphql_union(&self, item: &Value) -> bool {
85 self.docs[self.cur].is_graphql_union(item)
86 }
87
88 pub fn find_type_id(&self, name: &str) -> Option<Value> {
91 self.docs[0].scan_type_id(name)
92 }
93
94 pub fn find_by_path(&self, canonical: &str) -> Option<&'a Value> {
99 let doc = &self.docs[0];
100 let (id, _) = doc.paths.iter().find(|(_, entry)| {
101 entry["path"]
102 .as_array()
103 .map(|segs| {
104 let joined: Vec<&str> = segs.iter().filter_map(|s| s.as_str()).collect();
105 joined.join("::") == canonical
106 })
107 .unwrap_or(false)
108 })?;
109 doc.index.get(id)
110 }
111
112 pub fn resolve_by_name(&mut self, name: &str, at: &str) -> Option<Value> {
115 if let Some(id) = self.find_type_id(name) {
116 let node = json!({ "resolved_path": { "path": name, "id": id, "args": null } });
117 return Some(self.resolve(&node, &Subst::new(), at));
118 }
119 let found =
120 (1..self.docs.len()).find_map(|i| self.docs[i].locate_name(name).map(|id| (i, id)));
121 let (home, id) = found?;
122 self.note_aux(home, &id);
123 Some(self.resolve_named(home, &id, &[], &Subst::new(), at))
124 }
125
126 pub(super) fn canonical(&self, id: &Value) -> Option<String> {
128 self.docs[self.cur].canonical(id)
129 }
130
131 fn note_aux(&mut self, home: usize, id: &Value) {
133 if let Some(path) = self.docs[home].canonical(id) {
134 self.aux_resolved.insert(path);
135 }
136 }
137
138 pub(super) fn record(&mut self, gap: Gap) {
139 if !self.gaps.contains(&gap) {
140 self.gaps.push(gap);
141 }
142 }
143
144 pub fn is_option(ty: &Value) -> bool {
147 ty["resolved_path"]["path"]
148 .as_str()
149 .is_some_and(|p| p == "Option" || p.ends_with("::Option"))
150 }
151
152 pub fn resolve(&mut self, ty: &Value, subst: &Subst, at: &str) -> Value {
156 if let Some(p) = ty.get("primitive").and_then(|v| v.as_str()) {
157 return primitive(p);
158 }
159 if let Some(name) = ty.get("generic").and_then(|v| v.as_str()) {
160 return match subst.get(name) {
162 Some((schema, _)) => schema.clone(),
163 None => json!({}),
164 };
165 }
166 if let Some(bounds) = ty.get("impl_trait") {
167 return self.erased(bounds, at);
168 }
169 if let Some(dy) = ty.get("dyn_trait") {
170 return self.erased(&dy["traits"], at);
171 }
172 if let Some(inner) = ty.get("borrowed_ref") {
173 return self.resolve(&inner["type"], subst, at);
174 }
175 if let Some(inner) = ty.get("slice") {
176 let items = self.resolve(inner, subst, at);
177 return json!({ "type": "array", "items": items });
178 }
179 if let Some(arr) = ty.get("array") {
180 let items = self.resolve(&arr["type"], subst, at);
181 let mut schema = json!({ "type": "array", "items": items });
182 if let Some(len) = arr["len"].as_str().and_then(|l| l.parse::<u64>().ok()) {
183 schema["minItems"] = json!(len);
184 schema["maxItems"] = json!(len);
185 }
186 return schema;
187 }
188 if let Some(elems) = ty.get("tuple").and_then(|v| v.as_array()) {
189 if elems.is_empty() {
191 return json!({ "type": "null" });
192 }
193 let items: Vec<Value> = elems.iter().map(|e| self.resolve(e, subst, at)).collect();
194 let n = items.len();
195 return json!({ "type": "array", "prefixItems": items,
196 "minItems": n, "maxItems": n });
197 }
198 if ty.get("resolved_path").is_some() {
199 return self.resolve_path(&ty["resolved_path"], subst, at);
200 }
201 json!({})
204 }
205
206 fn erased(&mut self, bounds: &Value, at: &str) -> Value {
207 let bound = bounds
208 .as_array()
209 .and_then(|b| b.first())
210 .and_then(|b| b["trait_bound"]["trait"]["path"].as_str())
211 .unwrap_or("?")
212 .to_string();
213 self.record(Gap::Erased {
214 at: at.to_string(),
215 bound,
216 });
217 json!({})
218 }
219
220 fn resolve_path(&mut self, rp: &Value, subst: &Subst, at: &str) -> Value {
221 let display = rp["path"].as_str().unwrap_or_default();
222 let args = generic_args(rp);
223 let last = display.rsplit("::").next().unwrap_or(display);
224
225 match last {
228 "Option" => {
229 return match args.first() {
232 Some(inner) => self.resolve(inner, subst, at),
233 None => json!({}),
234 };
235 }
236 "Box" | "Arc" | "Rc" | "Cow" | "RefCell" | "Cell" | "Mutex" | "RwLock" => {
237 return match args.first() {
238 Some(inner) => self.resolve(inner, subst, at),
239 None => json!({}),
240 };
241 }
242 "Vec" | "VecDeque" | "HashSet" | "BTreeSet" | "BinaryHeap" | "LinkedList" => {
243 let items = match args.first() {
244 Some(inner) => self.resolve(inner, subst, at),
245 None => json!({}),
246 };
247 let mut schema = json!({ "type": "array", "items": items });
248 if matches!(last, "HashSet" | "BTreeSet") {
249 schema["uniqueItems"] = json!(true);
250 }
251 return schema;
252 }
253 "HashMap" | "BTreeMap" => {
254 let values = match args.get(1) {
255 Some(v) => self.resolve(v, subst, at),
256 None => json!({}),
257 };
258 return json!({ "type": "object", "additionalProperties": values });
259 }
260 "Result" => {
261 let ok = args
263 .first()
264 .map(|t| self.resolve(t, subst, at))
265 .unwrap_or(json!({}));
266 let err = args
267 .get(1)
268 .map(|t| self.resolve(t, subst, at))
269 .unwrap_or(json!({}));
270 return json!({ "oneOf": [
271 { "type": "object", "properties": { "Ok": ok },
272 "required": ["Ok"], "additionalProperties": false },
273 { "type": "object", "properties": { "Err": err },
274 "required": ["Err"], "additionalProperties": false },
275 ]});
276 }
277 "Connection" => {
286 let node = args
287 .get(1)
288 .map(|t| self.resolve(t, subst, at))
289 .unwrap_or(json!({}));
290 return json!({
291 "type": "object",
292 "properties": {
293 "pageInfo": {
294 "type": "object",
295 "properties": {
296 "hasPreviousPage": { "type": "boolean" },
297 "hasNextPage": { "type": "boolean" },
298 "startCursor": { "type": ["string", "null"] },
299 "endCursor": { "type": ["string", "null"] },
300 },
301 "required": ["hasPreviousPage", "hasNextPage"],
302 },
303 "edges": {
304 "type": "array",
305 "items": {
306 "type": "object",
307 "properties": { "cursor": { "type": "string" }, "node": node.clone() },
308 "required": ["cursor", "node"],
309 },
310 },
311 "nodes": { "type": "array", "items": node },
312 },
313 "required": ["pageInfo", "edges", "nodes"],
314 });
315 }
316 _ => {}
317 }
318
319 let id = &rp["id"];
320 if self.item(id).is_some() {
323 return self.resolve_named(self.cur, id, &args, subst, at);
324 }
325 let canonical = self.canonical(id).unwrap_or_else(|| display.to_string());
326 match self.table.lookup(&canonical).cloned() {
329 Some(TypeMapping::Literal(schema)) => return schema,
330 Some(TypeMapping::Transparent { arg }) => {
331 return self.transparent(&canonical, arg, &args, subst, at);
332 }
333 None => {}
334 }
335 if let Some((home, aux_id)) = self.locate_aux(&canonical) {
338 self.aux_resolved.insert(canonical);
339 return self.resolve_named(home, &aux_id, &args, subst, at);
340 }
341 if last == "String" || last == "str" {
342 return json!({ "type": "string" });
343 }
344 self.record(Gap::UnmappedForeign {
345 at: at.to_string(),
346 path: canonical,
347 });
348 json!({})
349 }
350
351 fn transparent(
355 &mut self,
356 path: &str,
357 arg: usize,
358 args: &[Value],
359 subst: &Subst,
360 at: &str,
361 ) -> Value {
362 match args.get(arg) {
363 Some(inner) => self.resolve(inner, subst, at),
364 None => {
365 self.record(Gap::TransparentWithoutArgument {
367 at: at.to_string(),
368 path: path.to_string(),
369 arg,
370 });
371 json!({})
372 }
373 }
374 }
375
376 fn locate_aux(&self, canonical: &str) -> Option<(usize, Value)> {
378 (1..self.docs.len()).find_map(|i| self.docs[i].locate(canonical).map(|id| (i, id)))
379 }
380
381 fn resolve_named(
387 &mut self,
388 home: usize,
389 id: &Value,
390 args: &[Value],
391 subst: &Subst,
392 at: &str,
393 ) -> Value {
394 let Some(item) = self.docs[home].item(id) else {
395 return json!({});
396 };
397 let base = item["name"].as_str().unwrap_or("Anonymous").to_string();
398
399 let params = generic_param_names(item);
401 let mut inner_subst = Subst::new();
402 let mut arg_names = Vec::new();
403 for (i, param) in params.iter().enumerate() {
404 let Some(arg) = args.get(i) else { continue };
405 let schema = self.resolve(arg, subst, at);
406 let name = type_display_name(arg, subst);
407 arg_names.push(name.clone());
408 inner_subst.insert(param.clone(), (schema, name));
409 }
410 let suffix = |stem: &str| match arg_names.is_empty() {
411 true => stem.to_string(),
412 false => format!("{stem}_{}", arg_names.join("_")),
413 };
414 let canonical = self.docs[home].canonical(id);
417 let stem = canonical
418 .as_ref()
419 .and_then(|c| self.stems.get(c))
420 .unwrap_or(&base);
421 let identity = suffix(canonical.as_ref().unwrap_or(&base));
422 let component = self.claim(&suffix(stem), &identity);
423 let reference = json!({ "$ref": format!("#/components/schemas/{component}") });
424
425 if self.components.contains_key(&component) || self.stack.contains(&component) {
426 return reference;
427 }
428 self.stack.insert(component.clone());
429 let outer = std::mem::replace(&mut self.cur, home);
431 let defined = self.define(item, &inner_subst, &component);
432 self.cur = outer;
433 self.stack.remove(&component);
434 self.components.insert(component, defined);
435 reference
436 }
437
438 fn claim(&mut self, display: &str, identity: &str) -> String {
446 let mut candidate = display.to_string();
447 let mut n = 1;
448 loop {
449 match self.owners.get(&candidate) {
450 Some(owner) if owner == identity => return candidate,
451 Some(_) => {
453 n += 1;
454 candidate = format!("{display}_{n}");
455 }
456 None => {
457 self.owners.insert(candidate.clone(), identity.to_string());
458 return candidate;
459 }
460 }
461 }
462 }
463
464 fn define(&mut self, item: &'a Value, subst: &Subst, at: &str) -> Value {
466 let inner = &item["inner"];
467 if let Some(s) = inner.get("struct") {
468 return self.walk_struct(item, s, subst, at);
469 }
470 if let Some(e) = inner.get("enum") {
471 return self.walk_enum(item, e, subst, at);
472 }
473 if let Some(t) = inner.get("type_alias") {
474 return self.resolve(&t["type"], subst, at);
475 }
476 json!({})
477 }
478
479 pub(super) fn describe(item: &Value, schema: &mut Value) {
481 if let Some(doc) = item["docs"].as_str().filter(|d| !d.is_empty())
482 && let Some(obj) = schema.as_object_mut()
483 {
484 let first = doc.split("\n\n").next().unwrap_or(doc);
485 obj.insert("description".into(), json!(first.trim()));
486 }
487 }
488
489 pub(super) fn container_attrs(&mut self, item: &Value, at: &str) -> WireNames {
491 let empty = Vec::new();
492 let attrs = item["attrs"].as_array().unwrap_or(&empty);
493 let serde = serde_attrs::container(attrs);
494
495 let gql = graphql_attrs::container(attrs);
499 let served = gql.present || self.docs[self.cur].serves_graphql(item);
500 let unknown = match served {
501 true => gql.unknown_rename_rule.clone(),
502 false => serde.unknown_rename_all.clone(),
503 };
504 if let Some(rule) = unknown {
505 self.record(Gap::UnknownRenameRule {
506 at: at.to_string(),
507 rule,
508 });
509 }
510 WireNames {
511 serde,
512 graphql: served.then_some(gql),
513 }
514 }
515}
516
517pub(super) fn generic_args(rp: &Value) -> Vec<Value> {
519 rp["args"]["angle_bracketed"]["args"]
520 .as_array()
521 .map(|args| args.iter().filter_map(|a| a.get("type").cloned()).collect())
522 .unwrap_or_default()
523}
524
525fn generic_param_names(item: &Value) -> Vec<String> {
527 let inner = &item["inner"];
528 let generics = inner
529 .get("struct")
530 .or_else(|| inner.get("enum"))
531 .or_else(|| inner.get("type_alias"))
532 .map(|k| &k["generics"]);
533 generics
534 .and_then(|g| g["params"].as_array())
535 .map(|ps| {
536 ps.iter()
537 .filter(|p| p["kind"].get("type").is_some())
538 .filter_map(|p| p["name"].as_str().map(String::from))
539 .collect()
540 })
541 .unwrap_or_default()
542}
543
544fn type_display_name(ty: &Value, subst: &Subst) -> String {
547 if let Some(p) = ty.get("primitive").and_then(|v| v.as_str()) {
548 return p.to_string();
549 }
550 if let Some(g) = ty.get("generic").and_then(|v| v.as_str()) {
551 return subst
552 .get(g)
553 .map(|(_, n)| n.clone())
554 .unwrap_or_else(|| g.to_string());
555 }
556 if let Some(path) = ty["resolved_path"]["path"].as_str() {
557 let base = path.rsplit("::").next().unwrap_or(path).to_string();
558 let args = generic_args(&ty["resolved_path"]);
559 if args.is_empty() {
560 return base;
561 }
562 let inner: Vec<String> = args.iter().map(|a| type_display_name(a, subst)).collect();
563 return format!("{base}_{}", inner.join("_"));
564 }
565 "T".to_string()
566}
567
568fn primitive(p: &str) -> Value {
570 match p {
571 "bool" => json!({ "type": "boolean" }),
572 "char" => json!({ "type": "string", "minLength": 1, "maxLength": 1 }),
573 "str" => json!({ "type": "string" }),
574 "f32" => json!({ "type": "number", "format": "float" }),
575 "f64" => json!({ "type": "number", "format": "double" }),
576 "i8" | "i16" | "i32" => json!({ "type": "integer", "format": "int32" }),
577 "u8" | "u16" | "u32" => json!({ "type": "integer", "format": "int32", "minimum": 0 }),
578 "i64" | "i128" | "isize" => json!({ "type": "integer", "format": "int64" }),
579 "u64" | "u128" | "usize" => {
580 json!({ "type": "integer", "format": "int64", "minimum": 0 })
581 }
582 "()" | "never" => json!({ "type": "null" }),
583 _ => json!({}),
584 }
585}