workshop-rs 1.7.0

Canonical multi-locale Overwatch Workshop semantic core: catalog, parser, WIR, validation, emitter.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
//! Canonical Workshop name lookup: display names, near spellings, and
//! settings paths resolve to the catalog entries, enum members, and settings
//! definitions the parser and emitter accept.
//!
//! [`Catalog::lookup`] answers in canonical Workshop terms: which identity a
//! display name or guess refers to, which parameters and argument domains an
//! action or value declares, which members an enum domain accepts, and which
//! settings keys, kinds, and value forms a path or display name selects.
//! Every answer derives from the same catalog and settings table that drive
//! parsing and emission, so lookup results cannot drift from the accepted
//! vocabulary. Consumers compose and present the matches; this module owns
//! no data of its own.

use crate::catalog::{Catalog, CatalogEntry, Kind, Locale};
use crate::core::error::{Result, WorkshopError};
use crate::core::suggest;
use crate::settings::{self, PathPart, SettingDefinition, SettingValueDomain, table};

/// Members of a parameter's enum domain are listed inline in a signature
/// when the domain has at most this many members. Larger domains report
/// their member count; a query on the domain itself lists them.
const INLINE_MEMBER_LIMIT: usize = 32;

/// One canonical construct matching a [`Catalog::lookup`] query.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum LookupMatch {
    /// A catalog builtin: structural keyword, action, value, event, or
    /// operator.
    Builtin {
        /// The entry's catalog kind.
        kind: Kind,
        /// The canonical identity (`createHudText`, `global`).
        id: String,
        /// The display name in the requested locale, when mapped.
        display_name: Option<String>,
        /// The call signature, for actions and values.
        signature: Option<Signature>,
    },
    /// A member of a canonical enum domain (`Team.ALL`, `Hero.SOLDIER_76`).
    EnumMember {
        /// The canonical domain name.
        domain: String,
        /// The canonical member id.
        member: String,
        /// The member's display name in the requested locale, when mapped.
        display_name: Option<String>,
    },
    /// A canonical enum domain and the members it accepts.
    EnumDomain {
        /// The canonical domain name.
        domain: String,
        /// The domain's display name in the requested locale, when mapped.
        display_name: Option<String>,
        /// Every member the domain accepts.
        members: Vec<LookupEnumMember>,
    },
    /// A reviewed settings-table definition: a valid key with its path,
    /// kind, and value forms.
    Setting {
        /// The canonical semantic definition.
        definition: SettingDefinition,
        /// The display name in the requested locale, or the English name
        /// when the locale has no mapping.
        display_name: String,
    },
    /// A parameter of a scoped callable, in call order. Returned only by
    /// [`Catalog::lookup_within`]; an unscoped [`Catalog::lookup`] never
    /// answers parameters.
    Parameter {
        /// The callable's canonical id.
        callable: String,
        /// The parameter's position in call order.
        position: usize,
        /// Whether the position must be supplied.
        required: bool,
        /// The parameter facts: name, declared type, domain, and default.
        param: SignatureParam,
        /// The enum domain this parameter accepts, with the members it
        /// accepts, when the parameter is enum-typed.
        domain: Option<SignatureDomain>,
    },
    /// The next path segment below a scoped settings prefix — an
    /// intermediate selector such as `<team>` or `general`, not a leaf
    /// key. Returned only by [`Catalog::lookup_within`].
    SettingPath {
        /// The full child path under the scoped prefix (`heroes.<team>`).
        path: String,
        /// The segment text (`<team>`, `general`).
        segment: String,
    },
}

/// A canonical enum member reported by a lookup.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct LookupEnumMember {
    /// The canonical member id (`SOLDIER_76`, `ALL`).
    pub id: String,
    /// The member's display name in the requested locale, when mapped.
    pub display_name: Option<String>,
}

/// An enum domain referenced by a [`Signature`] parameter, with the members
/// it accepts.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct SignatureDomain {
    /// The canonical domain name.
    pub domain: String,
    /// Every member the domain accepts.
    pub members: Vec<LookupEnumMember>,
}

