1use std::collections::{BTreeMap, HashMap, HashSet};
9
10use serde_json::{Map, Value};
11
12use super::read::{self, Doc, Reader};
13use super::schema::{self, MethodIn, PluginIn};
14use super::types::*;
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct TypeSource {
19 pub method: String,
20 pub schema: String,
22}
23
24#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum IrBuildError {
27 TitleCollision { namespace: String, title: String, first: TypeSource, second: TypeSource },
31 MissingSchema { path: Vec<String> },
33 Unreadable { path: Vec<String>, detail: String },
35}
36
37fn show_path(path: &[String]) -> String {
38 if path.is_empty() {
39 "the root".into()
40 } else {
41 path.join(".")
42 }
43}
44
45impl std::fmt::Display for IrBuildError {
47 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48 match self {
49 IrBuildError::TitleCollision { namespace, title, first, second } => {
50 let ns = if namespace.is_empty() { "(root)".to_string() } else { format!("\"{namespace}\"") };
51 write!(
52 f,
53 "IR: two different types are titled \"{title}\" in namespace {ns}: method {} ({}) and method {} ({}). One title in one namespace is one type; rename one of them.",
54 first.method, first.schema, second.method, second.schema
55 )
56 }
57 IrBuildError::MissingSchema { path } => write!(f, "IR: no schema at {}", show_path(path)),
58 IrBuildError::Unreadable { path, detail } => write!(f, "IR: the schema at {} is unreadable: {detail}", show_path(path)),
59 }
60 }
61}
62
63impl std::error::Error for IrBuildError {}
64
65pub fn build_one(backend: &str, path: &[String], schema: &Value) -> Result<Ir, IrBuildError> {
68 let parsed = schema::plugin(schema).map_err(|detail| IrBuildError::Unreadable { path: path.to_vec(), detail })?;
69 let raw = plugin_ir(path, &parsed, vec![])?;
70 Ok(Ir { backend: backend.into(), ..finalize(raw) })
71}
72
73pub fn build(backend: &str, roots: &[Vec<String>], schemas: &BTreeMap<Vec<String>, Value>) -> Result<Ir, IrBuildError> {
82 let mut irs = Vec::new();
83 for root in roots {
84 let schema = schemas.get(root).ok_or_else(|| IrBuildError::MissingSchema { path: root.clone() })?;
85 let parsed = schema::plugin(schema).map_err(|detail| IrBuildError::Unreadable { path: root.clone(), detail })?;
86 irs.push(walk(root, &parsed, schemas)?);
87 }
88 let raw = irs.into_iter().rev().fold(Ir::empty(), |acc, ir| merge(ir, acc));
89 Ok(Ir { backend: backend.into(), ..finalize(raw) })
90}
91
92fn walk(path: &[String], schema: &PluginIn<'_>, schemas: &BTreeMap<Vec<String>, Value>) -> Result<Ir, IrBuildError> {
93 let mut child_irs = Vec::new();
94 for ns in schema.children.iter().flatten() {
95 let mut child = path.to_vec();
96 child.push(ns.clone());
97 let Some(v) = schemas.get(&child) else { continue };
98 let Ok(parsed) = schema::plugin(v) else { continue };
99 child_irs.push(walk(&child, &parsed, schemas)?);
100 }
101 Ok(plugin_ir_refusing(path, schema, child_irs))
102}
103
104fn plugin_ir_refusing(path: &[String], schema: &PluginIn<'_>, child_irs: Vec<Ir>) -> Ir {
110 match plugin_ir(path, schema, child_irs.clone()) {
111 Ok(ir) => ir,
112 Err(err) => {
113 let bare_schema = PluginIn {
114 hash: schema.hash.clone(),
115 methods: Vec::new(),
116 children: schema.children.clone(),
117 request: schema.request,
118 roles: schema.roles.clone(),
119 };
120 let mut bare = plugin_ir(path, &bare_schema, child_irs).unwrap_or_else(|_| Ir::empty());
121 let rendered = err.to_string();
122 let why = rendered.strip_prefix("IR: ").unwrap_or(&rendered);
123 bare.refusals.insert(
124 0,
125 Refusal { site: path.join("."), keyword: "title".into(), variant: None, detail: format!("{why} The activation is left out.") },
126 );
127 bare
128 }
129 }
130}
131
132fn merge(a: Ir, b: Ir) -> Ir {
134 fn union<K: Ord, V>(mut a: BTreeMap<K, V>, b: BTreeMap<K, V>) -> BTreeMap<K, V> {
135 for (k, v) in b {
136 a.entry(k).or_insert(v);
137 }
138 a
139 }
140 fn opt_union<K: Ord, V>(a: Option<BTreeMap<K, V>>, b: Option<BTreeMap<K, V>>) -> Option<BTreeMap<K, V>> {
141 match (a, b) {
142 (Some(a), Some(b)) => Some(union(a, b)),
143 (a, None) => a,
144 (None, b) => b,
145 }
146 }
147 let mut plugins = a.plugins;
148 for (k, v) in b.plugins {
149 plugins.entry(k).or_default().extend(v);
150 }
151 let mut refusals = a.refusals;
152 refusals.extend(b.refusals);
153 Ir {
154 version: a.version,
155 backend: a.backend,
156 hash: a.hash.or(b.hash),
157 types: union(a.types, b.types),
158 methods: union(a.methods, b.methods),
159 plugins,
160 plugin_hashes: opt_union(a.plugin_hashes, b.plugin_hashes),
161 plugin_requests: opt_union(a.plugin_requests, b.plugin_requests),
162 plugin_roles: opt_union(a.plugin_roles, b.plugin_roles),
163 refusals,
164 }
165}
166
167fn plugin_ir(path: &[String], schema: &PluginIn<'_>, child_irs: Vec<Ir>) -> Result<Ir, IrBuildError> {
169 let namespace = path.join(".");
170 let (local_types, local_methods, local_refusals) = extract_from_plugin(&namespace, schema)?;
171 let child = child_irs.into_iter().rev().fold(Ir::empty(), |acc, ir| merge(ir, acc));
172 let plugin_methods: Vec<String> = local_methods.values().map(|m| m.name.clone()).collect();
173 let hash = if path.is_empty() { Some(schema.hash.clone()) } else { child.hash.clone() };
174 let mut hashes = child.plugin_hashes.unwrap_or_default();
175 hashes.insert(
176 namespace.clone(),
177 PluginHashInfo { hash: schema.hash.clone(), self_hash: schema.hash.clone(), children_hash: schema.hash.clone() },
178 );
179 let mut requests = child.plugin_requests.unwrap_or_default();
180 if let Some(r) = schema.request {
181 requests.insert(namespace.clone(), r.clone());
182 }
183 let roles = match &schema.roles {
184 None => child.plugin_roles,
185 Some(roles) => {
186 let mut all = child.plugin_roles.unwrap_or_default();
187 all.insert(namespace.clone(), roles.clone());
188 Some(all)
189 }
190 };
191 let mut types = local_types;
192 for (k, v) in child.types {
193 types.entry(k).or_insert(v);
194 }
195 let mut methods = local_methods;
196 for (k, v) in child.methods {
197 methods.entry(k).or_insert(v);
198 }
199 let mut plugins = child.plugins;
200 plugins.insert(namespace, plugin_methods);
201 let mut refusals = local_refusals;
202 refusals.extend(child.refusals);
203 Ok(Ir {
204 version: IR_VERSION.into(),
205 backend: String::new(),
206 hash,
207 types,
208 methods,
209 plugins,
210 plugin_hashes: Some(hashes),
211 plugin_requests: if requests.is_empty() { None } else { Some(requests) },
212 plugin_roles: roles,
213 refusals,
214 })
215}
216
217type Extracted = (BTreeMap<String, TypeDef>, BTreeMap<String, MethodDef>, Vec<Refusal>);
222
223fn extract_from_plugin(namespace: &str, schema: &PluginIn<'_>) -> Result<Extracted, IrBuildError> {
224 check_titles(namespace, &schema.methods)?;
225 let docs: Vec<&Map<String, Value>> =
227 schema.methods.iter().flat_map(|m| m.docs()).filter_map(|(_, v)| v.as_object()).collect();
228 let defs = read::shared_defs(&docs);
229 let shared = Doc { namespace, defs: &defs, root: None };
230 let mut r = Reader::default();
231 let mut types = read::read_defs(&mut r, &shared);
232 let mut methods = BTreeMap::new();
233 for m in &schema.methods {
234 let (ts, md) = method_def(&mut r, &shared, namespace, m);
235 for (k, v) in ts {
236 types.entry(k).or_insert(v);
237 }
238 methods.insert(md.full_path.clone(), md);
239 }
240 Ok((types, methods, r.refusals))
241}
242
243fn root_fallback(m: &MethodIn<'_>, which: &str) -> String {
245 match which {
246 "returns" => format!("{}Result", m.name),
247 "error" => format!("{}Error", m.name),
248 "progress" => format!("{}Progress", m.name),
249 "input" => format!("{}Input", m.name),
250 other => format!("{}{other}", m.name),
251 }
252}
253
254fn check_titles(namespace: &str, methods: &[MethodIn<'_>]) -> Result<(), IrBuildError> {
259 let mut by_name: BTreeMap<String, Vec<(Value, &Map<String, Value>, TypeSource)>> = BTreeMap::new();
260 for m in methods {
261 for (which, doc) in m.docs() {
262 let Value::Object(doc_obj) = doc else { continue };
263 let source = || TypeSource { method: m.name.clone(), schema: which.to_string() };
264 let defs = doc_obj.get("$defs").or_else(|| doc_obj.get("definitions"));
266 if let Some(Value::Object(d)) = defs {
267 for (k, v) in read::sorted(d) {
268 by_name.entry(k.clone()).or_default().push((v.clone(), doc_obj, source()));
269 }
270 }
271 if which != "params" {
272 if let Some((name, body)) = read::root_named(&root_fallback(m, which), doc) {
273 by_name.entry(name).or_default().push((body, doc_obj, source()));
274 }
275 }
276 }
277 }
278 for (name, occurrences) in &by_name {
279 let mut iter = occurrences.iter();
280 let Some((b0, d0, s0)) = iter.next() else { continue };
281 let mut k0: Option<Option<TypeKind>> = None;
282 for (b, d, s) in iter {
283 if b == b0 {
284 continue;
285 }
286 let kind0 = k0.get_or_insert_with(|| read::read_kind_in(namespace, d0, name, b0)).clone();
287 let kind = read::read_kind_in(namespace, d, name, b);
288 if !same_shape(&kind0, &kind) {
289 return Err(IrBuildError::TitleCollision {
290 namespace: namespace.into(),
291 title: name.clone(),
292 first: s0.clone(),
293 second: s.clone(),
294 });
295 }
296 }
297 }
298 Ok(())
299}
300
301fn same_shape(a: &Option<TypeKind>, b: &Option<TypeKind>) -> bool {
304 fn undocumented(k: &TypeKind) -> TypeKind {
305 let field = |f: &FieldDef| FieldDef { description: None, ..f.clone() };
306 match k {
307 TypeKind::Struct { fields } => TypeKind::Struct { fields: fields.iter().map(field).collect() },
308 TypeKind::Enum { discriminator, variants, repr } => TypeKind::Enum {
309 discriminator: discriminator.clone(),
310 variants: variants
311 .iter()
312 .map(|v| VariantDef { description: None, fields: v.fields.iter().map(field).collect(), ..v.clone() })
313 .collect(),
314 repr: *repr,
315 },
316 other => other.clone(),
317 }
318 }
319 a.as_ref().map(undocumented) == b.as_ref().map(undocumented)
320}
321
322fn method_def(r: &mut Reader, shared: &Doc<'_>, namespace: &str, m: &MethodIn<'_>) -> (BTreeMap<String, TypeDef>, MethodDef) {
323 let full_path = format!("{namespace}.{}", m.name);
324 let (param_types, params, injected) = read_params(r, shared, &full_path, m);
325 let returns = match m.role {
326 MethodRole::Rpc => read::read_root(r, Some(shared), namespace, &read::site_returns(&full_path), &root_fallback(m, "returns"), &m.returns),
327 _ => read::RootRead { types: BTreeMap::new(), r#ref: TypeRef::Child(full_path.clone()) },
328 };
329 let error = m.error.map(|e| read::read_root(r, Some(shared), namespace, &read::site_error(&full_path), &root_fallback(m, "error"), e));
330 let progress =
331 m.progress.map(|p| read::read_root(r, Some(shared), namespace, &read::site_progress(&full_path), &root_fallback(m, "progress"), p));
332 let input = m.input.map(|i| read::read_root(r, Some(shared), namespace, &read::site_input(&full_path), &root_fallback(m, "input"), i));
333 let mut types = param_types;
334 let mut add = |ts: BTreeMap<String, TypeDef>| {
335 for (k, v) in ts {
336 types.entry(k).or_insert(v);
337 }
338 };
339 let returns_ref = returns.r#ref;
340 add(returns.types);
341 let error_ref = error.map(|e| {
342 add(e.types);
343 e.r#ref
344 });
345 let progress_ref = progress.map(|p| {
346 add(p.types);
347 p.r#ref
348 });
349 let input_ref = input.map(|i| {
350 add(i.types);
351 i.r#ref
352 });
353 let md = MethodDef {
354 name: m.name.clone(),
355 full_path,
356 namespace: namespace.into(),
357 description: Some(m.description.clone()),
358 params,
359 returns: returns_ref,
360 error: error_ref,
361 progress: progress_ref,
362 cardinality: m.cardinality,
363 role: m.role.clone(),
364 grant: m.grant.clone(),
365 target: m.target.clone(),
366 long_description: m.long_description.clone(),
367 injected,
368 input: input_ref,
369 };
370 (types, md)
371}
372
373fn read_params(r: &mut Reader, shared: &Doc<'_>, full_path: &str, m: &MethodIn<'_>) -> (BTreeMap<String, TypeDef>, Vec<ParamDef>, Vec<InjectedParam>) {
376 let Some(Value::Object(o)) = m.params else { return (BTreeMap::new(), vec![], vec![]) };
377 let props: Vec<(&String, &Value)> = match o.get("properties") {
378 Some(Value::Object(p)) => read::sorted(p),
379 _ => vec![],
380 };
381 let required = read::required_of(o);
382 let deprecation_of = |name: &str| {
383 m.param_schemas.as_ref().and_then(|ps| ps.iter().find(|p| p.name == name)).and_then(|p| p.deprecation.clone())
384 };
385 let mut params = Vec::new();
386 let mut injected = Vec::new();
387 for (name, v) in props {
388 let source = match v {
389 Value::Object(po) => po.get("x-plexus-source").cloned(),
390 _ => None,
391 };
392 let server_supplied = matches!(&source, Some(Value::Object(src)) if src.get("from") != Some(&Value::String("rpc".into())));
393 if server_supplied {
394 injected.push(InjectedParam { name: name.clone(), source: source.unwrap_or(Value::Null), description: read::description_of(v) });
395 continue;
396 }
397 let ty = read::read_type(r, shared, &read::site_param(full_path, name), v);
398 let values = match v {
399 Value::Object(po) => match po.get("x-plexus-values") {
400 Some(Value::Array(vs)) => Some(vs.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()),
401 _ => None,
402 },
403 _ => None,
404 };
405 params.push(ParamDef {
406 name: name.clone(),
407 ty,
408 description: read::description_of(v),
409 required: required.contains(name),
410 default: read::default_of(v),
411 deprecation: deprecation_of(name),
412 source,
413 values,
414 });
415 }
416 (BTreeMap::new(), params, injected)
417}
418
419fn finalize(raw: Ir) -> Ir {
425 let placed = deduplicate(raw);
426 let refused: HashSet<String> = placed.refusals.iter().map(|r| r.site.clone()).collect();
427 let (mut fixed, dangling) = unknown_where_unnamed(&refused, placed);
428 let mut all = std::mem::take(&mut fixed.refusals);
429 all.extend(dangling);
430 let mut refusals: Vec<Refusal> = Vec::new();
431 for r in all {
432 if !refusals.contains(&r) {
433 refusals.push(r);
434 }
435 }
436 refusals.sort_by(|a, b| a.site.cmp(&b.site));
437 fixed.refusals = refusals;
438 fixed
439}
440
441fn strip_namespace(t: TypeRef) -> TypeRef {
442 t.map(&|t| match t {
443 TypeRef::Named(qn) => TypeRef::Named(QualifiedName { namespace: String::new(), local: qn.local }),
444 other => other,
445 })
446}
447
448fn deduplicate(mut ir: Ir) -> Ir {
451 let mut groups: Vec<((String, TypeKind), Vec<(String, TypeDef)>)> = Vec::new();
453 let mut by_name: HashMap<String, Vec<usize>> = HashMap::new();
454 for (full, td) in std::mem::take(&mut ir.types) {
455 let key = (td.name.clone(), td.kind.clone().map_refs(&strip_namespace));
456 let slot = by_name.get(&td.name).and_then(|ix| ix.iter().copied().find(|&i| groups[i].0 == key));
457 match slot {
458 Some(i) => groups[i].1.push((full, td)),
459 None => {
460 by_name.entry(td.name.clone()).or_default().push(groups.len());
461 groups.push((key, vec![(full, td)]));
462 }
463 }
464 }
465 let contested: HashSet<(String, String)> = groups
466 .iter()
467 .filter(|(_, g)| g.len() > 1)
468 .flat_map(|(_, g)| g.iter().map(|(_, td)| (td.namespace.clone(), td.name.clone())))
469 .collect();
470 let counts = ref_counts(&contested, &ir, &groups);
471 let mut redirects: HashMap<String, String> = HashMap::new();
472 let mut canonical: Vec<(String, TypeDef)> = Vec::new();
473 for (_, group) in groups {
474 let at = select_canonical(&counts, &group);
475 let name = group[at].0.clone();
476 for (old, _) in &group {
477 if *old != name {
478 redirects.insert(old.clone(), name.clone());
479 }
480 }
481 let td = group.into_iter().nth(at).expect("the canonical copy").1;
482 canonical.push((name, td));
483 }
484 let update = |t: TypeRef| update_ref(&redirects, t);
485 ir.types = canonical.into_iter().map(|(k, td)| (k, TypeDef { kind: td.kind.map_refs(&update), ..td })).collect();
486 for md in ir.methods.values_mut() {
487 for p in md.params.iter_mut() {
488 p.ty = update(std::mem::replace(&mut p.ty, TypeRef::Unknown));
489 }
490 md.returns = update(std::mem::replace(&mut md.returns, TypeRef::Unknown));
491 md.error = md.error.take().map(update);
492 md.progress = md.progress.take().map(update);
493 md.input = md.input.take().map(update);
494 }
495 ir
496}
497
498fn ref_counts(contested: &HashSet<(String, String)>, ir: &Ir, groups: &[((String, TypeKind), Vec<(String, TypeDef)>)]) -> HashMap<(String, String), usize> {
502 let mut counts = HashMap::new();
503 if contested.is_empty() {
504 return counts;
505 }
506 fn keys<'a>(t: &'a TypeRef, out: &mut Vec<&'a QualifiedName>) {
507 match t {
508 TypeRef::Named(qn) => out.push(qn),
509 other => other.children().into_iter().for_each(|c| keys(c, out)),
510 }
511 }
512 let mut names: Vec<&QualifiedName> = Vec::new();
513 for md in ir.methods.values() {
514 for p in &md.params {
515 keys(&p.ty, &mut names);
516 }
517 keys(&md.returns, &mut names);
518 for t in [&md.error, &md.progress, &md.input].into_iter().flatten() {
519 keys(t, &mut names);
520 }
521 }
522 for (_, group) in groups {
523 for (_, td) in group {
524 match &td.kind {
525 TypeKind::Struct { fields } => fields.iter().for_each(|f| keys(&f.ty, &mut names)),
526 TypeKind::Enum { variants, .. } => {
527 for v in variants {
528 v.fields.iter().for_each(|f| keys(&f.ty, &mut names));
529 if let Some(r) = &v.vref {
530 keys(r, &mut names);
531 }
532 }
533 }
534 TypeKind::Alias { target } => keys(target, &mut names),
535 _ => {}
536 }
537 }
538 }
539 for qn in names {
540 let k = (qn.namespace.clone(), qn.local.clone());
541 if contested.contains(&k) {
542 *counts.entry(k).or_insert(0) += 1;
543 }
544 }
545 counts
546}
547
548fn select_canonical(counts: &HashMap<(String, String), usize>, group: &[(String, TypeDef)]) -> usize {
553 if group.len() == 1 {
554 return 0;
555 }
556 let generated: Vec<usize> = (0..group.len()).filter(|&i| !group[i].1.namespace.is_empty()).collect();
557 let candidates: Vec<usize> = if generated.is_empty() { (0..group.len()).collect() } else { generated };
558 let count_of = |i: usize| counts.get(&(group[i].1.namespace.clone(), group[i].1.name.clone())).copied().unwrap_or(0);
559 let best = candidates.iter().map(|&i| count_of(i)).max().unwrap_or(0);
560 let tied: Vec<usize> = candidates.into_iter().filter(|&i| count_of(i) == best).collect();
561 let ns = |i: usize| group[i].1.namespace.as_str();
562 let ancestor_of_all = |c: usize| tied.iter().all(|&o| ns(o) == ns(c) || ns(o).starts_with(&format!("{}.", ns(c))));
563 if let Some(&c) = tied.iter().find(|&&c| ancestor_of_all(c)) {
564 return c;
565 }
566 *tied.iter().min_by(|&&a, &&b| (ns(a).chars().count(), ns(a)).cmp(&(ns(b).chars().count(), ns(b)))).expect("a tied copy")
567}
568
569fn parse_qualified_name(t: &str) -> Option<QualifiedName> {
571 let i = t.rfind('.')?;
572 let local = &t[i + 1..];
573 if local.is_empty() {
574 return None;
575 }
576 Some(QualifiedName { namespace: t[..i].to_string(), local: local.to_string() })
577}
578
579fn update_ref(redirects: &HashMap<String, String>, t: TypeRef) -> TypeRef {
582 t.map(&|t| match t {
583 TypeRef::Named(qn) => {
584 let full = qn.key();
585 let canonical = redirects.get(&full).cloned().unwrap_or(full);
586 match parse_qualified_name(&canonical) {
587 Some(q) => TypeRef::Named(q),
588 None => TypeRef::Named(qn),
589 }
590 }
591 other => other,
592 })
593}
594
595fn unknown_where_unnamed(refused: &HashSet<String>, mut ir: Ir) -> (Ir, Vec<Refusal>) {
599 let known: HashSet<String> = ir.types.keys().cloned().collect();
600 fn fix(known: &HashSet<String>, refused: &HashSet<String>, site: &str, t: TypeRef, out: &mut Vec<Refusal>) -> TypeRef {
601 match t {
602 TypeRef::Named(qn) => {
603 let full = qn.key();
604 if known.contains(&full) {
605 TypeRef::Named(qn)
606 } else {
607 if !refused.contains(&full) {
608 out.push(Refusal {
609 site: site.into(),
610 keyword: "$ref".into(),
611 variant: None,
612 detail: format!("names {full}, which no $defs defines"),
613 });
614 }
615 TypeRef::Unknown
616 }
617 }
618 TypeRef::Array(i) => TypeRef::Array(Box::new(fix(known, refused, &format!("{site}[]"), *i, out))),
619 TypeRef::Optional(i) => TypeRef::Optional(Box::new(fix(known, refused, &format!("{site}?"), *i, out))),
620 TypeRef::Map(i) => TypeRef::Map(Box::new(fix(known, refused, &format!("{site}{{}}"), *i, out))),
621 TypeRef::Refined(i, r) => TypeRef::Refined(Box::new(fix(known, refused, site, *i, out)), r),
622 TypeRef::Tuple(ts) => {
623 TypeRef::Tuple(ts.into_iter().enumerate().map(|(n, x)| fix(known, refused, &format!("{site}.{n}"), x, out)).collect())
624 }
625 other => other,
626 }
627 }
628 let mut out = Vec::new();
629 let fields = |site: &str, fs: Vec<FieldDef>, out: &mut Vec<Refusal>| -> Vec<FieldDef> {
630 fs.into_iter()
631 .map(|f| {
632 let ty = fix(&known, refused, &format!("{site}.{}", f.name), f.ty.clone(), out);
633 FieldDef { ty, ..f }
634 })
635 .collect()
636 };
637 let types = std::mem::take(&mut ir.types);
638 let mut fixed_types = BTreeMap::new();
639 for (name, td) in types {
640 let kind = match td.kind {
641 TypeKind::Struct { fields: fs } => TypeKind::Struct { fields: fields(&name, fs, &mut out) },
642 TypeKind::Enum { discriminator, variants, repr } => {
643 let variants = variants
644 .into_iter()
645 .map(|v| {
646 let vsite = format!("{name}.{}", v.name);
647 let fs = fields(&vsite, v.fields, &mut out);
648 let vref = v.vref.map(|x| fix(&known, refused, &vsite, x, &mut out));
649 VariantDef { fields: fs, vref, name: v.name, description: v.description }
650 })
651 .collect();
652 TypeKind::Enum { discriminator, variants, repr }
653 }
654 TypeKind::Alias { target } => TypeKind::Alias { target: fix(&known, refused, &name, target, &mut out) },
655 other => other,
656 };
657 fixed_types.insert(name, TypeDef { kind, ..td });
658 }
659 ir.types = fixed_types;
660 for md in ir.methods.values_mut() {
661 let path = md.full_path.clone();
662 for p in md.params.iter_mut() {
663 let ty = std::mem::replace(&mut p.ty, TypeRef::Unknown);
664 p.ty = fix(&known, refused, &read::site_param(&path, &p.name), ty, &mut out);
665 }
666 let ret = std::mem::replace(&mut md.returns, TypeRef::Unknown);
667 md.returns = fix(&known, refused, &read::site_returns(&path), ret, &mut out);
668 md.error = md.error.take().map(|t| fix(&known, refused, &read::site_error(&path), t, &mut out));
669 md.progress = md.progress.take().map(|t| fix(&known, refused, &read::site_progress(&path), t, &mut out));
670 md.input = md.input.take().map(|t| fix(&known, refused, &read::site_input(&path), t, &mut out));
671 }
672 (ir, out)
673}