Skip to main content

plexus_core/plexus/ir/
build.rs

1//! The builder: synapse's `Synapse.IR.Builder`, ported — a plugin's types
2//! and methods read from its schema (one title, one shape: else the build
3//! fails), the walk's fold over a node and its children, and the IR made
4//! whole: identical types in different namespaces deduplicated, each placed
5//! where it is referred to most, every ref that names no type turned to
6//! `RefUnknown`, the refusals deduplicated and sorted by site.
7
8use 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/// Where a type was read: a method, and which of its schemas.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct TypeSource {
19    pub method: String,
20    /// `params`, `returns`, `error`, `progress` or `input`.
21    pub schema: String,
22}
23
24/// Why no IR can be built.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum IrBuildError {
27    /// Two different shapes carry one name in one namespace (RETURNS-13):
28    /// a conflict the activation's author resolves; the IR never picks one.
29    /// Only [`build_one`] fails so; [`build`]'s walk refuses that activation.
30    TitleCollision { namespace: String, title: String, first: TypeSource, second: TypeSource },
31    /// A walk's root no schema was given for.
32    MissingSchema { path: Vec<String> },
33    /// A walk's root whose schema synapse could not read.
34    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
45/// synapse's `renderIRBuildError`, word for word.
46impl 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
65/// The IR of one plugin schema at `path`, children aside (synapse's
66/// `buildIRFromSchema`).
67pub 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
73/// What synapse's walk builds from each of `roots`, every schema it would
74/// fetch given by path (the root at `[]`): a node's IR from its schema and
75/// its children's (in its `children` order; a child with no schema, or one
76/// synapse could not read, skipped as a walk skips a failed fetch; one whose
77/// schemas put two shapes under one title refused, not the walk), each
78/// root's merged left to right, then made whole (synapse's
79/// `buildIRFromSchemas`). Only a root with no schema, or one that cannot be
80/// read, fails.
81pub 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
104/// synapse's `pluginIRRefusing` (RETURNS-36 review #9): one node as the
105/// walk builds it. A plugin whose schemas put two shapes under one title is
106/// refused, not the walk: its methods and types are left out, a `title`
107/// refusal at its namespace names both sites, and its children are built
108/// as ever.
109fn 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
132/// synapse's `mergeIR`: left-biased.
133fn 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
167/// One plugin node: its own types and methods, merged with its children's.
168fn 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
217// ---------------------------------------------------------------------------
218// One plugin
219// ---------------------------------------------------------------------------
220
221type 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    // every method's documents share one namespace's $defs: read once
226    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
243/// The fallback name of a method's untitled named root, by schema.
244fn 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
254/// One name in one namespace is one type (RETURNS-13): every name the
255/// methods' schemas define — each `$defs` entry, each named root — compared
256/// in name order; two shapes under one name fail, naming the first and the
257/// second.
258fn 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            // `$defs`, else `definitions` — whichever key is there, as long as it is an object
265            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
301/// Two readings of a name are one type when they agree on everything but
302/// their documentation.
303fn 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        // StandardBidirChannel's T = serde_json::Value
364        bidir_type: m.bidirectional.then_some(TypeRef::Json),
365        bidir_response_type: None,
366        bidir_response_schema: m.response_type.cloned(),
367        role: m.role.clone(),
368        grant: m.grant.clone(),
369        target: m.target.clone(),
370        long_description: m.long_description.clone(),
371        injected,
372        input: input_ref,
373    };
374    (types, md)
375}
376
377/// The params schema read: the params a client sends, and those the server
378/// injects (`x-plexus-source` other than rpc — not read as types).
379fn read_params(r: &mut Reader, shared: &Doc<'_>, full_path: &str, m: &MethodIn<'_>) -> (BTreeMap<String, TypeDef>, Vec<ParamDef>, Vec<InjectedParam>) {
380    let Some(Value::Object(o)) = m.params else { return (BTreeMap::new(), vec![], vec![]) };
381    let props: Vec<(&String, &Value)> = match o.get("properties") {
382        Some(Value::Object(p)) => read::sorted(p),
383        _ => vec![],
384    };
385    let required = read::required_of(o);
386    let deprecation_of = |name: &str| {
387        m.param_schemas.as_ref().and_then(|ps| ps.iter().find(|p| p.name == name)).and_then(|p| p.deprecation.clone())
388    };
389    let mut params = Vec::new();
390    let mut injected = Vec::new();
391    for (name, v) in props {
392        let source = match v {
393            Value::Object(po) => po.get("x-plexus-source").cloned(),
394            _ => None,
395        };
396        let server_supplied = matches!(&source, Some(Value::Object(src)) if src.get("from") != Some(&Value::String("rpc".into())));
397        if server_supplied {
398            injected.push(InjectedParam { name: name.clone(), source: source.unwrap_or(Value::Null), description: read::description_of(v) });
399            continue;
400        }
401        let ty = read::read_type(r, shared, &read::site_param(full_path, name), v);
402        let values = match v {
403            Value::Object(po) => match po.get("x-plexus-values") {
404                Some(Value::Array(vs)) => Some(vs.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()),
405                _ => None,
406            },
407            _ => None,
408        };
409        params.push(ParamDef {
410            name: name.clone(),
411            ty,
412            description: read::description_of(v),
413            required: required.contains(name),
414            default: read::default_of(v),
415            deprecation: deprecation_of(name),
416            source,
417            values,
418        });
419    }
420    (BTreeMap::new(), params, injected)
421}
422
423// ---------------------------------------------------------------------------
424// The IR made whole
425// ---------------------------------------------------------------------------
426
427/// synapse's `finalizeIR`.
428fn finalize(raw: Ir) -> Ir {
429    let placed = deduplicate(raw);
430    let refused: HashSet<String> = placed.refusals.iter().map(|r| r.site.clone()).collect();
431    let (mut fixed, dangling) = unknown_where_unnamed(&refused, placed);
432    let mut all = std::mem::take(&mut fixed.refusals);
433    all.extend(dangling);
434    let mut refusals: Vec<Refusal> = Vec::new();
435    for r in all {
436        if !refusals.contains(&r) {
437            refusals.push(r);
438        }
439    }
440    refusals.sort_by(|a, b| a.site.cmp(&b.site));
441    fixed.refusals = refusals;
442    fixed
443}
444
445fn strip_namespace(t: TypeRef) -> TypeRef {
446    t.map(&|t| match t {
447        TypeRef::Named(qn) => TypeRef::Named(QualifiedName { namespace: String::new(), local: qn.local }),
448        other => other,
449    })
450}
451
452/// Deduplicate types by structure (name and kind, namespaces stripped from
453/// refs), each kept once, in the namespace that refers to it most.
454fn deduplicate(mut ir: Ir) -> Ir {
455    // groups of structurally identical types: (name, normalized kind) → copies
456    let mut groups: Vec<((String, TypeKind), Vec<(String, TypeDef)>)> = Vec::new();
457    let mut by_name: HashMap<String, Vec<usize>> = HashMap::new();
458    for (full, td) in std::mem::take(&mut ir.types) {
459        let key = (td.name.clone(), td.kind.clone().map_refs(&strip_namespace));
460        let slot = by_name.get(&td.name).and_then(|ix| ix.iter().copied().find(|&i| groups[i].0 == key));
461        match slot {
462            Some(i) => groups[i].1.push((full, td)),
463            None => {
464                by_name.entry(td.name.clone()).or_default().push(groups.len());
465                groups.push((key, vec![(full, td)]));
466            }
467        }
468    }
469    let contested: HashSet<(String, String)> = groups
470        .iter()
471        .filter(|(_, g)| g.len() > 1)
472        .flat_map(|(_, g)| g.iter().map(|(_, td)| (td.namespace.clone(), td.name.clone())))
473        .collect();
474    let counts = ref_counts(&contested, &ir, &groups);
475    let mut redirects: HashMap<String, String> = HashMap::new();
476    let mut canonical: Vec<(String, TypeDef)> = Vec::new();
477    for (_, group) in groups {
478        let at = select_canonical(&counts, &group);
479        let name = group[at].0.clone();
480        for (old, _) in &group {
481            if *old != name {
482                redirects.insert(old.clone(), name.clone());
483            }
484        }
485        let td = group.into_iter().nth(at).expect("the canonical copy").1;
486        canonical.push((name, td));
487    }
488    let update = |t: TypeRef| update_ref(&redirects, t);
489    ir.types = canonical.into_iter().map(|(k, td)| (k, TypeDef { kind: td.kind.map_refs(&update), ..td })).collect();
490    for md in ir.methods.values_mut() {
491        for p in md.params.iter_mut() {
492            p.ty = update(std::mem::replace(&mut p.ty, TypeRef::Unknown));
493        }
494        md.returns = update(std::mem::replace(&mut md.returns, TypeRef::Unknown));
495        md.error = md.error.take().map(update);
496        md.progress = md.progress.take().map(update);
497        md.bidir_type = md.bidir_type.take().map(update);
498        md.input = md.input.take().map(update);
499    }
500    ir
501}
502
503/// How often each contested type is named, by (namespace, name): in every
504/// method's params, returns, error, progress, input and bidirectional type,
505/// and every type's fields, before deduplication.
506fn ref_counts(contested: &HashSet<(String, String)>, ir: &Ir, groups: &[((String, TypeKind), Vec<(String, TypeDef)>)]) -> HashMap<(String, String), usize> {
507    let mut counts = HashMap::new();
508    if contested.is_empty() {
509        return counts;
510    }
511    fn keys<'a>(t: &'a TypeRef, out: &mut Vec<&'a QualifiedName>) {
512        match t {
513            TypeRef::Named(qn) => out.push(qn),
514            other => other.children().into_iter().for_each(|c| keys(c, out)),
515        }
516    }
517    let mut names: Vec<&QualifiedName> = Vec::new();
518    for md in ir.methods.values() {
519        for p in &md.params {
520            keys(&p.ty, &mut names);
521        }
522        keys(&md.returns, &mut names);
523        for t in [&md.error, &md.progress, &md.input, &md.bidir_type].into_iter().flatten() {
524            keys(t, &mut names);
525        }
526    }
527    for (_, group) in groups {
528        for (_, td) in group {
529            match &td.kind {
530                TypeKind::Struct { fields } => fields.iter().for_each(|f| keys(&f.ty, &mut names)),
531                TypeKind::Enum { variants, .. } => {
532                    for v in variants {
533                        v.fields.iter().for_each(|f| keys(&f.ty, &mut names));
534                        if let Some(r) = &v.vref {
535                            keys(r, &mut names);
536                        }
537                    }
538                }
539                TypeKind::Alias { target } => keys(target, &mut names),
540                _ => {}
541            }
542        }
543    }
544    for qn in names {
545        let k = (qn.namespace.clone(), qn.local.clone());
546        if contested.contains(&k) {
547            *counts.entry(k).or_insert(0) += 1;
548        }
549    }
550    counts
551}
552
553/// The copy in the namespace that refers to it most; a tie to the namespace
554/// that is an ancestor of every other tied one, then the shortest name, then
555/// alphabetical order; the root `""` never when a generated namespace has
556/// a copy.
557fn select_canonical(counts: &HashMap<(String, String), usize>, group: &[(String, TypeDef)]) -> usize {
558    if group.len() == 1 {
559        return 0;
560    }
561    let generated: Vec<usize> = (0..group.len()).filter(|&i| !group[i].1.namespace.is_empty()).collect();
562    let candidates: Vec<usize> = if generated.is_empty() { (0..group.len()).collect() } else { generated };
563    let count_of = |i: usize| counts.get(&(group[i].1.namespace.clone(), group[i].1.name.clone())).copied().unwrap_or(0);
564    let best = candidates.iter().map(|&i| count_of(i)).max().unwrap_or(0);
565    let tied: Vec<usize> = candidates.into_iter().filter(|&i| count_of(i) == best).collect();
566    let ns = |i: usize| group[i].1.namespace.as_str();
567    let ancestor_of_all = |c: usize| tied.iter().all(|&o| ns(o) == ns(c) || ns(o).starts_with(&format!("{}.", ns(c))));
568    if let Some(&c) = tied.iter().find(|&&c| ancestor_of_all(c)) {
569        return c;
570    }
571    *tied.iter().min_by(|&&a, &&b| (ns(a).chars().count(), ns(a)).cmp(&(ns(b).chars().count(), ns(b)))).expect("a tied copy")
572}
573
574/// synapse's `parseQualifiedName`: split at the last dot.
575fn parse_qualified_name(t: &str) -> Option<QualifiedName> {
576    let i = t.rfind('.')?;
577    let local = &t[i + 1..];
578    if local.is_empty() {
579        return None;
580    }
581    Some(QualifiedName { namespace: t[..i].to_string(), local: local.to_string() })
582}
583
584/// A ref to its canonical name — every named ref re-parsed from its full
585/// name, as synapse's `updateTypeRef` does.
586fn update_ref(redirects: &HashMap<String, String>, t: TypeRef) -> TypeRef {
587    t.map(&|t| match t {
588        TypeRef::Named(qn) => {
589            let full = qn.key();
590            let canonical = redirects.get(&full).cloned().unwrap_or(full);
591            match parse_qualified_name(&canonical) {
592                Some(q) => TypeRef::Named(q),
593                None => TypeRef::Named(qn),
594            }
595        }
596        other => other,
597    })
598}
599
600/// Every named ref that names no type becomes `RefUnknown`: one naming a
601/// type the reader refused needs nothing more; any other is refused at its
602/// own site.
603fn unknown_where_unnamed(refused: &HashSet<String>, mut ir: Ir) -> (Ir, Vec<Refusal>) {
604    let known: HashSet<String> = ir.types.keys().cloned().collect();
605    fn fix(known: &HashSet<String>, refused: &HashSet<String>, site: &str, t: TypeRef, out: &mut Vec<Refusal>) -> TypeRef {
606        match t {
607            TypeRef::Named(qn) => {
608                let full = qn.key();
609                if known.contains(&full) {
610                    TypeRef::Named(qn)
611                } else {
612                    if !refused.contains(&full) {
613                        out.push(Refusal {
614                            site: site.into(),
615                            keyword: "$ref".into(),
616                            variant: None,
617                            detail: format!("names {full}, which no $defs defines"),
618                        });
619                    }
620                    TypeRef::Unknown
621                }
622            }
623            TypeRef::Array(i) => TypeRef::Array(Box::new(fix(known, refused, &format!("{site}[]"), *i, out))),
624            TypeRef::Optional(i) => TypeRef::Optional(Box::new(fix(known, refused, &format!("{site}?"), *i, out))),
625            TypeRef::Map(i) => TypeRef::Map(Box::new(fix(known, refused, &format!("{site}{{}}"), *i, out))),
626            TypeRef::Refined(i, r) => TypeRef::Refined(Box::new(fix(known, refused, site, *i, out)), r),
627            TypeRef::Tuple(ts) => {
628                TypeRef::Tuple(ts.into_iter().enumerate().map(|(n, x)| fix(known, refused, &format!("{site}.{n}"), x, out)).collect())
629            }
630            other => other,
631        }
632    }
633    let mut out = Vec::new();
634    let fields = |site: &str, fs: Vec<FieldDef>, out: &mut Vec<Refusal>| -> Vec<FieldDef> {
635        fs.into_iter()
636            .map(|f| {
637                let ty = fix(&known, refused, &format!("{site}.{}", f.name), f.ty.clone(), out);
638                FieldDef { ty, ..f }
639            })
640            .collect()
641    };
642    let types = std::mem::take(&mut ir.types);
643    let mut fixed_types = BTreeMap::new();
644    for (name, td) in types {
645        let kind = match td.kind {
646            TypeKind::Struct { fields: fs } => TypeKind::Struct { fields: fields(&name, fs, &mut out) },
647            TypeKind::Enum { discriminator, variants, repr } => {
648                let variants = variants
649                    .into_iter()
650                    .map(|v| {
651                        let vsite = format!("{name}.{}", v.name);
652                        let fs = fields(&vsite, v.fields, &mut out);
653                        let vref = v.vref.map(|x| fix(&known, refused, &vsite, x, &mut out));
654                        VariantDef { fields: fs, vref, name: v.name, description: v.description }
655                    })
656                    .collect();
657                TypeKind::Enum { discriminator, variants, repr }
658            }
659            TypeKind::Alias { target } => TypeKind::Alias { target: fix(&known, refused, &name, target, &mut out) },
660            other => other,
661        };
662        fixed_types.insert(name, TypeDef { kind, ..td });
663    }
664    ir.types = fixed_types;
665    for md in ir.methods.values_mut() {
666        let path = md.full_path.clone();
667        for p in md.params.iter_mut() {
668            let ty = std::mem::replace(&mut p.ty, TypeRef::Unknown);
669            p.ty = fix(&known, refused, &read::site_param(&path, &p.name), ty, &mut out);
670        }
671        let ret = std::mem::replace(&mut md.returns, TypeRef::Unknown);
672        md.returns = fix(&known, refused, &read::site_returns(&path), ret, &mut out);
673        md.error = md.error.take().map(|t| fix(&known, refused, &read::site_error(&path), t, &mut out));
674        md.progress = md.progress.take().map(|t| fix(&known, refused, &read::site_progress(&path), t, &mut out));
675        md.input = md.input.take().map(|t| fix(&known, refused, &read::site_input(&path), t, &mut out));
676    }
677    (ir, out)
678}