/// A compact signature for a catalog action or value.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Signature {
    /// The signature rendered in the requested locale's call syntax:
    /// parameters appear in call order, a parameter without a declared
    /// default reads `name: Type`, a parameter with a declared default reads
    /// `name=default` or `name?` when the default is null, and an enum-typed
    /// parameter without a default reads `name: Domain(members)` listing the
    /// domain's members once per signature when it has at most
    /// 32 members, or `name: Domain(count members)` for a larger domain.
    pub text: String,
    /// Parameters in call order.
    pub params: Vec<SignatureParam>,
    /// The argument count a call must supply: positions below this index
    /// cannot be omitted; declared defaults only make the suffix optional.
    pub required_params: usize,
    /// Whether the final parameter repeats for extra arguments.
    pub variadic: bool,
    /// The source-backed return type for values, when declared.
    pub return_type: Option<String>,
    /// The enum domains referenced by parameters, each with the members it
    /// accepts, for follow-up inspection of large domains.
    pub domains: Vec<SignatureDomain>,
}

/// One parameter of a [`Signature`].
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct SignatureParam {
    /// The semantic parameter name, or the catalog parameter name.
    pub name: String,
    /// The source-backed semantic type, when declared.
    pub param_type: Option<String>,
    /// The canonical enum domain expected at this position, when declared.
    pub domain: Option<String>,
    /// The declared default applied when the argument is omitted. `None`
    /// marks a parameter with no declared default; a declared default before
    /// another required position does not make this position omittable (see
    /// [`Signature::required_params`]).
    pub default: Option<String>,
}

impl Catalog {
    /// Find canonical constructs matching `query` under `locale`.
    ///
    /// `query` may be a display name in `locale`, a primary-locale display
    /// name, a canonical id, a near spelling or guess, or a settings path
    /// prefix (`gamemodes.control`, `heroes.<team>.<hero>`). Matches rank
    /// exact spellings first, then near spellings, token prefixes, and
    /// substring guesses; ties keep catalog and table order. All matches are
    /// canonical constructs the parser and emitter accept, with the display
    /// name in `locale` and, for actions and values, the compact signature.
    ///
    /// An empty result reports that nothing matched. `Err` reports a query
    /// the catalog cannot answer: a locale the catalog does not declare.
    ///
    /// ```
    /// use workshop_rs::catalog::{Catalog, Locale};
    /// use workshop_rs::lookup::LookupMatch;
    ///
    /// let catalog = Catalog::builtin().unwrap();
    /// let matches = catalog.lookup(&Locale::new("en-US"), "create hud txt").unwrap();
    /// assert!(matches.iter().any(|m| matches!(
    ///     m,
    ///     LookupMatch::Builtin { id, .. } if id == "createHudText"
    /// )));
    /// ```
    pub fn lookup(&self, locale: &Locale, query: &str) -> Result<Vec<LookupMatch>> {
        if !self.supports(locale) {
            return Err(WorkshopError::unsupported(
                format!(
                    "lookup for locale '{locale}' is not supported: \
                     the catalog does not declare it"
                ),
                None,
            ));
        }
        let primary = self.primary_locale();
        let distinct_locale = locale != primary;
        let prepared = PreparedQuery::new(query);
        let query_segments: Vec<&str> = query.split('.').collect();
        let mut matches: Vec<(u32, LookupMatch)> = Vec::new();
        for entry in &self.entries {
            let primary_spellings: &[String] = if distinct_locale {
                entry.spellings(primary)
            } else {
                &[]
            };
            let score = std::iter::once(entry.id.as_str())
                .chain(entry.spellings(locale).iter().map(String::as_str))
                .chain(primary_spellings.iter().map(String::as_str))
                .filter_map(|text| prepared.name_score(text))
                .min();
            if let Some(score) = score {
                matches.push((
                    score,
                    LookupMatch::Builtin {
                        kind: entry.kind,
                        id: entry.id.clone(),
                        display_name: entry.spelling(locale).map(String::from),
                        signature: signature(self, entry, locale),
                    },
                ));
            }
        }
        for domain in self.enum_domains() {
            let score = std::iter::once(domain.domain.as_str())
                .chain(domain.spelling(locale))
                .chain(domain.spelling(primary).filter(|_| distinct_locale))
                .filter_map(|text| prepared.name_score(text))
                .min();
            if let Some(score) = score {
                matches.push((
                    score,
                    LookupMatch::EnumDomain {
                        domain: domain.domain.clone(),
                        display_name: domain.spelling(locale).map(String::from),
                        members: self.enum_members(&domain.domain, locale),
                    },
                ));
            }
        }
        for domain in self.enum_domains() {
            for member in &domain.members {
                let qualified = format!("{}.{}", domain.domain, member.member);
                let primary_spellings: &[String] = if distinct_locale {
                    member.spellings(primary)
                } else {
                    &[]
                };
                let score = std::iter::once(member.member.as_str())
                    .chain(std::iter::once(qualified.as_str()))
                    .chain(member.spellings(locale).iter().map(String::as_str))
                    .chain(primary_spellings.iter().map(String::as_str))
                    .filter_map(|text| prepared.name_score(text))
                    .min();
                if let Some(score) = score {
                    matches.push((
                        score,
                        LookupMatch::EnumMember {
                            domain: domain.domain.clone(),
                            member: member.member.clone(),
                            display_name: self
                                .enum_spelling(&domain.domain, locale, &member.member)
                                .map(String::from),
                        },
                    ));
                }
            }
        }
        for definition in settings::definitions() {
            let name_texts = [
                Some(definition.path().rsplit('.').next().unwrap_or_default()),
                Some(definition.presentation().english_name),
                definition.presentation().localized_name(locale.as_str()),
                definition.id().map(|id| id.as_str()),
                Some(definition.path()),
            ];
            let score = name_texts
                .into_iter()
                .flatten()
                .filter_map(|text| prepared.name_score(text))
                .min()
                .into_iter()
                .chain(path_prefix_score(&query_segments, definition.path()))
                .min();
            if let Some(score) = score {
                matches.push((
                    score,
                    LookupMatch::Setting {
                        display_name: definition
                            .presentation()
                            .localized_name(locale.as_str())
                            .unwrap_or(definition.presentation().english_name)
                            .to_string(),
                        definition,
                    },
                ));
            }
        }
        // Stable sort: equal-ranked matches keep catalog and table order.
        matches.sort_by_key(|(score, _)| *score);
        Ok(matches.into_iter().map(|(_, lookup)| lookup).collect())
    }

