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
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
//! OPY vocabulary lookup: display names and guesses resolve to OPY spellings,
//! parameter facts, enum members, and settings keys through the same manifest,
//! catalog, and settings tables `check`/`compile` resolve against.
//!
//! This module is the answer surface for agents; it owns no data of its own.
//! Callable spellings and parameter facts come from the compatibility manifest,
//! enum members and display names come from the `workshop-rs` catalog, and
//! settings vocabulary comes from the `workshop-rs` emission table (which it
//! expands to every effective path, including inherited per-mode keys).
//! The same scoring helpers feed the candidate lists unknown-name diagnostics
//! carry, so lookup results and rejection diagnostics cannot drift.
use serde::Serialize;
use workshop_rs::catalog::{Catalog, Kind};
use workshop_rs::settings::{self, PathPart, SettingValueDomain};
use crate::manifest::{
AliasKind, Function, FunctionKind, Manifest, Param, ParamDefault, ReceiverCategory,
};
/// The default bound on returned hits; also the diagnostic candidate bound.
pub const DEFAULT_LIMIT: usize = 8;
/// A source-level special form: a call name the lowerer handles by name
/// rather than through the manifest (`crate::lower::expressions`). Their
/// parameter facts mirror the reference's declared signatures — the same
/// `(name, type, required, default)` facts manifest-backed callables report.
struct SpecialFunction {
name: &'static str,
params: &'static [SpecialParam],
}
/// One ordered parameter of a special call, from the reference signature.
struct SpecialParam {
name: &'static str,
/// The reference's declared argument type (`IntLiteral`, `Lambda`, …).
param_type: &'static str,
required: bool,
/// The declared default rendered in source syntax, when declared.
default: Option<&'static str>,
}
const fn required(name: &'static str, param_type: &'static str) -> SpecialParam {
SpecialParam {
name,
param_type,
required: true,
default: None,
}
}
const fn defaulted(
name: &'static str,
param_type: &'static str,
default: &'static str,
) -> SpecialParam {
SpecialParam {
name,
param_type,
required: false,
default: Some(default),
}
}
const fn optional(name: &'static str, param_type: &'static str) -> SpecialParam {
SpecialParam {
name,
param_type,
required: false,
default: None,
}
}
/// The special-call spellings an `unknown-value` diagnostic can suggest and
/// the lookup can describe, with the parameter facts the reference declares.
const SPECIAL_FUNCTIONS: &[SpecialFunction] = &[
SpecialFunction {
name: "sorted",
params: &[
required("array", "Array"),
// The reference's signature names the slot `lambda`; `key` is
// the keyword spelling callers write (#437).
optional("key", "Lambda"),
],
},
SpecialFunction {
name: "createWorkshopSetting",
params: &[
required("type", "Type"),
required("category", "CustomStringLiteral"),
required("name", "CustomStringLiteral"),
required("default", "BoolLiteral|IntLiteral|FloatLiteral|HeroLiteral"),
defaulted("sortOrder", "IntLiteral", "0"),
],
},
SpecialFunction {
name: "createWorkshopSettingBool",
params: &[
required("category", "CustomStringLiteral"),
required("name", "CustomStringLiteral"),
required("default", "BoolLiteral"),
defaulted("sortOrder", "IntLiteral", "0"),
],
},
SpecialFunction {
name: "createWorkshopSettingEnum",
params: &[
required("category", "CustomStringLiteral"),
required("name", "CustomStringLiteral"),
required("default", "UnsignedIntLiteral"),
required("options", "Array<CustomStringLiteral>"),
defaulted("sortOrder", "IntLiteral", "0"),
],
},
SpecialFunction {
name: "createWorkshopSettingInt",
params: &[
required("category", "CustomStringLiteral"),
required("name", "CustomStringLiteral"),
required("default", "IntLiteral"),
required("min", "IntLiteral"),
required("max", "IntLiteral"),
defaulted("sortOrder", "IntLiteral", "0"),
],
},
SpecialFunction {
name: "createWorkshopSettingFloat",
params: &[
required("category", "CustomStringLiteral"),
required("name", "CustomStringLiteral"),
required("default", "FloatLiteral"),
required("min", "FloatLiteral"),
required("max", "FloatLiteral"),
defaulted("sortOrder", "IntLiteral", "0"),
],
},
SpecialFunction {
name: "createWorkshopSettingHero",
params: &[
required("category", "CustomStringLiteral"),
required("name", "CustomStringLiteral"),
required("default", "HeroLiteral"),
defaulted("sortOrder", "IntLiteral", "0"),
],
},
];
/// A lookup request.
#[derive(Debug, Clone, PartialEq)]
pub struct LookupQuery {
/// The name or guess to resolve: an OPY spelling, a canonical Workshop
/// id, a Workshop display name, or a settings path prefix. Empty text
/// applies no text constraint and lists the in-scope entries instead of
/// scoring them.
pub text: String,
/// The namespaces the query searches; `LookupScope::ALL` is the default.
/// `within` selects its own namespace when set.
pub scope: LookupScope,
/// Restricts the answer to the children of one named scope instead of
/// searching every candidate in `scope`.
pub within: Option<LookupWithin>,
/// The display-name locale to read; only `en-US` is supported.
/// Localized display names remain `workshop-rs`-owned and are answered
/// as `LookupOutcome::Unsupported`, not silently returned in English.
pub locale: Option<String>,
/// The maximum number of returned hits; `0` selects `DEFAULT_LIMIT`.
pub limit: usize,
}
impl LookupQuery {
/// A query across every namespace.
pub fn new(text: impl Into<String>) -> LookupQuery {
LookupQuery {
text: text.into(),
scope: LookupScope::ALL,
within: None,
locale: None,
limit: 0,
}
}
}
/// The namespaces a query searches.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LookupScope {
/// Callable spellings and parameter facts.
pub functions: bool,
/// Enum domains and members.
pub enums: bool,
/// Settings keys and value forms.
pub settings: bool,
}
impl LookupScope {
/// Every namespace.
pub const ALL: LookupScope = LookupScope {
functions: true,
enums: true,
settings: true,
};
/// Callables only.
pub const FUNCTIONS: LookupScope = LookupScope {
functions: true,
enums: false,
settings: false,
};
/// Enum domains and members only.
pub const ENUMS: LookupScope = LookupScope {
functions: false,
enums: true,
settings: false,
};
/// Settings only.
pub const SETTINGS: LookupScope = LookupScope {
functions: false,
enums: false,
settings: true,
};
fn any(self) -> bool {
self.functions || self.enums || self.settings
}
}
/// A named scope whose children a lookup lists instead of searching every
/// namespace. `text` still filters or ranks the children; each variant names
/// the scope in the vocabulary's own terms.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase", tag = "kind", content = "value")]
pub enum LookupWithin {
/// The parameters of the callable with this OPY spelling, in call order.
Callable(String),
/// The member entries of this OPY enum domain, in domain order.
Enum(String),
/// The settings keys and intermediate path segments directly below this
/// settings path prefix; an empty value lists the root.
Settings(String),
/// The accepted member spellings of a settings enum domain.
SettingEnum(String),
}
impl LookupWithin {
/// The namespace this scope's children belong to.
fn scope(&self) -> LookupScope {
match self {
LookupWithin::Callable(_) => LookupScope::FUNCTIONS,
LookupWithin::Enum(_) | LookupWithin::SettingEnum(_) => LookupScope::ENUMS,
LookupWithin::Settings(_) => LookupScope::SETTINGS,
}
}
}
/// The result of a lookup.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(
rename_all = "camelCase",
rename_all_fields = "camelCase",
tag = "kind"
)]
pub enum LookupOutcome {
/// The query was answered (possibly with no hits when nothing matched).
Matched {
/// The namespaces searched.
scope: LookupScope,
/// The maximum number of hits the bound permitted.
limit: usize,
/// The hits, best matches first.
results: Vec<LookupHit>,
},
/// The `within` selector names no scope the vocabulary knows; the
/// request carried no matches because the scope itself does not exist.
UnknownWithin {
/// The selector that named nothing.
within: LookupWithin,
},
/// The query is valid but the requested capability is not served:
/// nothing was searched.
Unsupported {
/// The namespaces that would have been searched.
scope: LookupScope,
/// Why the query cannot be answered (e.g. localized display names
/// are `workshop-rs`-owned).
reason: String,
},
}
impl LookupOutcome {
/// The hits of a `Matched` outcome, else an empty slice.
pub fn results(&self) -> &[LookupHit] {
match self {
LookupOutcome::Matched { results, .. } => results,
LookupOutcome::UnknownWithin { .. } | LookupOutcome::Unsupported { .. } => &[],
}
}
}
/// Which spelling form a hit matched on.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum MatchKind {
/// The OPY source spelling (e.g. `hudText`, `Hero.SOLDIER`).
OpySpelling,
/// The canonical Workshop id (e.g. `createHudText`).
CatalogId,
/// A Workshop display name (e.g. `Create HUD Text`).
DisplayName,
/// A declared OPY alias spelling (e.g. `getPlayers`).
Alias,
/// A settings path (e.g. `gamemodes.ffa.scoreToWin`).
Path,
/// No form matched exactly; the hit is the closest near-spelling.
Near,
}
impl MatchKind {
/// The serialized kind label.
pub fn as_str(&self) -> &'static str {
match self {
MatchKind::OpySpelling => "opySpelling",
MatchKind::CatalogId => "catalogId",
MatchKind::DisplayName => "displayName",
MatchKind::Alias => "alias",
MatchKind::Path => "path",
MatchKind::Near => "near",
}
}
}
/// One lookup hit.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "hit")]
pub enum LookupHit {
/// A callable.
Function {
/// The OPY call spelling (member calls carry their member name).
spelling: String,
/// Whether the callable is an action, a value, or a member call.
function_kind: LookupFunctionKind,
/// The declared receiver category of a member call — how it is
/// invoked (`eventPlayer.setMoveSpeed(…)` takes a `Player`
/// receiver). `None` for standalone calls.
#[serde(skip_serializing_if = "Option::is_none")]
receiver: Option<ReceiverCategory>,
/// Whether the argument count is unbounded (`.format` placeholders).
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
unbounded: bool,
/// The parameters in call order: the owner facts Wright renders
/// into a signature string.
params: Vec<LookupParam>,
/// The canonical catalog id the callable emits, when linked.
catalog_id: Option<String>,
/// The English display name the catalog records, when linked.
#[serde(skip_serializing_if = "Option::is_none")]
display_name: Option<String>,
/// Which spelling form matched.
matched_on: MatchKind,
},
/// A callable enum domain.
EnumDomain {
/// The OPY domain spelling (`Domain.MEMBER` head).
domain: String,
/// The members the domain accepts, or `None` when the domain is
/// manifest-only/contextual and carries no standalone member list.
members: Option<Vec<EnumMemberEntry>>,
/// The English display name the catalog records, when linked.
#[serde(skip_serializing_if = "Option::is_none")]
display_name: Option<String>,
/// Which spelling form matched.
matched_on: MatchKind,
},
/// One enum member.
EnumMember {
/// The OPY spelling (`Hero.SOLDIER`).
spelling: String,
/// The domain it belongs to.
domain: String,
/// The canonical catalog member id it lowers to.
member: String,
/// The English display name, when the catalog provides one.
display_name: Option<String>,
/// The other source spellings the member accepts.
aliases: Vec<String>,
/// Which spelling form matched.
matched_on: MatchKind,
},
/// A settings key.
Setting {
/// The effective `settings` path; per-team/per-hero slots stay
/// templated as `heroes.<team>.<hero>.<key>`.
path: String,
/// The English display name.
display_name: Option<String>,
/// The accepted value form.
value: SettingValueForm,
/// Which spelling form matched.
matched_on: MatchKind,
},
/// One parameter of a callable, listed inside a `LookupWithin::Callable`
/// scope.
Parameter {
/// The callable's OPY spelling.
callable: String,
/// The parameter facts.
param: LookupParam,
/// Which spelling form matched.
matched_on: MatchKind,
},
/// An intermediate settings path segment, listed inside a
/// `LookupWithin::Settings` scope. It names a scope, not a key.
SettingPath {
/// The settings path this node represents.
path: String,
/// Which spelling form matched.
matched_on: MatchKind,
},
}
/// The call position a function hit occupies.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum LookupFunctionKind {
/// A statement-position action.
Action,
/// A value-position function or special form.
Value,
/// An action that takes an event-player receiver.
MemberAction,
/// A value that takes a receiver.
MemberValue,
}
impl LookupFunctionKind {
/// The serialized kind label.
pub fn as_str(&self) -> &'static str {
match self {
LookupFunctionKind::Action => "action",
LookupFunctionKind::Value => "value",
LookupFunctionKind::MemberAction => "memberAction",
LookupFunctionKind::MemberValue => "memberValue",
}
}
}
/// One ordered parameter of a callable: the owner facts a caller renders.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LookupParam {
/// The canonical OPY keyword spelling.
pub name: String,
/// The alternate keyword spellings the slot accepts.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub alternate_names: Vec<String>,
/// Whether the slot must be supplied.
pub required: bool,
/// The enum domain the slot takes, when it takes one.
#[serde(skip_serializing_if = "Option::is_none")]
pub domain: Option<String>,
/// Every member spelling of that domain, when it is an enum slot —
/// the owner supplies the full inventory; which members a signature
/// renders is the caller's policy.
#[serde(skip_serializing_if = "Option::is_none")]
pub members: Option<Vec<EnumMemberEntry>>,
/// The semantic type the catalog records for the slot.
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
pub param_type: Option<String>,
/// The default value, rendered in source syntax.
#[serde(skip_serializing_if = "Option::is_none")]
pub default: Option<String>,
}
/// One member of an enum domain.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct EnumMemberEntry {
/// The OPY member spelling (`Hero.SOLDIER` minus its head).
pub spelling: String,
/// The canonical catalog member id it lowers to.
pub id: String,
/// The English display name, when the catalog provides one.
#[serde(skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
/// The other source spellings the member accepts.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub aliases: Vec<String>,
}
/// The value form a settings key accepts.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SettingValueForm {
/// The value shape.
pub kind: SettingValueKind,
/// The settings enum domain an `enum` key accepts members of.
#[serde(skip_serializing_if = "Option::is_none")]
pub domain: Option<String>,
/// The member spellings an `enum` slot accepts.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub members: Vec<String>,
/// The numeric bounds the table declares, when it declares them.
#[serde(skip_serializing_if = "Option::is_none")]
pub min: Option<f64>,
/// The numeric upper bound, when declared.
#[serde(skip_serializing_if = "Option::is_none")]
pub max: Option<f64>,
}
/// The value shape a settings key accepts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum SettingValueKind {
/// `key` with no value.
Presence,
/// `true` or `false`.
Boolean,
/// A number literal.
Number,
/// A number interpreted as a percent.
Percent,
/// A string literal.
String,
/// One of the `members` spellings.
Enum,
/// A list of map names.
MapList,
/// A list of hero names.
HeroList,
}
impl SettingValueKind {
/// The serialized kind label.
pub fn as_str(&self) -> &'static str {
match self {
SettingValueKind::Presence => "presence",
SettingValueKind::Boolean => "boolean",
SettingValueKind::Number => "number",
SettingValueKind::Percent => "percent",
SettingValueKind::String => "string",
SettingValueKind::Enum => "enum",
SettingValueKind::MapList => "mapList",
SettingValueKind::HeroList => "heroList",
}
}
}
/// Resolve a `LookupQuery` against the bundled manifest and catalog.
///
/// The answer is `LookupOutcome::Matched` (possibly with zero hits),
/// `LookupOutcome::UnknownWithin` when the named scope does not exist, or
/// `LookupOutcome::Unsupported` with a reason; vocabulary lookup never
/// fails — a name that resolves to nothing is simply absent from `results`.
/// An empty `text` applies no text constraint and lists the in-scope
/// entries in the vocabulary's stable order.
pub fn lookup(query: &LookupQuery) -> LookupOutcome {
let limit = if query.limit == 0 {
DEFAULT_LIMIT
} else {
query.limit
};
let scope = query.scope;
let unsupported = |reason: &str| LookupOutcome::Unsupported {
scope,
reason: reason.to_string(),
};
if let Some(locale) = &query.locale {
if !locale.eq_ignore_ascii_case("en-US") {
return unsupported(
"localized display names are owned by workshop-rs; opy-rs \
resolves display names in the 'en-US' locale only",
);
}
}
let (manifest, catalog) = match (Manifest::builtin(), Catalog::builtin()) {
(Ok(manifest), Ok(catalog)) => (manifest, catalog),
_ => return unsupported("vocabulary data (manifest or catalog) is not bundled"),
};
let index = Index::new(manifest, &catalog);
if let Some(within) = &query.within {
let Some(children) = index.children(within) else {
return LookupOutcome::UnknownWithin {
within: within.clone(),
};
};
let mut results = index.rank(children.iter(), query);
results.truncate(limit);
return LookupOutcome::Matched {
scope: within.scope(),
limit,
results,
};
}
if !query.scope.any() {
return unsupported("the query scope selects no namespace");
}
let mut results = index.rank(
index
.candidates
.iter()
.filter(|candidate| index.in_scope(candidate, scope)),
query,
);
results.truncate(limit);
LookupOutcome::Matched {
scope,
limit,
results,
}
}
/// Lookup with a default query (all namespaces, `DEFAULT_LIMIT`).
pub fn lookup_str(text: &str) -> LookupOutcome {
lookup(&LookupQuery::new(text))
}
// ---------------------------------------------------------------------------
// The search index — spellings projected from manifest + catalog data
// ---------------------------------------------------------------------------
struct ScoredHit {
score: u32,
hit: LookupHit,
}
impl LookupHit {
fn sort_key(&self) -> String {
match self {
LookupHit::Function { spelling, .. } => format!("0{spelling}"),
LookupHit::EnumMember { spelling, .. } => format!("1{spelling}"),
LookupHit::EnumDomain { domain, .. } => format!("2{domain}"),
LookupHit::Setting { path, .. } => format!("3{path}"),
LookupHit::Parameter {
callable, param, ..
} => {
format!("4{callable}.{}", param.name)
}
LookupHit::SettingPath { path, .. } => format!("5{path}"),
}
}
/// Restamp `matched_on` for a listed answer: no text constraint scored,
/// so the entry's own primary form is what it answers to.
fn listed(self) -> LookupHit {
let kind = match &self {
LookupHit::Setting { .. } | LookupHit::SettingPath { .. } => MatchKind::Path,
_ => MatchKind::OpySpelling,
};
self.with_match_kind(kind, 0, false)
}
/// Stamp the matched-on kind: a folded-equal or structurally matching
/// (settings path-prefix) form reports its own kind; other hits are
/// `Near` near-misses.
fn with_match_kind(self, kind: MatchKind, score: u32, structural: bool) -> LookupHit {
let matched_on = if score == 0 || structural {
kind
} else {
MatchKind::Near
};
match self {
LookupHit::Function {
spelling,
function_kind,
receiver,
unbounded,
params,
catalog_id,
display_name,
..
} => LookupHit::Function {
spelling,
function_kind,
receiver,
unbounded,
params,
catalog_id,
display_name,
matched_on,
},
LookupHit::EnumDomain {
domain,
members,
display_name,
..
} => LookupHit::EnumDomain {
domain,
members,
display_name,
matched_on,
},
LookupHit::EnumMember {
spelling,
domain,
member,
display_name,
aliases,
..
} => LookupHit::EnumMember {
spelling,
domain,
member,
display_name,
aliases,
matched_on,
},
LookupHit::Setting {
path,
display_name,
value,
..
} => LookupHit::Setting {
path,
display_name,
value,
matched_on,
},
LookupHit::Parameter {
callable, param, ..
} => LookupHit::Parameter {
callable,
param,
matched_on,
},
LookupHit::SettingPath { path, .. } => LookupHit::SettingPath { path, matched_on },
}
}
}
/// One searchable entry: every spelling form it answers to plus the payload
/// returned when one matches.
#[derive(Clone)]
struct Candidate {
forms: Vec<(String, MatchKind)>,
hit: LookupHit,
}
struct Index<'a> {
manifest: &'a Manifest,
catalog: &'a Catalog,
candidates: Vec<Candidate>,
}
impl<'a> Index<'a> {
fn new(manifest: &'a Manifest, catalog: &'a Catalog) -> Index<'a> {
let mut index = Index {
manifest,
catalog,
candidates: Vec::new(),
};
index.index_functions();
index.index_enums();
index.index_settings();
index
}
/// Rank `candidates` under `query`: a non-empty text scores each
/// candidate's best-matching form through the shared matcher pipeline,
/// while an empty text lists the candidates in their construction order.
fn rank<'c>(
&self,
candidates: impl Iterator<Item = &'c Candidate>,
query: &LookupQuery,
) -> Vec<LookupHit> {
if query.text.trim().is_empty() {
return candidates
.map(|candidate| candidate.hit.clone().listed())
.collect();
}
let mut hits: Vec<ScoredHit> = candidates
.filter_map(|candidate| {
candidate
.forms
.iter()
.filter_map(|(form, kind)| {
// Settings paths match segment by segment: structure,
// template segments and `%` suffixes stay meaningful
// for exact/path-prefix queries; the folded `score`
// only serves near-name ranking. Both scorers live in
// `crate::matcher` — the same pipeline that produces
// the `did you mean` candidates on rejected names.
let (scored, structural) = if *kind == MatchKind::Path {
match crate::matcher::path_score(&query.text, form) {
Some(s) => (Some(s), true),
None => (crate::matcher::score(&query.text, form), false),
}
} else {
(crate::matcher::score(&query.text, form), false)
};
scored.map(|s| {
// A raw (case-insensitive) hit reports the form
// the user actually typed when folds collide.
(
s,
form.eq_ignore_ascii_case(query.text.trim()),
*kind,
structural,
)
})
})
.min_by_key(|(s, exact, _, _)| (*s, !*exact))
.map(|(s, _, kind, structural)| ScoredHit {
score: s,
hit: candidate.hit.clone().with_match_kind(kind, s, structural),
})
})
.collect();
hits.sort_by(|a, b| {
a.score
.cmp(&b.score)
.then_with(|| a.hit.sort_key().cmp(&b.hit.sort_key()))
});
hits.into_iter().map(|scored| scored.hit).collect()
}
fn in_scope(&self, candidate: &Candidate, scope: LookupScope) -> bool {
match &candidate.hit {
LookupHit::Function { .. } | LookupHit::Parameter { .. } => scope.functions,
LookupHit::EnumDomain { .. } | LookupHit::EnumMember { .. } => scope.enums,
LookupHit::Setting { .. } | LookupHit::SettingPath { .. } => scope.settings,
}
}
// -- within scopes -----------------------------------------------------
/// The child candidates of one `within` scope, or `None` when `within`
/// names no scope the index knows.
fn children(&self, within: &LookupWithin) -> Option<Vec<Candidate>> {
match within {
LookupWithin::Callable(name) => self.callable_children(name),
LookupWithin::Enum(domain) => self.enum_children(domain),
LookupWithin::Settings(prefix) => self.settings_children(prefix),
LookupWithin::SettingEnum(domain) => self.setting_enum_children(domain),
}
}
/// One candidate per declared parameter of the callable `name` (its OPY
/// spelling), in call order.
fn callable_children(&self, name: &str) -> Option<Vec<Candidate>> {
self.candidates
.iter()
.find_map(|candidate| match &candidate.hit {
LookupHit::Function {
spelling, params, ..
} if spelling == name => Some(
params
.iter()
.map(|param| {
let mut forms = vec![(param.name.clone(), MatchKind::OpySpelling)];
forms.extend(
param
.alternate_names
.iter()
.map(|name| (name.clone(), MatchKind::Alias)),
);
Candidate {
forms,
hit: LookupHit::Parameter {
callable: spelling.clone(),
param: param.clone(),
matched_on: MatchKind::OpySpelling,
},
}
})
.collect(),
),
_ => None,
})
}
/// One candidate per member of the enum domain `domain`, in domain
/// order. A manifest-only domain is an existing but empty scope.
fn enum_children(&self, domain: &str) -> Option<Vec<Candidate>> {
let known = self.candidates.iter().any(|candidate| {
matches!(&candidate.hit, LookupHit::EnumDomain { domain: d, .. } if d == domain)
});
if !known {
return None;
}
Some(
crate::enums::domain_members(domain, self.catalog)
.map(|members| {
members
.iter()
.map(|member| self.member_candidate(domain, member))
.collect()
})
.unwrap_or_default(),
)
}
/// The settings keys and intermediate path segments directly below
/// `prefix`, in settings-table order; an empty prefix lists the root.
/// `None` when `prefix` is not a proper segment-wise prefix of any
/// settings path.
fn settings_children(&self, prefix: &str) -> Option<Vec<Candidate>> {
let prefix_segments: Vec<&str> =
prefix.split('.').filter(|part| !part.is_empty()).collect();
let mut children: Vec<Candidate> = Vec::new();
let mut seen: Vec<&str> = Vec::new();
for candidate in &self.candidates {
let LookupHit::Setting { path, .. } = &candidate.hit else {
continue;
};
let segments: Vec<&str> = path.split('.').collect();
if !segments.starts_with(prefix_segments.as_slice()) {
continue;
}
let Some(&child_segment) = segments.get(prefix_segments.len()) else {
continue;
};
if seen.contains(&child_segment) {
continue;
}
seen.push(child_segment);
if segments.len() == prefix_segments.len() + 1 {
children.push(candidate.clone());
} else {
let child_path = prefix_segments
.iter()
.copied()
.chain(std::iter::once(child_segment))
.collect::<Vec<_>>()
.join(".");
children.push(Candidate {
forms: vec![
(child_segment.to_string(), MatchKind::OpySpelling),
(child_path.clone(), MatchKind::Path),
],
hit: LookupHit::SettingPath {
path: child_path,
matched_on: MatchKind::Path,
},
});
}
}
(!children.is_empty()).then_some(children)
}
/// One candidate per accepted member of a settings enum domain, in
/// table order. `None` when `domain` is not a settings enum domain.
fn setting_enum_children(&self, domain: &str) -> Option<Vec<Candidate>> {
let mut members: Vec<(String, String)> = Vec::new();
for definition in settings::definitions() {
for member in definition.enum_members() {
if member.domain() == domain && !members.iter().any(|(id, _)| id == member.id()) {
members.push((member.id().to_string(), member.english_name().to_string()));
}
}
}
if members.is_empty() {
return None;
}
Some(
members
.into_iter()
.map(|(id, name)| Candidate {
forms: vec![
(id.clone(), MatchKind::OpySpelling),
(name.clone(), MatchKind::DisplayName),
],
hit: LookupHit::EnumMember {
spelling: id.clone(),
domain: domain.to_string(),
member: id,
display_name: (!name.is_empty()).then_some(name),
aliases: Vec::new(),
matched_on: MatchKind::OpySpelling,
},
})
.collect(),
)
}
// -- functions --------------------------------------------------------
fn index_functions(&mut self) {
let locale = crate::enums::en_us();
for function in self.manifest.functions() {
let mut forms = vec![(function.id.clone(), MatchKind::OpySpelling)];
let mut display_name = None;
if let Some(catalog_id) = &function.catalog_id {
forms.push((catalog_id.clone(), MatchKind::CatalogId));
let kind = match function.kind {
FunctionKind::Action | FunctionKind::MemberAction => Kind::Action,
FunctionKind::Value | FunctionKind::MemberValue => Kind::Value,
};
if let Some(entry) = self.catalog.entry(kind, catalog_id) {
if let Some(spelling) = entry.spelling(&locale) {
display_name = Some(spelling.to_string());
forms.push((spelling.to_string(), MatchKind::DisplayName));
}
for spelling in entry.spellings(&locale) {
forms.push((spelling.clone(), MatchKind::DisplayName));
}
}
}
for alias in self.manifest.aliases() {
if alias_target(alias, self.manifest)
.is_some_and(|target| std::ptr::eq(target, function))
{
forms.push((alias.source.clone(), MatchKind::Alias));
}
}
let params = self.lookup_params(function);
self.candidates.push(Candidate {
forms,
hit: LookupHit::Function {
spelling: function.id.clone(),
function_kind: match function.kind {
FunctionKind::Action => LookupFunctionKind::Action,
FunctionKind::Value => LookupFunctionKind::Value,
FunctionKind::MemberAction => LookupFunctionKind::MemberAction,
FunctionKind::MemberValue => LookupFunctionKind::MemberValue,
},
receiver: function.receiver,
unbounded: function.unbounded,
params,
catalog_id: function.catalog_id.clone(),
display_name,
matched_on: MatchKind::OpySpelling,
},
});
}
for special in SPECIAL_FUNCTIONS {
let params: Vec<LookupParam> = special
.params
.iter()
.map(|param| LookupParam {
name: param.name.to_string(),
alternate_names: Vec::new(),
required: param.required,
domain: None,
members: None,
param_type: Some(param.param_type.to_string()),
default: param.default.map(str::to_string),
})
.collect();
self.candidates.push(Candidate {
forms: vec![(special.name.to_string(), MatchKind::OpySpelling)],
hit: LookupHit::Function {
spelling: special.name.to_string(),
function_kind: LookupFunctionKind::Value,
receiver: None,
unbounded: false,
params,
catalog_id: None,
display_name: None,
matched_on: MatchKind::OpySpelling,
},
});
}
}
fn lookup_params(&self, function: &Function) -> Vec<LookupParam> {
let catalog_entry = function.catalog_id.as_deref().and_then(|catalog_id| {
let kind = match function.kind {
FunctionKind::Action | FunctionKind::MemberAction => Kind::Action,
FunctionKind::Value | FunctionKind::MemberValue => Kind::Value,
};
self.catalog.entry(kind, catalog_id)
});
function
.params
.iter()
.enumerate()
.map(|(index, param)| {
let catalog_index = self.catalog_param_index(catalog_entry, function, param, index);
let (param_type, catalog_domain) = catalog_index
.and_then(|i| {
catalog_entry.map(|entry| {
(
entry.param_type(i).map(str::to_string),
entry.param_domain(i).map(str::to_string),
)
})
})
.unwrap_or((None, None));
// The reported domain is the reference source spelling:
// a catalog-declared `Clipping` slot renders as `Clip`.
let domain = param
.domain
.clone()
.or(catalog_domain)
.map(|domain| crate::enums::opy_domain(&domain).to_string());
let required = !param.optional && param.default.is_none();
// An enum slot carries its domain's full member inventory:
// which members a rendered signature shows is the caller's
// (Wright's) policy, not the owner's.
let members = domain
.as_deref()
.and_then(|domain| crate::enums::domain_members(domain, self.catalog))
.map(|members| members.iter().map(member_entry).collect::<Vec<_>>());
let default = param
.default
.as_ref()
.map(|d| default_text(d, domain.as_deref(), self.catalog));
LookupParam {
name: param.name.clone(),
alternate_names: param.alternate_names.clone(),
required,
members,
domain,
param_type,
default,
}
})
.collect()
}
/// The catalog parameter index a manifest parameter occupies: member
/// calls carry a receiver slot the manifest does not list, so they shift
/// by one when the catalog side names a receiver first.
fn catalog_param_index(
&self,
entry: Option<&workshop_rs::catalog::CatalogEntry>,
function: &Function,
param: &Param,
index: usize,
) -> Option<usize> {
let entry = entry?;
let count = entry.param_count();
let offset = if function.kind.is_member() && count == function.params.len() + 1 {
1
} else {
0
};
if count == function.params.len() + offset {
// Aligned declarations: the semantic name resolves the slot,
// else position wins.
let candidate = index + offset;
match (0..count).position(|i| {
entry.param_name(i).is_some_and(|name| {
crate::matcher::fold(name) == crate::matcher::fold(¶m.name)
})
}) {
Some(i) => Some(i),
None => (candidate < count).then_some(candidate),
}
} else {
(0..count).find(|&i| {
entry.param_name(i).is_some_and(|name| {
crate::matcher::fold(name) == crate::matcher::fold(¶m.name)
})
})
}
}
// -- enums ------------------------------------------------------------
fn index_enums(&mut self) {
for domain in self.lookup_domains() {
let members = crate::enums::domain_members(&domain, self.catalog);
let mut domain_forms = vec![(domain.clone(), MatchKind::OpySpelling)];
let mut display_name = None;
if let Some(catalog_domain) = self
.catalog
.enum_domain(crate::enums::catalog_domain(&domain))
{
domain_forms.push((catalog_domain.domain.clone(), MatchKind::CatalogId));
let locale = crate::enums::en_us();
if let Some(spelling) = catalog_domain.spelling(&locale) {
display_name = Some(spelling.to_string());
domain_forms.push((spelling.to_string(), MatchKind::DisplayName));
}
}
let entries: Option<Vec<EnumMemberEntry>> = members
.as_ref()
.map(|members| members.iter().map(member_entry).collect());
self.candidates.push(Candidate {
forms: domain_forms,
hit: LookupHit::EnumDomain {
domain: domain.clone(),
members: entries,
display_name,
matched_on: MatchKind::OpySpelling,
},
});
if let Some(members) = members {
for member in &members {
self.candidates.push(self.member_candidate(&domain, member));
}
}
}
}
/// The member candidate the enum domain index and a `within: enum`
/// scope share, so a member answers to the same forms in both.
fn member_candidate(&self, domain: &str, member: &crate::enums::DomainMember) -> Candidate {
let entry = member_entry(member);
let mut forms = vec![
(
format!("{domain}.{}", entry.spelling),
MatchKind::OpySpelling,
),
(entry.spelling.clone(), MatchKind::OpySpelling),
];
if let Some(display) = &member.display_name {
forms.push((display.clone(), MatchKind::DisplayName));
}
if let Some(catalog_member) = &member.catalog_member {
forms.push((catalog_member.clone(), MatchKind::CatalogId));
}
for alias in &member.aliases {
forms.push((alias.clone(), MatchKind::Alias));
}
Candidate {
forms,
hit: LookupHit::EnumMember {
spelling: format!("{domain}.{}", entry.spelling),
domain: domain.to_string(),
member: entry.id,
display_name: entry.display_name,
aliases: entry.aliases,
matched_on: MatchKind::OpySpelling,
},
}
}
/// Every enum domain the lookup reports: catalog domains under their
/// reference source spelling (`Clipping` reports as `Clip`), plus
/// source-level alias domains (`AsyncBehavior`) and manifest-only
/// signature domains. Catalog domains that are not `Domain.MEMBER`
/// sources in the reference (`EventTeam`, `Rounding`, …) are not
/// reported — their members are spellings upstream rejects.
fn lookup_domains(&self) -> Vec<String> {
let mut domains: Vec<String> = self
.catalog
.enum_domains()
.filter(|domain| !crate::enums::NON_SOURCE_DOMAINS.contains(&domain.domain.as_str()))
.map(|domain| crate::enums::opy_domain(&domain.domain).to_string())
.collect();
domains.extend(
crate::enums::DOMAIN_ALIASES
.iter()
.map(|(source, _)| source.to_string()),
);
for domain in self
.manifest
.functions()
.iter()
.flat_map(|function| function.params.iter())
.filter_map(|param| param.domain.as_deref())
.map(crate::enums::opy_domain)
{
if !crate::enums::NON_SOURCE_DOMAINS.contains(&domain)
&& !domains.iter().any(|d| d == domain)
{
domains.push(domain.to_string());
}
}
domains
}
// -- settings ---------------------------------------------------------
fn index_settings(&mut self) {
for definition in settings::definitions() {
self.push_setting(definition.path(), &definition);
}
// Per-mode keys inherited from `gamemodes.general` answer to their
// effective path: the table resolves them through lookup, so index
// the same way emission does rather than re-declaring them.
let modes: Vec<String> = settings::definitions()
.filter_map(|definition| {
let mut parts = definition.path().split('.');
match (parts.next(), parts.next(), parts.next()) {
(Some("gamemodes"), Some(mode), Some(_)) if mode != "general" => {
Some(mode.to_string())
}
_ => None,
}
})
.collect();
let modes: Vec<String> = {
let mut seen = Vec::new();
for mode in modes {
if !seen.contains(&mode) {
seen.push(mode);
}
}
seen
};
for definition in settings::definitions() {
let Some(leaf) = definition.path().strip_prefix("gamemodes.general.") else {
continue;
};
for mode in &modes {
let probe = [
PathPart::Part("gamemodes"),
PathPart::Part(mode.as_str()),
PathPart::Part(leaf),
];
if let Some(resolved) = settings::definition(&probe) {
let path = format!("gamemodes.{mode}.{leaf}");
if resolved.path() != path {
// The resolution is the inherited general entry.
self.push_setting(&path, &resolved);
}
}
}
}
}
fn push_setting(&mut self, path: &str, definition: &settings::SettingDefinition) {
let leaf = path.rsplit('.').next().unwrap_or(path);
let english_name = definition.presentation().english_name;
let mut forms = vec![
(path.to_string(), MatchKind::Path),
(leaf.to_string(), MatchKind::OpySpelling),
];
if !english_name.is_empty() {
forms.push((english_name.to_string(), MatchKind::DisplayName));
}
self.candidates.push(Candidate {
forms,
hit: LookupHit::Setting {
path: path.to_string(),
display_name: (!english_name.is_empty()).then(|| english_name.to_string()),
value: setting_value_form(definition),
matched_on: MatchKind::Path,
},
});
}
}
/// The function an alias resolves to, through its declared kind.
fn alias_target<'a>(
alias: &crate::manifest::Alias,
manifest: &'a Manifest,
) -> Option<&'a Function> {
match alias.kind {
AliasKind::FunctionAlias => manifest.function(&alias.target),
AliasKind::MemberAlias => manifest.member(&alias.target),
}
}
/// Render a manifest `DomainMember` as a lookup member entry.
fn member_entry(member: &crate::enums::DomainMember) -> EnumMemberEntry {
EnumMemberEntry {
spelling: member.member.clone(),
id: member
.catalog_member
.clone()
.unwrap_or_else(|| member.member.clone()),
display_name: member.display_name.clone(),
aliases: member.aliases.clone(),
}
}
/// The value form of one settings table definition.
fn setting_value_form(definition: &settings::SettingDefinition) -> SettingValueForm {
let (kind, domain, min, max) = match definition.domain() {
SettingValueDomain::PresenceOnly => (SettingValueKind::Presence, None, None, None),
SettingValueDomain::Boolean => (SettingValueKind::Boolean, None, None, None),
SettingValueDomain::Number(bounds) => {
(SettingValueKind::Number, None, bounds.min(), bounds.max())
}
SettingValueDomain::Percent(bounds) => {
(SettingValueKind::Percent, None, bounds.min(), bounds.max())
}
SettingValueDomain::String => (SettingValueKind::String, None, None, None),
SettingValueDomain::Enum { domain } => {
(SettingValueKind::Enum, Some(domain.clone()), None, None)
}
SettingValueDomain::MapList => (SettingValueKind::MapList, None, None, None),
SettingValueDomain::HeroList => (SettingValueKind::HeroList, None, None, None),
// `SettingValueDomain` is non-exhaustive upstream; a future variant
// must be mapped here rather than silently re-typed.
other => unreachable!("unhandled SettingValueDomain variant {other:?}"),
};
// A `BoolEnum` key is Boolean-typed over an enum domain and accepts
// `true` only; a plain `Enum` key accepts its member ids.
let members: Vec<String> =
if kind == SettingValueKind::Boolean && definition.enum_members().next().is_some() {
vec!["true".to_string()]
} else {
definition
.enum_members()
.map(|member| member.id().to_string())
.collect()
};
SettingValueForm {
kind,
domain,
members,
min,
max,
}
}
/// Render a parameter default in source syntax.
fn default_text(default: &ParamDefault, domain: Option<&str>, catalog: &Catalog) -> String {
match default {
ParamDefault::Null { .. } => "null".to_string(),
ParamDefault::Bool(value) => value.to_string(),
ParamDefault::Number(value) => {
if value.fract() == 0.0 {
format!("{}", *value as i64)
} else {
value.to_string()
}
}
ParamDefault::Call { call, args } => {
let args = args
.iter()
.map(|arg| {
if arg.fract() == 0.0 {
format!("{}", *arg as i64)
} else {
arg.to_string()
}
})
.collect::<Vec<_>>()
.join(", ");
format!("{call}({args})")
}
ParamDefault::EnumMember(member) => match domain {
// Defaults render under the advertised OPY spelling: a member
// recorded by its catalog id (`DO_NOT_CLIP`) shows as `NONE`.
Some(domain) => {
let spelling = crate::enums::domain_members(domain, catalog)
.and_then(|members| {
members
.iter()
.find(|entry| {
entry.member == *member
|| entry.catalog_member.as_deref() == Some(member.as_str())
})
.map(|entry| entry.member.clone())
})
.unwrap_or_else(|| member.clone());
format!("{domain}.{spelling}")
}
None => member.clone(),
},
}
}
#[cfg(test)]
mod tests {
use super::*;
use workshop_rs::catalog::Catalog;
/// The lookup cannot claim a member spelling the lowerer would reject:
/// every member and alias `domain_members` reports must resolve through
/// `canonical_member`, the same function lowering calls.
#[test]
fn reported_member_spellings_resolve_through_lowering() {
let catalog = Catalog::builtin().expect("bundled catalog");
let manifest = Manifest::builtin().expect("bundled manifest");
let index = Index::new(manifest, &catalog);
for domain in index.lookup_domains() {
let Some(members) = crate::enums::domain_members(&domain, &catalog) else {
continue;
};
for member in &members {
for spelling in std::iter::once(&member.member).chain(&member.aliases) {
// OPY-only `Color` members lower to `rgb(...)` calls
// through `extra_color_member` rather than a canonical
// member id.
let resolves = crate::enums::canonical_member(&domain, spelling, &catalog)
.is_some()
|| (domain == "Color"
&& crate::enums::extra_color_member(spelling).is_some());
assert!(
resolves,
"{domain}.{spelling} is lookup-visible but does not resolve"
);
}
}
}
}
/// Every function spelling a lookup hit reports must resolve through
/// the same manifest the lowerer resolves: lookup data is never a
/// second table.
#[test]
fn reported_function_spellings_resolve_through_the_manifest() {
let manifest = Manifest::builtin().expect("bundled manifest");
for function in manifest.functions() {
let resolves = if function.kind.is_member() {
manifest.resolve_member(&function.id).is_some()
} else {
manifest.resolve_function(&function.id).is_some()
};
assert!(
resolves,
"{} is lookup-visible but does not resolve",
function.id
);
}
// Special-call spellings must be exactly the names `lower_call`
// dispatches on: `SPECIAL_VALUE_CALLS` is the descriptor the resolver
// consults, so a dropped or renamed special form makes the reported
// set disagree and fails here.
let reported: Vec<&str> = SPECIAL_FUNCTIONS
.iter()
.map(|special| special.name)
.collect();
let dispatched: Vec<&str> = crate::lower::special_forms::SPECIAL_VALUE_CALLS
.iter()
.map(|(name, _)| *name)
.collect();
assert_eq!(
reported, dispatched,
"reported special-call spellings must be the dispatched set"
);
// Each reported special must resolve through the real lowerer: a
// call in value position is `unknown-value` when the dispatch table
// no longer recognizes the name.
for special in SPECIAL_FUNCTIONS {
let source = format!(
"globalvar x\nrule \"r\":\n @Event global\n x = {}()\n",
special.name
);
let diagnostics =
crate::tooling::check(&source, "main.opy", std::path::Path::new("")).diagnostics;
assert!(
!diagnostics.iter().any(|diagnostic| matches!(
diagnostic.code.as_str(),
"unknown-value" | "unknown-action" | "invalid-iterable"
)),
"'{}' is lookup-reported but the lowerer rejects it: {diagnostics:?}",
special.name
);
}
}
/// Every member alias the lookup reports must be an OPY spelling the
/// pinned reference accepts — never a canonical catalog id
/// (`Hero.SOLDIER_76` is a reference rejection, not an alias). The
/// upstream-accepted extra spellings are the legacy hero names
/// `MCCREE`/`HAMMOND` and the `HudPosition.ACTUALLY_LEFT` emit alias
/// (overpy 9.7.10 rewrites all three in member access); `opy-compat
/// probe-generate` emits a `:spelling` probe per reported spelling so
/// the same set is checked against the oracle.
#[test]
fn reported_member_aliases_are_reference_spellings() {
let catalog = Catalog::builtin().expect("bundled catalog");
let manifest = Manifest::builtin().expect("bundled manifest");
let index = Index::new(manifest, &catalog);
let mut reported = Vec::new();
for domain in index.lookup_domains() {
let Some(members) = crate::enums::domain_members(&domain, &catalog) else {
continue;
};
for member in members {
for alias in member.aliases {
assert_ne!(
Some(alias.as_str()),
member.catalog_member.as_deref(),
"{domain}.{alias} advertises the catalog id as an OPY alias"
);
reported.push(format!("{domain}.{alias}"));
}
}
}
reported.sort();
assert_eq!(
reported,
["Hero.HAMMOND", "Hero.MCCREE", "HudPosition.ACTUALLY_LEFT"]
);
}
/// Ranking goes through the shared `crate::matcher` pipeline: exact and
/// near matches come first, the rejected spelling is not a candidate.
#[test]
fn rank_prefers_close_spellings() {
let pool = crate::matcher::bare_candidates(["hudText", "smallMessage", "destroyIcon"]);
let ranked = crate::matcher::rank("hudTex", &pool);
assert_eq!(ranked.first().map(String::as_str), Some("hudText"));
assert!(
!ranked.iter().any(|candidate| candidate == "hudTex"),
"the rejected spelling is not a candidate"
);
}
/// The settings candidate walk finds sibling keys of an unknown member
/// at a per-mode path (inherited `gamemodes.general` keys included).
#[test]
fn sibling_keys_cover_inherited_gamemode_keys() {
let keys =
crate::matcher::sibling_keys(&[PathPart::Part("gamemodes"), PathPart::Part("ffa")]);
assert!(
keys.iter().any(|key| key == "scoreToWin"),
"inherited general keys must be candidates: {keys:?}"
);
}
fn within_query(within: LookupWithin) -> LookupQuery {
LookupQuery {
text: String::new(),
scope: LookupScope::ALL,
within: Some(within),
locale: None,
limit: usize::MAX,
}
}
/// A `within: callable` scope lists the callable's declared parameters
/// as `Parameter` hits in call order, not ranked text matches.
#[test]
fn within_callable_lists_params_in_call_order() {
let LookupOutcome::Matched { results, .. } =
lookup(&within_query(LookupWithin::Callable("wait".to_string())))
else {
panic!("wait is a known callable");
};
let names: Vec<&str> = results
.iter()
.map(|hit| {
let LookupHit::Parameter { param, .. } = hit else {
panic!("callable children are parameters: {hit:?}");
};
param.name.as_str()
})
.collect();
assert_eq!(names, ["time", "waitBehavior"]);
let LookupOutcome::UnknownWithin { .. } = lookup(&within_query(LookupWithin::Callable(
"notAFunction".to_string(),
))) else {
panic!("an unknown callable is not a scope");
};
}
/// A `within: enum` scope lists the domain's member spellings in domain
/// order; a `within: settings` scope lists immediate children — leaf
/// keys as `Setting` hits, intermediate segments as `SettingPath` hits —
/// and an empty prefix lists the root.
#[test]
fn within_scopes_list_their_children() {
let LookupOutcome::Matched { results, .. } =
lookup(&within_query(LookupWithin::Enum("Button".to_string())))
else {
panic!("Button is a known enum domain");
};
let LookupHit::EnumMember { spelling, .. } = &results[0] else {
panic!("enum children are members: {:?}", results[0]);
};
assert_eq!(spelling, "Button.PRIMARY_FIRE");
let LookupOutcome::Matched { results, .. } =
lookup(&within_query(LookupWithin::Settings(String::new())))
else {
panic!("the settings root exists");
};
assert!(
results
.iter()
.all(|hit| matches!(hit, LookupHit::SettingPath { .. })),
"the root has only intermediate segments: {results:?}"
);
let LookupOutcome::Matched { results, .. } = lookup(&within_query(LookupWithin::Settings(
"gamemodes.ffa".to_string(),
))) else {
panic!("gamemodes.ffa is a settings path prefix");
};
assert!(
results.iter().any(|hit| matches!(
hit,
LookupHit::Setting { path, .. } if path == "gamemodes.ffa.scoreToWin"
)),
"a leaf child reports its Setting hit: {results:?}"
);
let LookupOutcome::UnknownWithin { .. } = lookup(&within_query(LookupWithin::Settings(
"gamemodes.ffa.scoreToWin".to_string(),
))) else {
panic!("a leaf setting has no children");
};
}
/// A settings enum domain (`lobby.mapRotation` accepts `afterAGame`…)
/// answers under `LookupWithin::SettingEnum` with the member spellings
/// the settings table declares; it is not an OPY enum domain.
#[test]
fn within_settings_enum_lists_accepted_members() {
let LookupOutcome::Matched { results, .. } = lookup(&within_query(
LookupWithin::SettingEnum("mapRotation".to_string()),
)) else {
panic!("mapRotation is a settings enum domain");
};
let spellings: Vec<&str> = results
.iter()
.map(|hit| {
let LookupHit::EnumMember { spelling, .. } = hit else {
panic!("settings enum children are members: {hit:?}");
};
spelling.as_str()
})
.collect();
assert_eq!(spellings, ["afterAGame", "afterMirrorMatch", "paused"]);
let LookupOutcome::UnknownWithin { .. } =
lookup(&within_query(LookupWithin::Enum("mapRotation".to_string())))
else {
panic!("mapRotation is not a source enum domain");
};
}
/// An empty text lists the scope's children in construction order with
/// each hit's primary match kind stamped; it is not a `Near` ranking.
#[test]
fn empty_text_lists_children_in_stable_order() {
let outcome_a = lookup(&within_query(LookupWithin::Enum("Button".to_string())));
let outcome_b = lookup(&within_query(LookupWithin::Enum("Button".to_string())));
assert_eq!(outcome_a, outcome_b, "repeat listings are identical");
let LookupOutcome::Matched { results, .. } = outcome_a else {
panic!("Button is a known enum domain");
};
assert!(
results.iter().all(|hit| matches!(
hit,
LookupHit::EnumMember {
matched_on: MatchKind::OpySpelling,
..
}
)),
"listed members report their spelling form: {results:?}"
);
}
}