Skip to main content

soothfast_spec/schema/
types.rs

1//! Rustdoc type nodes → JSON Schema.
2//!
3//! Named local types resolve to `$ref`s into a components map, which both
4//! keeps the emitted spec readable and makes self-referential types
5//! terminate: a type already on the resolution stack yields its `$ref`
6//! immediately and the outer frame fills the definition.
7
8use 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
18/// Generic parameter bindings captured at a concrete use site: parameter name
19/// → (resolved schema, display name used for component naming).
20pub type Subst = BTreeMap<String, (Value, String)>;
21
22/// Walks rustdoc JSON, emitting JSON Schema and collecting [`Gap`]s.
23///
24/// Resolution may span several documents (see [`Docs`]), but `components`,
25/// the component-name registry and the cycle-breaking stack are shared across
26/// all of them: one type gets one component wherever it was defined.
27pub struct Resolver<'a> {
28    /// The documents in consultation order; `docs[0]` is the primary one.
29    docs: Vec<Doc<'a>>,
30    /// Which document the current descent is walking. A type pulled out of an
31    /// auxiliary document names its fields' types in that same document, so
32    /// the cursor moves with the descent and is restored on the way out.
33    cur: usize,
34    table: &'a TypeTable,
35    /// Named schemas, emitted as `components/schemas` in OpenAPI.
36    pub components: BTreeMap<String, Value>,
37    /// Canonical path → component-name stem, decided up front from the
38    /// documents alone (see [`naming`]). Because it does not depend on the
39    /// walk, every resolver over the same documents names a type identically,
40    /// which is what lets a dialect merge many operations' components.
41    stems: BTreeMap<String, String>,
42    /// Component name → the type identity holding it. The stems already keep
43    /// distinct types apart; this catches what they cannot see — a type with
44    /// no canonical path at all, and a monomorphisation suffix that happens
45    /// to spell another type's name.
46    owners: BTreeMap<String, String>,
47    pub gaps: Vec<Gap>,
48    /// Canonical paths walked out of an auxiliary document. Resolved, so
49    /// deliberately *not* gaps — reported only to say where they came from.
50    pub aux_resolved: BTreeSet<String>,
51    /// Component names currently being resolved, to break reference cycles.
52    stack: BTreeSet<String>,
53}
54
55impl<'a> Resolver<'a> {
56    /// Build a resolver over a parsed rustdoc JSON document, or over a
57    /// primary document plus its workspace-local companions ([`Docs`]).
58    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    /// Find a struct or enum by its plain name, for attribute overrides that
89    /// name a type rather than pointing at a signature.
90    pub fn find_type_id(&self, name: &str) -> Option<Value> {
91        self.docs[0].scan_type_id(name)
92    }
93
94    /// Find an item by its fully-qualified path, e.g. `app::routes::create`.
95    ///
96    /// `#[route]` records handler ids as `module_path!()::fn_name`, which is
97    /// exactly the path rustdoc reports, so route lookup is a direct match.
98    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    /// Resolve a struct or enum named in an attribute, searching this crate
113    /// first and then the workspace-local documents.
114    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    /// Canonical definition path of an id, in the document being walked.
127    pub(super) fn canonical(&self, id: &Value) -> Option<String> {
128        self.docs[self.cur].canonical(id)
129    }
130
131    /// Record that a type came out of an auxiliary crate rather than a gap.
132    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    /// True when a type is `Option<..>`, which makes a field optional on the
145    /// wire independently of the schema its inner type produces.
146    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    /// Resolve one rustdoc type node into a JSON Schema.
153    ///
154    /// `at` is a human-readable location (`Item.when`) used for gap reports.
155    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            // An unbound parameter means the use site was not monomorphic.
161            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            // serde emits the unit tuple as null and others as a JSON array.
190            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        // Function pointers, qualified paths and inferred types have no wire
202        // meaning worth guessing at.
203        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        // Standard containers are structural: they shape the schema rather
226        // than contributing a named component of their own.
227        match last {
228            "Option" => {
229                // Optionality is carried by the field, not the schema; a
230                // nullable inner schema is the honest rendering elsewhere.
231                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                // serde's externally tagged representation of Result.
262                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            // async-graphql's cursor-pagination wrapper — hand-written
278            // (`#[Object]` inside async-graphql itself, not derived from its
279            // own struct fields), so it can never be walked out of rustdoc
280            // JSON like a local type; its wire shape is fixed by the crate's
281            // own resolver, not by anything this repo defines. `Cursor` (the
282            // first argument) never reaches the wire itself — only through
283            // the `cursor` field the crate renders as a string — so only the
284            // second argument, the node type, needs resolving.
285            "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        // A type in the current document's `index` can be walked; one only in
321        // `paths` is identifiable but opaque *here*.
322        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        // The table first: an explicit mapping is the escape hatch for a type
327        // soothfast would derive wrongly, so it outranks anything derived.
328        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        // Then the workspace: a sibling crate's type is as walkable as a local
336        // one once its own document is on hand.
337        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    /// Resolve a wrapper mapped `transparent`: its wire shape is exactly its
352    /// type argument's, so it contributes no component and no `$ref` of its
353    /// own — the argument's schema stands in its place.
354    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                // Nothing to forward to: a guess here would invent a shape.
366                self.record(Gap::TransparentWithoutArgument {
367                    at: at.to_string(),
368                    path: path.to_string(),
369                    arg,
370                });
371                json!({})
372            }
373        }
374    }
375
376    /// The first auxiliary document defining `canonical`, and its id there.
377    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    /// Resolve a named type living in `home` to a `$ref`, defining the
382    /// component on first visit.
383    ///
384    /// Generic arguments come from the *use site*, so they are resolved
385    /// before the cursor moves; only the body walk happens in `home`.
386    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        // Bind the type's own generic parameters to this use site's args.
400        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        // The stem is a property of the type, so every operation in the
415        // document names it the same way and their components can be merged.
416        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        // Reserve the name before descending so a cycle finds it on the stack.
430        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    /// Hold `display` for this type, or number it if another type has it.
439    ///
440    /// [`naming::stems`] has already told apart every type the documents can
441    /// see, so this only fires for the two things it cannot: a type rustdoc
442    /// gives no canonical path (identified by bare name alone, exactly as
443    /// before), and a monomorphisation suffix that happens to spell another
444    /// component's name. A name is never re-pointed at a second type.
445    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                // `owners` is finite, so a free name is always reached.
452                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    /// Build the schema body for a local struct or enum.
465    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    /// Attach a `description` from the item's own doc comment when present.
480    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    /// Container-level serde attributes, reporting an unusable rename rule.
490    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        // A GraphQL-served type is known two ways: by the container traits its
496        // derive generated, and — for documents whose impls rustdoc did not
497        // record — by carrying a `#[graphql(...)]` attribute at all.
498        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
517/// The angle-bracketed type arguments of a resolved path, in order.
518pub(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
525/// Names of a type's own generic parameters, in declaration order.
526fn 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
544/// A short display name for a type argument, used to name monomorphised
545/// components (`ApiResponse<Item>` → `ApiResponse_Item`).
546fn 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
568/// Rust primitive → JSON Schema, with the integer formats OpenAPI expects.
569fn 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}