    /// The entries `within` contains under `locale` — the members of an
    /// enum domain, the parameters of a callable, or the settings keys
    /// and segments under a path prefix — optionally filtered and ranked
    /// by `query` with the same matcher an unscoped [`Catalog::lookup`]
    /// uses.
    ///
    /// `within` resolves in a fixed order: an enum domain (catalog or
    /// settings-table), an action or value id or `locale` spelling, then
    /// a settings path prefix. Template segments (`<team>`, `<hero>`)
    /// accept their own template spelling or a canonical team/hero key
    /// the settings table recognizes — never an arbitrary value — so a
    /// literal path stays literal (`heroes.general` lists only the
    /// `general` group's children). With no `query`, or an
    /// empty one, children keep the scope's own order — domain order for
    /// members, call order for parameters, table order for settings — and
    /// a non-empty query filters and ranks them by the same scoring an
    /// unscoped lookup applies to its candidates.
    ///
    /// `Err` reports a locale the catalog does not declare or a `within`
    /// naming no known scope; an empty result reports a scope whose
    /// children do not match `query`.
    ///
    /// ```
    /// use workshop_rs::catalog::{Catalog, Locale};
    /// use workshop_rs::lookup::LookupMatch;
    ///
    /// let catalog = Catalog::builtin().unwrap();
    /// let members = catalog
    ///     .lookup_within(&Locale::new("en-US"), "Team", None)
    ///     .unwrap();
    /// assert!(members.iter().all(|m| matches!(m, LookupMatch::EnumMember { domain, .. } if domain == "Team")));
    /// ```
    pub fn lookup_within(
        &self,
        locale: &Locale,
        within: &str,
        query: Option<&str>,
    ) -> Result<Vec<LookupMatch>> {
        if !self.supports(locale) {
            return Err(WorkshopError::unsupported(
                format!(
                    "lookup for locale '{locale}' is not supported: \
                     the catalog does not declare it"
                ),
                None,
            ));
        }
        let prepared = query
            .filter(|query| !query.is_empty())
            .map(PreparedQuery::new);
        let mut scored = self
            .within_enum_domain(locale, within, prepared.as_ref())
            .or_else(|| self.within_settings_enum(locale, within, prepared.as_ref()))
            .or_else(|| self.within_callable(locale, within, prepared.as_ref()))
            .or_else(|| within_settings(within, locale, prepared.as_ref()))
            .ok_or_else(|| WorkshopError::unknown("lookup scope", within, locale.clone(), None))?;
        if prepared.is_some() {
            scored.retain(|(score, _)| *score != u32::MAX);
            scored.sort_by_key(|(score, _)| *score);
        }
        Ok(scored.into_iter().map(|(_, lookup)| lookup).collect())
    }

