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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
//! Canonical Workshop name lookup: display names, near spellings, and
//! settings paths resolve to the catalog entries, preset strings, 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, EnumDomain, Kind, Locale};
use crate::core::error::{Result, WorkshopError};
use crate::core::suggest;
use crate::settings::{self, PathPart, SettingDefinition, SettingValueDomain, table};
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 preset localized string identity from the catalog's
/// `localizedStrings` table — the id a `{"localizedString": id}`
/// rule-content node or a `Value::LocalizedString` carries.
LocalizedString {
/// The canonical id (`hello`, `goodbye`).
id: String,
/// The display name in the requested locale, when mapped — the
/// spelling the emitter writes for that locale.
display_name: Option<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>> {
self.check_locale(locale)?;
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, self.builtin_match(entry, locale)));
}
}
for entry in &self.localized_strings {
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::LocalizedString {
id: entry.id.clone(),
display_name: entry.spelling(locale).map(String::from),
},
));
}
}
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, self.enum_domain_match(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,
},
));
}
}
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>> {
self.check_locale(locale)?;
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())
}
/// Every entry of a listable `kind` under `locale` — one
/// [`LookupMatch`] per catalog entry of the kind, in catalog order,
/// with no query, matching, or ranking.
///
/// `Kind::Action`, `Kind::Value`, and `Kind::Event` list one
/// [`LookupMatch::Builtin`] per entry — the same match
/// [`Catalog::lookup`] builds for that entry, signature included.
/// `Kind::Enum` lists one [`LookupMatch::EnumDomain`] per declared
/// enum domain, in [`Catalog::enum_domains`] order. Enum members and
/// call parameters are scoped children that already list through
/// [`Catalog::lookup_within`]; the other kinds have no listing
/// surface, and naming one is an `Err`.
///
/// `Err` reports a locale the catalog does not declare or a `kind`
/// with no listing surface. The result is the complete listable
/// vocabulary of the kind: paging and presentation belong to the
/// consumer.
///
/// ```
/// use workshop_rs::catalog::{Catalog, Kind, Locale};
/// use workshop_rs::lookup::LookupMatch;
///
/// let catalog = Catalog::builtin().unwrap();
/// let events = catalog
/// .lookup_entries(&Locale::new("en-US"), Kind::Event)
/// .unwrap();
/// assert!(events.iter().all(
/// |m| matches!(m, LookupMatch::Builtin { kind: Kind::Event, .. })
/// ));
/// ```
pub fn lookup_entries(&self, locale: &Locale, kind: Kind) -> Result<Vec<LookupMatch>> {
self.check_locale(locale)?;
match kind {
Kind::Action | Kind::Value | Kind::Event => Ok(self
.entries_of(kind)
.map(|entry| self.builtin_match(entry, locale))
.collect()),
Kind::Enum => Ok(self
.enum_domains()
.map(|domain| self.enum_domain_match(domain, locale))
.collect()),
Kind::Structural | Kind::Operator | Kind::Setting => Err(WorkshopError::unsupported(
format!(
"listing kind '{}' is not supported: \
the listable kinds are action, value, event, and enum",
kind.as_str()
),
None,
)),
}
}
fn check_locale(&self, locale: &Locale) -> Result<()> {
if self.supports(locale) {
return Ok(());
}
Err(WorkshopError::unsupported(
format!(
"lookup for locale '{locale}' is not supported: \
the catalog does not declare it"
),
None,
))
}
fn builtin_match(&self, entry: &CatalogEntry, locale: &Locale) -> LookupMatch {
LookupMatch::Builtin {
kind: entry.kind,
id: entry.id.clone(),
display_name: entry.spelling(locale).map(String::from),
signature: signature(self, entry, locale),
}
}
fn enum_domain_match(&self, domain: &EnumDomain, locale: &Locale) -> LookupMatch {
LookupMatch::EnumDomain {
domain: domain.domain.clone(),
display_name: domain.spelling(locale).map(String::from),
members: self.enum_members(&domain.domain, locale),
}
}
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(),
)
}
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)
}
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(),
)
}
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()
}
}
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 ¶ms {
let Some(domain) = ¶m.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, ¶ms),
params,
required_params: entry.required_param_count(),
variadic: entry.is_variadic(),
return_type: entry.return_type().map(String::from),
domains,
})
}
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 ¶m.default {
Some(default) if default == "null" => format!("{}?", param.name),
Some(default) => format!(
"{}={}",
param.name,
render_default(catalog, locale, default)
),
None => match ¶m.domain {
Some(domain) => {
let Some(domain_entry) = catalog.enum_domain(domain) else {
match ¶m.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 ¶m.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(", "))
}
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()
}
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)
}
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(),
}
}
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() {
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)
}
struct PreparedQuery {
raw: String,
folded: String,
folded_chars: Vec<char>,
tokens: Vec<String>,
max_distance: usize,
/// The folded length at which token-prefix and substring matching
/// start. A script without word spacing carries a whole word in two
/// characters (`阈值`, `スロットル`), so its queries match loosely at
/// two; word-spaced queries keep three, so a two-letter ASCII query
/// does not flood the results.
loose_min_chars: usize,
}
impl PreparedQuery {
fn new(query: &str) -> Self {
let folded = suggest::fold_loose(query);
let folded_chars: Vec<char> = folded.chars().collect();
let loose_min_chars = if folded_chars
.iter()
.any(|&character| is_unspaced_script(character))
{
2
} else {
3
};
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(),
loose_min_chars,
}
}
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() >= self.loose_min_chars {
if self.token_prefix_match(candidate) {
return Some(6);
}
if candidate_folded.contains(&self.folded) {
return Some(8);
}
}
None
}
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))
})
}
}
/// Whether `character` belongs to a CJK script written without word
/// spacing — unified ideographs, kana, or hangul — where two characters
/// already carry a complete word.
fn is_unspaced_script(character: char) -> bool {
matches!(
character,
'\u{1100}'..='\u{11FF}' // Hangul Jamo
| '\u{3040}'..='\u{309F}' // Hiragana
| '\u{30A0}'..='\u{30FF}' // Katakana
| '\u{3400}'..='\u{4DBF}' // CJK Unified Ideographs Extension A
| '\u{4E00}'..='\u{9FFF}' // CJK Unified Ideographs
| '\u{AC00}'..='\u{D7AF}' // Hangul Syllables
| '\u{F900}'..='\u{FAFF}' // CJK Compatibility Ideographs
| '\u{FF66}'..='\u{FF9D}' // Halfwidth katakana
)
}
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)
}
}
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)
}