    /// The members of one catalog enum domain — `value` a canonical domain
    /// name or a `locale` spelling — scored against `prepared` when given.
    fn within_enum_domain(
        &self,
        locale: &Locale,
        value: &str,
        prepared: Option<&PreparedQuery>,
    ) -> Option<Vec<(u32, LookupMatch)>> {
        let domain = if self.enum_domain(value).is_some() {
            Some(value.to_string())
        } else {
            self.resolve_enum_domain(locale, value).map(str::to_string)
        }?;
        let domain = self.enum_domain(&domain)?;
        let primary = self.primary_locale();
        let distinct_locale = locale != primary;
        Some(
            domain
                .members
                .iter()
                .map(|member| {
                    let qualified = format!("{}.{}", domain.domain, member.member);
                    let mut texts = vec![member.member.as_str(), qualified.as_str()];
                    texts.extend(member.spellings(locale).iter().map(String::as_str));
                    if distinct_locale {
                        texts.extend(member.spellings(primary).iter().map(String::as_str));
                    }
                    (
                        child_score(prepared, texts.into_iter()),
                        LookupMatch::EnumMember {
                            domain: domain.domain.clone(),
                            member: member.member.clone(),
                            display_name: self
                                .enum_spelling(&domain.domain, locale, &member.member)
                                .map(String::from),
                        },
                    )
                })
                .collect(),
        )
    }

    /// The members of one settings-table enum domain — `value` a domain
    /// name such as `mapRotation` — scored against `prepared` when given.
    /// Member spellings in `locale` match and surface as the display name
    /// the same way catalog enum members do.
    fn within_settings_enum(
        &self,
        locale: &Locale,
        value: &str,
        prepared: Option<&PreparedQuery>,
    ) -> Option<Vec<(u32, LookupMatch)>> {
        let mut seen = std::collections::HashSet::new();
        let mut members = Vec::new();
        for definition in settings::definitions() {
            let SettingValueDomain::Enum { domain } = definition.domain() else {
                continue;
            };
            if domain.as_str() != value {
                continue;
            }
            for member in definition.enum_members() {
                if !seen.insert((member.domain().to_string(), member.id().to_string())) {
                    continue;
                }
                let localized =
                    table::localized_name(locale.as_str(), "enums", member.english_name());
                let qualified = format!("{}.{}", member.domain(), member.id());
                members.push((
                    child_score(
                        prepared,
                        [
                            member.id(),
                            qualified.as_str(),
                            member.english_name(),
                            localized.unwrap_or_default(),
                        ]
                        .into_iter(),
                    ),
                    LookupMatch::EnumMember {
                        domain: member.domain().to_string(),
                        member: member.id().to_string(),
                        display_name: Some(localized.unwrap_or(member.english_name()).to_string()),
                    },
                ));
            }
        }
        (!members.is_empty()).then_some(members)
    }

    /// The parameters of one callable — `value` a canonical id or a
    /// `locale` spelling — in call order, scored against `prepared` when
    /// given.
    fn within_callable(
        &self,
        locale: &Locale,
        value: &str,
        prepared: Option<&PreparedQuery>,
    ) -> Option<Vec<(u32, LookupMatch)>> {
        let entry = [Kind::Action, Kind::Value].into_iter().find_map(|kind| {
            self.entry(kind, value)
                .or_else(|| self.resolve(kind, locale, value))
        })?;
        let signature = signature(self, entry, locale)?;
        Some(
            signature
                .params
                .iter()
                .enumerate()
                .map(|(position, param)| {
                    let qualified = format!("{}.{}", entry.id, param.name);
                    (
                        child_score(
                            prepared,
                            [param.name.as_str(), qualified.as_str()].into_iter(),
                        ),
                        LookupMatch::Parameter {
                            callable: entry.id.clone(),
                            position,
                            required: position < signature.required_params,
                            param: param.clone(),
                            domain: param.domain.as_ref().and_then(|name| {
                                signature
                                    .domains
                                    .iter()
                                    .find(|domain| &domain.domain == name)
                                    .cloned()
                            }),
                        },
                    )
                })
                .collect(),
        )
    }

    /// The members of `domain` with their display names under `locale`.
    fn enum_members(&self, domain: &str, locale: &Locale) -> Vec<LookupEnumMember> {
        self.enum_domain(domain)
            .map(|domain| {
                domain
                    .members
                    .iter()
                    .map(|member| LookupEnumMember {
                        id: member.member.clone(),
                        display_name: self
                            .enum_spelling(&domain.domain, locale, &member.member)
                            .map(String::from),
                    })
                    .collect()
            })
            .unwrap_or_default()
    }
}

/// The [`Signature`] for a catalog `entry` under `locale`, when the entry is
/// an action or value.
fn signature(catalog: &Catalog, entry: &CatalogEntry, locale: &Locale) -> Option<Signature> {
    if !matches!(entry.kind, Kind::Action | Kind::Value) {
        return None;
    }
    let params: Vec<SignatureParam> = (0..entry.param_count())
        .map(|index| SignatureParam {
            name: entry.param_name(index).unwrap_or_default().to_string(),
            param_type: entry.param_type(index).map(String::from),
            domain: entry.param_domain(index).map(String::from),
            default: entry.param_default(index).map(String::from),
        })
        .collect();
    let mut domains = Vec::new();
    for param in &params {
        let Some(domain) = &param.domain else {
            continue;
        };
        if domains
            .iter()
            .any(|known: &SignatureDomain| known.domain == *domain)
        {
            continue;
        }
        domains.push(SignatureDomain {
            domain: domain.clone(),
            members: catalog.enum_members(domain, locale),
        });
    }
    Some(Signature {
        text: signature_text(catalog, entry, locale, &params),
        params,
        required_params: entry.required_param_count(),
        variadic: entry.is_variadic(),
        return_type: entry.return_type().map(String::from),
        domains,
    })
}

/// Render `entry`'s call signature in `locale`'s call syntax, following the
/// shared signature form: `name: Type` without a declared default,
/// `name=default` or `name?` with one, and `name: Domain(members|count)` for
/// an enum-typed parameter without a default.
fn signature_text(
    catalog: &Catalog,
    entry: &CatalogEntry,
    locale: &Locale,
    params: &[SignatureParam],
) -> String {
    let display = entry.spelling(locale).unwrap_or(entry.id.as_str());
    let mut listed_domains = std::collections::HashSet::new();
    let mut rendered: Vec<String> = Vec::with_capacity(params.len());
    for param in params {
        rendered.push(match &param.default {
            Some(default) if default == "null" => format!("{}?", param.name),
            Some(default) => format!(
                "{}={}",
                param.name,
                render_default(catalog, locale, default)
            ),
            None => match &param.domain {
                Some(domain) => {
                    let Some(domain_entry) = catalog.enum_domain(domain) else {
                        match &param.param_type {
                            Some(param_type) => {
                                rendered.push(format!("{}: {}", param.name, param_type));
                            }
                            None => rendered.push(param.name.clone()),
                        }
                        continue;
                    };
                    let domain_display = domain_entry
                        .spelling(locale)
                        .unwrap_or(domain_entry.domain.as_str());
                    if !listed_domains.insert(domain.clone()) {
                        format!("{}: {}", param.name, domain_display)
                    } else if domain_entry.members.len() <= INLINE_MEMBER_LIMIT {
                        let members = domain_entry
                            .members
                            .iter()
                            .map(|member| {
                                catalog
                                    .enum_spelling(&domain_entry.domain, locale, &member.member)
                                    .unwrap_or(member.member.as_str())
                            })
                            .collect::<Vec<_>>()
                            .join("|");
                        format!("{}: {}({})", param.name, domain_display, members)
                    } else {
                        format!(
                            "{}: {}({} members)",
                            param.name,
                            domain_display,
                            domain_entry.members.len()
                        )
                    }
                }
                None => match &param.param_type {
                    Some(param_type) => format!("{}: {}", param.name, param_type),
                    None => param.name.clone(),
                },
            },
        });
    }
    if entry.is_variadic() {
        rendered.push("...".to_string());
    }
    format!("{}({})", display, rendered.join(", "))
}

/// Render a declared parameter default in `locale`'s call syntax: a
/// `Domain.Member` literal resolves to the localized emitted member form
/// (constructor-form domains write `Domain(Member)`, other domains write
/// the member bare), a canonical value id resolves to its localized
/// spelling, and any other literal stays as declared.
fn render_default(catalog: &Catalog, locale: &Locale, default: &str) -> String {
    if let Some((domain, member)) = default.split_once('.') {
        if let Some(member_spelling) = catalog.enum_spelling(domain, locale, member) {
            return catalog.enum_member_form(domain, member_spelling, locale);
        }
    }
    catalog
        .spelling(Kind::Value, locale, default)
        .unwrap_or(default)
        .to_string()
}

/// The best [`PreparedQuery::name_score`] over `texts`, or `u32::MAX` when
/// there is no prepared query or no text matched; scoped lookups drop
/// `u32::MAX` children only when a query is present.
fn child_score<'a>(prepared: Option<&PreparedQuery>, texts: impl Iterator<Item = &'a str>) -> u32 {
    prepared
        .and_then(|prepared| texts.filter_map(|text| prepared.name_score(text)).min())
        .unwrap_or(u32::MAX)
}

/// Whether one declared path segment accepts the asked `within` segment:
/// a literal key matches exactly; a `<team>`/`<hero>` template slot
/// accepts its own template spelling or a canonical team/hero key the
/// settings table recognizes (`allTeams`, `team1`, `mei`), never an
/// arbitrary value.
fn declared_segment_accepts(declared: PathPart<'_>, asked: &str) -> bool {
    match declared {
        PathPart::Part(name) => name == asked,
        PathPart::Team => asked == "<team>" || table::team_name(asked).is_some(),
        PathPart::Hero => asked == "<hero>" || table::hero_name(asked).is_some(),
    }
}

/// The immediate settings children under `prefix`: leaf keys and the next
/// path segment, matched segment by segment against the canonical paths.
/// An empty `prefix` lists the root. `None` reports a prefix naming no
/// known scope.
fn within_settings(
    prefix: &str,
    locale: &Locale,
    prepared: Option<&PreparedQuery>,
) -> Option<Vec<(u32, LookupMatch)>> {
    let prefix_segments: Vec<&str> = if prefix.is_empty() {
        Vec::new()
    } else {
        prefix.split('.').collect()
    };
    let mut seen = std::collections::HashSet::new();
    let mut children = Vec::new();
    let mut known = prefix.is_empty();
    for definition in settings::definitions() {
        let parts = definition.path_parts();
        if parts.len() < prefix_segments.len() {
            continue;
        }
        let matches_prefix = prefix_segments
            .iter()
            .zip(parts.iter())
            .all(|(asked, declared)| declared_segment_accepts(*declared, asked));
        if !matches_prefix {
            continue;
        }
        known = true;
        if parts.len() == prefix_segments.len() {
            // The prefix names this leaf itself — an existing but empty
            // scope, not an unknown one.
            continue;
        }
        let segment = match &parts[prefix_segments.len()] {
            PathPart::Part(name) => *name,
            PathPart::Team => "<team>",
            PathPart::Hero => "<hero>",
        };
        let child_path = if prefix.is_empty() {
            segment.to_string()
        } else {
            format!("{prefix}.{segment}")
        };
        if parts.len() == prefix_segments.len() + 1 {
            if !seen.insert(definition.path().to_string()) {
                continue;
            }
            let texts = [
                Some(definition.path().rsplit('.').next().unwrap_or_default()),
                Some(definition.presentation().english_name),
                definition.presentation().localized_name(locale.as_str()),
                definition.id().map(|id| id.as_str()),
                Some(definition.path()),
            ];
            children.push((
                child_score(prepared, texts.into_iter().flatten()),
                LookupMatch::Setting {
                    display_name: definition
                        .presentation()
                        .localized_name(locale.as_str())
                        .unwrap_or(definition.presentation().english_name)
                        .to_string(),
                    definition,
                },
            ));
        } else if seen.insert(child_path.clone()) {
            children.push((
                child_score(prepared, [segment, child_path.as_str()].into_iter()),
                LookupMatch::SettingPath {
                    path: child_path,
                    segment: segment.to_string(),
                },
            ));
        }
    }
    known.then_some(children)
}

/// A lookup query prepared once for comparison against every candidate:
/// the raw text, its comparison fold, and its folded tokens.
struct PreparedQuery {
    raw: String,
    folded: String,
    folded_chars: Vec<char>,
    tokens: Vec<String>,
    max_distance: usize,
}

impl PreparedQuery {
    fn new(query: &str) -> Self {
        let folded = suggest::fold_loose(query);
        let folded_chars: Vec<char> = folded.chars().collect();
        Self {
            raw: query.to_string(),
            max_distance: suggest::max_distance(folded_chars.len()),
            folded,
            folded_chars,
            tokens: query
                .split(|character: char| !character.is_alphanumeric())
                .map(suggest::fold_loose)
                .filter(|token| !token.is_empty())
                .collect(),
        }
    }

    /// How closely the query resembles `candidate`: exact equality ranks 0,
    /// a comparison-fold equality (case, accents, punctuation, and
    /// whitespace are insignificant) ranks 1, a small edit distance ranks
    /// 2 + distance, a token prefix match ranks 6, and a substring guess
    /// ranks 8. Guesses shorter than three folded characters only rank on
    /// exact or near forms so that vague queries do not flood the result.
    fn name_score(&self, candidate: &str) -> Option<u32> {
        if self.raw == candidate {
            return Some(0);
        }
        let candidate_folded = fold_candidate(candidate);
        if self.folded.is_empty() || candidate_folded.is_empty() {
            return None;
        }
        if self.folded == candidate_folded {
            return Some(1);
        }
        if candidate_folded
            .chars()
            .count()
            .abs_diff(self.folded_chars.len())
            <= self.max_distance
        {
            let candidate_chars: Vec<char> = candidate_folded.chars().collect();
            let distance =
                suggest::edit_distance(&self.folded_chars, &candidate_chars, self.max_distance);
            if distance <= self.max_distance {
                return Some(2 + distance as u32);
            }
        }
        if self.folded_chars.len() >= 3 {
            if self.token_prefix_match(candidate) {
                return Some(6);
            }
            if candidate_folded.contains(&self.folded) {
                return Some(8);
            }
        }
        None
    }

    /// Whether every whitespace/punctuation-separated query token is a
    /// prefix of some `candidate` token (`hud text` matches
    /// `Create HUD Text`, `create hud` matches `Create HUD Text`).
    fn token_prefix_match(&self, candidate: &str) -> bool {
        let candidate_tokens = candidate
            .split(|character: char| !character.is_alphanumeric())
            .map(fold_candidate)
            .filter(|token| !token.is_empty());
        !self.tokens.is_empty()
            && self.tokens.iter().all(|token| {
                candidate_tokens
                    .clone()
                    .any(|candidate| candidate.starts_with(token))
            })
    }
}

/// The [`suggest::fold_loose`] of `candidate`, fast-pathed for ASCII
/// spellings (the overwhelmingly common catalog and table form).
fn fold_candidate(candidate: &str) -> String {
    if candidate.is_ascii() {
        candidate
            .bytes()
            .filter(u8::is_ascii_alphanumeric)
            .map(|byte| char::from(byte.to_ascii_lowercase()))
            .collect()
    } else {
        suggest::fold_loose(candidate)
    }
}

/// Whether `query_segments` prefix-matches `path` segment for segment: a
/// `<team>` or `<hero>` template segment accepts any query segment, and a
/// literal segment accepts a case-insensitive equal query segment. A full
/// match ranks 2; each unmatched trailing path segment lowers the rank.
fn path_prefix_score(query_segments: &[&str], path: &str) -> Option<u32> {
    let mut path_segments = path.split('.');
    let mut consumed = 0usize;
    for segment in query_segments {
        match path_segments.next() {
            Some("<team>") | Some("<hero>") => {}
            Some(part) if part.eq_ignore_ascii_case(segment) => {}
            _ => return None,
        }
        consumed += 1;
    }
    let depth = path.matches('.').count() + 1;
    Some(2 + (depth - consumed) as u32)
}