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
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
//! Deterministic localized Workshop emitter.
//!
//! Serializes validated Workshop IR into localized Workshop text with a
//! selectable output locale. Canonical catalog identities resolve to
//! locale-specific spellings; missing target-locale mappings fail explicitly
//! with a [`WorkshopError::MissingMapping`] diagnostic — never a guess, never
//! a silent passthrough of another locale's spelling. Fallback to another
//! declared locale is opt-in ([`EmitOptions`]) and every fell-back identity
//! is recorded in [`EmitOutput::fallback_ids`]. The formatting is fixed and
//! presentation-canonical, so the same WIR/config emits byte-stable text that
//! reparses to equivalent WIR — except for the `settings` section:
//! settings-bearing emissions are deliberately rejected by the Workshop
//! parser (a `.ws` decompiler is a non-goal). Settings names are resolved from
//! the generated locale corpus, with an explicit `en-US` fallback when needed.
use std::fmt::Write;
use crate::catalog::{Catalog, Kind, Locale};
use crate::error::{Result, WorkshopError};
use crate::format::format_number;
use crate::settings::table::{self, KeyKind, PathPart};
use crate::settings::{Settings as SettingsTree, SettingsNode};
use crate::wir;
/// Emission options: opt-in fallback for missing target-locale mappings.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct EmitOptions {
/// When a canonical identity has no spelling for the target locale, its
/// spelling in this declared locale is used instead. `None` (the default)
/// keeps missing mappings failing explicitly. The fallback choice is
/// visible in [`EmitOutput::fallback_ids`].
pub fallback_locale: Option<Locale>,
}
/// The result of a localized emission.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EmitOutput {
/// The emitted localized Workshop text.
pub text: String,
/// Canonical identities (and the `settings` marker) whose spelling came
/// from the opt-in fallback locale instead of the target locale. Empty
/// when no fallback occurred.
pub fallback_ids: Vec<String>,
}
/// Emit a Workshop IR program as localized Workshop text, failing explicitly
/// on any missing target-locale mapping (no fallback).
pub fn emit(program: &wir::Program, catalog: &Catalog, locale: &Locale) -> Result<String> {
emit_with_options(program, catalog, locale, &EmitOptions::default()).map(|out| out.text)
}
/// Emit a Workshop IR program as localized Workshop text with emission
/// options (opt-in fallback locale).
pub fn emit_with_options(
program: &wir::Program,
catalog: &Catalog,
locale: &Locale,
options: &EmitOptions,
) -> Result<EmitOutput> {
emit_with_options_inner(program, catalog, locale, options, false)
}
pub(crate) fn emit_with_options_for_conversion(
program: &wir::Program,
catalog: &Catalog,
locale: &Locale,
options: &EmitOptions,
) -> Result<EmitOutput> {
emit_with_options_inner(program, catalog, locale, options, true)
}
fn emit_with_options_inner(
program: &wir::Program,
catalog: &Catalog,
locale: &Locale,
options: &EmitOptions,
force_hero_constructors: bool,
) -> Result<EmitOutput> {
let mut emitter = Emitter {
program,
catalog,
locale: locale.clone(),
fallback: options.fallback_locale.clone(),
force_hero_constructors,
fallback_ids: Vec::new(),
out: String::new(),
};
emitter.run()?;
Ok(EmitOutput {
text: emitter.out,
fallback_ids: emitter.fallback_ids,
})
}
struct Emitter<'a> {
program: &'a wir::Program,
catalog: &'a Catalog,
locale: Locale,
/// The opt-in fallback locale for missing target-locale mappings.
fallback: Option<Locale>,
/// Canonical ids emitted with a fallback-locale spelling.
fallback_ids: Vec<String>,
force_hero_constructors: bool,
out: String,
}
impl Emitter<'_> {
fn run(&mut self) -> Result<()> {
// Section order: settings, variables, subroutines, rules.
if let Some(settings) = &self.program.settings {
self.emit_settings(settings)?;
self.out.push('\n');
}
if !self.program.global_variables.is_empty() || !self.program.player_variables.is_empty() {
let variables = self.structural("variables")?;
self.line(0, &format!("{variables} {{"))?;
if !self.program.global_variables.is_empty() {
let global = self.structural("global")?;
self.line(1, &format!("{global}:"))?;
for variable in self.program.global_variables.iter() {
self.line(2, &format!("{}: {}", variable.index, variable.name))?;
}
}
if !self.program.player_variables.is_empty() {
let player = self.structural("player")?;
self.line(1, &format!("{player}:"))?;
for variable in self.program.player_variables.iter() {
self.line(2, &format!("{}: {}", variable.index, variable.name))?;
}
}
self.line(0, "}")?;
self.out.push('\n');
}
if !self.program.subroutines.is_empty() {
let subroutines = self.structural("subroutines")?;
self.line(0, &format!("{subroutines} {{"))?;
for subroutine in self.program.subroutines.iter() {
self.line(1, &format!("{}: {}", subroutine.index, subroutine.name))?;
}
self.line(0, "}")?;
self.out.push('\n');
}
for (emitted_rules, rule) in self.program.rules.iter().enumerate() {
if emitted_rules > 0 {
self.out.push('\n');
}
self.rule(rule)?;
}
// The oracle's raw artifact ends with a trailing blank line (the
// committed snapshots strip it via the acquisition normalizer; the
// pinned oracle's own output keeps it).
if !self.out.is_empty() && !self.out.ends_with("\n\n") {
self.out.push('\n');
}
Ok(())
}
/// Emit the `settings { ... }` section from the validated settings
/// carrier, table-driven (fixture-evidenced names). Only runs on
/// validated programs, so unknown keys cannot reach this point.
fn emit_settings(&mut self, settings: &SettingsTree) -> Result<()> {
let settings_keyword = self.structural("settings")?;
self.line(0, &format!("{settings_keyword} {{"))?;
for child in &settings.children {
if let SettingsNode::Workshop { children, .. } = child {
self.emit_workshop_settings(children, 1)?;
continue;
}
let SettingsNode::Group { name, children, .. } = child else {
return Err(self.malformed("settings block children must be groups"));
};
match name.as_str() {
"main" | "lobby" => {
self.line(1, &format!("{name} {{"))?;
for member in children {
self.settings_member(member, 2, &[PathPart::Part(name)], None)?;
}
self.line(1, "}")?;
}
"gamemodes" => self.emit_modes(children)?,
"heroes" => self.emit_heroes(children)?,
"extensions" => {
self.line(1, "extensions {")?;
for member in children {
self.settings_member(member, 2, &[PathPart::Part("extensions")], None)?;
}
self.line(1, "}")?;
}
_ => self.emit_opaque_group(children, name, 1)?,
}
}
self.line(0, "}")?;
Ok(())
}
fn emit_workshop_settings(&mut self, children: &[SettingsNode], level: usize) -> Result<()> {
let workshop = self.structural("workshop")?;
self.line(level, &format!("{workshop} {{"))?;
for child in children {
self.emit_workshop_node(child, level + 1)?;
}
self.line(level, "}")?;
Ok(())
}
fn emit_workshop_node(&mut self, node: &SettingsNode, level: usize) -> Result<()> {
match node {
SettingsNode::Group { name, children, .. } => {
self.line(level, &format!("{name} {{"))?;
for child in children {
self.emit_workshop_node(child, level + 1)?;
}
self.line(level, "}")?;
Ok(())
}
SettingsNode::Workshop { children, .. } => self.emit_workshop_settings(children, level),
SettingsNode::Raw { name, value, .. } => {
if value.is_empty() {
self.line(level, name)
} else {
self.line(level, &format!("{name}: {value}"))
}
}
_ => Err(self.malformed("settings.workshop contains a typed builtin setting")),
}
}
/// Emit the `modes { <Mode> { ... } }` block of a gamemodes group.
fn emit_modes(&mut self, modes: &[SettingsNode]) -> Result<()> {
self.line(1, "modes {")?;
for mode in modes {
let SettingsNode::Group { name, children, .. } = mode else {
return Err(self.malformed("mode entries must be groups"));
};
let display = match table::mode_name(name) {
Some(english) => self.setting_name("modes", english, &format!("mode.{name}"))?,
None => name.clone(),
};
// `enabled: false` prefixes the mode header; true renders with no
// prefix (only false is evidenced in the corpus, #86).
let disabled = children.iter().any(|member| {
matches!(
member,
SettingsNode::Bool { name: n, value: false, .. } if n == "enabled"
)
});
let header = if disabled {
let disabled_name = self.setting_name("tokens", "disabled", "token.disabled")?;
format!("{disabled_name} {display}")
} else {
display
};
self.line(2, &format!("{header} {{"))?;
for member in children {
if matches!(member, SettingsNode::Bool { name: n, .. } if n == "enabled") {
continue;
}
self.settings_member(
member,
3,
&[PathPart::Part("gamemodes"), PathPart::Part(name)],
None,
)?;
}
self.line(2, "}")?;
}
self.line(1, "}")?;
Ok(())
}
/// Emit the `heroes { <Team> { ... } }` block of a heroes group.
fn emit_heroes(&mut self, teams: &[SettingsNode]) -> Result<()> {
self.line(1, "heroes {")?;
for team in teams {
let SettingsNode::Group { name, children, .. } = team else {
return Err(self.malformed("team entries must be groups"));
};
let english = table::team_name(name)
.ok_or_else(|| self.malformed(format!("unknown team '{name}'")))?;
let display = self.setting_name("teams", english, &format!("team.{name}"))?;
self.line(2, &format!("{display} {{"))?;
for member in children {
match member {
SettingsNode::Group { name, children, .. } => {
let english = table::hero_name(name)
.ok_or_else(|| self.malformed(format!("unknown hero '{name}'")))?;
let hero = self.setting_name("heroes", english, &format!("hero.{name}"))?;
self.line(3, &format!("{hero} {{"))?;
for inner in children {
self.settings_member(
inner,
4,
&[PathPart::Part("heroes"), PathPart::Team, PathPart::Hero],
Some(name),
)?;
}
self.line(3, "}")?;
}
other => self.settings_member(
other,
3,
&[PathPart::Part("heroes"), PathPart::Team],
None,
)?,
}
}
self.line(2, "}")?;
}
self.line(1, "}")?;
Ok(())
}
/// Emit one leaf-level settings member (`Name: value`, lists as blocks).
fn settings_member(
&mut self,
node: &SettingsNode,
level: usize,
path: &[PathPart],
hero: Option<&str>,
) -> Result<()> {
if let SettingsNode::Raw { name, value, .. } = node {
if value.is_empty() {
self.line(level, name)?;
} else {
self.line(level, &format!("{name}: {value}"))?;
}
return Ok(());
}
let name = node.name();
let mut full = path.to_vec();
full.push(PathPart::Part(name));
let entry = table::lookup(&full).ok_or_else(|| {
self.malformed(format!(
"settings key '{}' is outside the emission table",
table::path_string(&full)
))
})?;
let display_name = if let (Some(hero), Some(key)) = (
hero,
full.last().and_then(|part| match part {
PathPart::Part(key) => Some(*key),
_ => None,
}),
) {
if let Some(name) = table::hero_setting_name(hero, key, self.locale.as_str()) {
name.to_string()
} else if !matches!(
key,
"enableAbility1" | "enableAbility2" | "enableAbility3" | "enableSecondaryFire"
) {
if let Some(slot) = table::ability_slot_for_path(&full) {
self.gameplay_setting_name(hero, slot, &table::path_string(&full))?
} else {
self.setting_name("labels", entry.workshop_name, &table::path_string(&full))?
}
} else {
self.setting_name("labels", entry.workshop_name, &table::path_string(&full))?
}
} else if let (Some(hero), Some(slot)) = (hero, table::ability_slot_for_path(&full)) {
self.gameplay_setting_name(hero, slot, &table::path_string(&full))?
} else {
self.setting_name("labels", entry.workshop_name, &table::path_string(&full))?
};
match (node, &entry.kind) {
(SettingsNode::Flag { .. }, KeyKind::Flag) => {
self.line(level, &display_name)?;
}
(SettingsNode::String { value, .. }, KeyKind::String) => {
self.line(
level,
&format!("{}: \"{}\"", display_name, escape_settings_string(value)),
)?;
}
(SettingsNode::String { value, .. }, KeyKind::Enum(domain)) => {
let english = table::enum_name(domain, value).ok_or_else(|| {
self.malformed(format!("unknown value '{value}' for settings key '{name}'"))
})?;
let display =
self.setting_name("enums", english, &format!("enum.{domain}.{value}"))?;
self.line(level, &format!("{display_name}: {display}"))?;
}
(SettingsNode::Number { value, .. }, KeyKind::Number) => {
self.line(level, &format!("{display_name}: {}", format_number(*value)))?;
}
(SettingsNode::Number { value, .. }, KeyKind::Percent) => {
self.line(
level,
&format!("{display_name}: {}%", format_number(*value)),
)?;
}
(SettingsNode::Bool { value, .. }, KeyKind::Bool) => {
let rendered = self.setting_name(
"tokens",
if *value { "On" } else { "Off" },
if *value { "token.on" } else { "token.off" },
)?;
self.line(level, &format!("{display_name}: {rendered}"))?;
}
(SettingsNode::List { elements, .. }, KeyKind::ListMap) => {
self.line(level, &format!("{display_name} {{"))?;
for element in elements {
let english = table::map_name(&element.value).ok_or_else(|| {
self.malformed(format!(
"unknown map '{}' in settings list '{name}'",
element.value
))
})?;
let display =
self.setting_name("maps", english, &format!("map.{}.name", element.value))?;
self.line(level + 1, &display)?;
}
self.line(level, "}")?;
}
(SettingsNode::List { elements, .. }, KeyKind::ListHero) => {
self.line(level, &format!("{display_name} {{"))?;
for element in elements {
let english = table::hero_name(&element.value).ok_or_else(|| {
self.malformed(format!(
"unknown hero '{}' in settings list '{name}'",
element.value
))
})?;
let display = self.setting_name(
"heroes",
english,
&format!("hero.{}.name", element.value),
)?;
self.line(level + 1, &display)?;
}
self.line(level, "}")?;
}
_ => {
return Err(self.malformed(format!(
"settings key '{name}' does not match its table kind"
)));
}
}
Ok(())
}
fn emit_opaque_group(
&mut self,
children: &[SettingsNode],
name: &str,
level: usize,
) -> Result<()> {
self.line(level, &format!("{name} {{"))?;
for child in children {
match child {
SettingsNode::Group { name, children, .. } => {
self.emit_opaque_group(children, name, level + 1)?;
}
_ => self.settings_member(child, level + 1, &[], None)?,
}
}
self.line(level, "}")?;
Ok(())
}
/// Resolve a settings spelling from the generated locale corpus. The
/// English table remains the explicit fallback only when the caller opts
/// into `en-US`, matching the catalog's missing-mapping contract.
fn gameplay_setting_name(&mut self, hero: &str, slot: &str, id: &str) -> Result<String> {
let resolve = |locale: &Locale| {
crate::gameplay_data::builtin().ok().and_then(|catalog| {
catalog
.query()
.ability_name(hero, slot, None, locale.as_str())
.ok()
.map(str::to_string)
})
};
if let Some(name) = resolve(&self.locale) {
return Ok(name);
}
if let Some(fallback) = &self.fallback {
if let Some(name) = resolve(fallback) {
if !self.fallback_ids.iter().any(|value| value == "settings") {
self.fallback_ids.push("settings".to_string());
}
return Ok(name);
}
}
Err(WorkshopError::MissingMapping {
kind: "setting",
id: id.to_string(),
locale: self.locale.clone(),
})
}
fn setting_name(&mut self, section: &str, english: &str, id: &str) -> Result<String> {
let en_us = Locale::new("en-US");
if self.locale == en_us {
return Ok(english.to_string());
}
if let Some(spelling) = table::localized_name(self.locale.as_str(), section, english) {
return Ok(spelling.to_string());
}
if let Some(fallback) = &self.fallback {
if *fallback == en_us {
if !self.fallback_ids.iter().any(|value| value == "settings") {
self.fallback_ids.push("settings".to_string());
}
return Ok(english.to_string());
}
}
Err(WorkshopError::MissingMapping {
kind: "setting",
id: id.to_string(),
locale: self.locale.clone(),
})
}
fn malformed(&self, message: impl Into<String>) -> WorkshopError {
WorkshopError::Malformed {
message: message.into(),
span: None,
}
}
fn rule(&mut self, rule: &wir::Rule) -> Result<()> {
let disabled = if rule.disabled {
format!("{} ", self.structural("disabled")?)
} else {
String::new()
};
let rule_keyword = self.structural("rule")?;
self.line(
0,
&format!(
"{disabled}{rule_keyword} (\"{}\") {{",
escape_string(&rule.name)
),
)?;
let event = self.structural("event")?;
self.line(1, &format!("{event} {{"))?;
match &rule.event {
wir::Event::Global => {
let spelling = self.spelling(Kind::Event, "global")?;
self.line(2, &format!("{spelling};"))?;
}
wir::Event::EachPlayer => {
let spelling = self.spelling(Kind::Event, "eachPlayer")?;
self.line(2, &format!("{spelling};"))?;
self.event_filters(wir::EventTeam::All, &wir::EventTarget::All)?;
}
wir::Event::EachPlayerWithFilters { team, target } => {
let spelling = self.spelling(Kind::Event, "eachPlayer")?;
self.line(2, &format!("{spelling};"))?;
self.event_filters(*team, target)?;
}
wir::Event::Player { kind, team, target } => {
let spelling = self.spelling(Kind::Event, kind.catalog_id())?;
self.line(2, &format!("{spelling};"))?;
self.event_filters(*team, target)?;
}
wir::Event::Subroutine(subroutine) => {
let spelling = self.spelling(Kind::Event, "subroutine")?;
self.line(2, &format!("{spelling};"))?;
let name = self
.program
.subroutines
.get(*subroutine)
.map(|s| s.name.clone())
.unwrap_or_else(|| "<dangling>".to_string());
self.line(2, &format!("{name};"))?;
}
}
self.line(1, "}")?;
if !rule.conditions.is_empty() {
let conditions = self.structural("conditions")?;
self.line(1, &format!("{conditions} {{"))?;
for condition in &rule.conditions {
let mut text = String::new();
// Reference normalization: comparison conditions render
// infix; other conditions render as `value == True`.
if let Some(wir::Value::Call { name, args }) =
self.program.values.get(*condition).map(|node| &node.value)
{
if is_comparison_operator(name) && args.len() == 2 {
self.value(args[0], &mut text)?;
write!(text, " {name} ").unwrap();
self.value(args[1], &mut text)?;
} else {
self.value(*condition, &mut text)?;
text.push_str(" == True");
}
} else {
self.value(*condition, &mut text)?;
text.push_str(" == True");
}
self.line(2, &format!("{text};"))?;
}
self.line(1, "}")?;
}
if !rule.actions.is_empty() {
let actions = self.structural("actions")?;
self.line(1, &format!("{actions} {{"))?;
for (index, action) in rule.actions.iter().enumerate() {
let rule_final = index + 1 == rule.actions.len();
self.action(*action, 2, rule_final)?;
}
self.line(1, "}")?;
}
self.line(0, "}")?;
Ok(())
}
fn event_filters(&mut self, team: wir::EventTeam, target: &wir::EventTarget) -> Result<()> {
let team = match team {
wir::EventTeam::All => "ALL",
wir::EventTeam::Team1 => "TEAM_1",
wir::EventTeam::Team2 => "TEAM_2",
};
let team = self.enum_spelling("EventTeam", team)?;
self.line(2, &format!("{team};"))?;
let target = match target {
wir::EventTarget::All => self.enum_spelling("EventPlayer", "ALL")?,
wir::EventTarget::Slot(slot) => {
self.enum_spelling("EventPlayer", &format!("SLOT_{slot}"))?
}
wir::EventTarget::Hero(hero) => self.enum_spelling("Hero", hero)?,
};
self.line(2, &format!("{target};"))?;
Ok(())
}
/// Emit one rule action; `rule_final` marks the last action of the rule,
/// for which an `if`/`if-else` closes without the trailing `End;`
/// (the pinned oracle's spelling, #87).
fn action(&mut self, id: wir::ActionId, level: usize, rule_final: bool) -> Result<()> {
let Some(action) = self.program.actions.get(id) else {
return Err(WorkshopError::Malformed {
message: format!("dangling action {id}"),
span: None,
});
};
match action {
wir::Action::SetGlobalVariable {
variable, value, ..
} => {
let name = self.global_name(*variable)?;
let mut value_text = String::new();
self.value(*value, &mut value_text)?;
let keyword = self.spelling(Kind::Structural, "setGlobalVariable")?;
self.line(level, &format!("{keyword}({name}, {value_text});"))?;
}
wir::Action::ModifyGlobalVariable {
variable,
op,
value,
..
} => {
let name = self.global_name(*variable)?;
let op = self.modify_op_spelling(*op)?;
let mut value_text = String::new();
self.value(*value, &mut value_text)?;
let keyword = self.spelling(Kind::Structural, "modifyGlobalVariable")?;
self.line(level, &format!("{keyword}({name}, {op}, {value_text});"))?;
}
wir::Action::SetPlayerVariable {
player,
variable,
value,
..
} => {
let mut player_text = String::new();
self.value(*player, &mut player_text)?;
let name = self.player_name(*variable)?;
let mut value_text = String::new();
self.value(*value, &mut value_text)?;
let keyword = self.spelling(Kind::Structural, "setPlayerVariable")?;
self.line(
level,
&format!("{keyword}({player_text}, {name}, {value_text});"),
)?;
}
wir::Action::ModifyPlayerVariable {
player,
variable,
op,
value,
..
} => {
let mut player_text = String::new();
self.value(*player, &mut player_text)?;
let name = self.player_name(*variable)?;
let op = self.modify_op_spelling(*op)?;
let mut value_text = String::new();
self.value(*value, &mut value_text)?;
let keyword = self.spelling(Kind::Structural, "modifyPlayerVariable")?;
self.line(
level,
&format!("{keyword}({player_text}, {name}, {op}, {value_text});"),
)?;
}
wir::Action::CallSubroutine { subroutine, .. } => {
let name = self
.program
.subroutines
.get(*subroutine)
.map(|s| s.name.clone())
.ok_or_else(|| WorkshopError::Unknown {
kind: "subroutine",
spelling: format!("<{subroutine}>"),
locale: self.locale.clone(),
span: None,
})?;
let keyword = self.spelling(Kind::Structural, "callSubroutine")?;
self.line(level, &format!("{keyword}({name});"))?;
}
wir::Action::If {
branches,
else_body,
..
} => {
for (index, branch) in branches.iter().enumerate() {
let mut condition = String::new();
self.value(branch.condition, &mut condition)?;
let keyword =
self.spelling(Kind::Structural, if index == 0 { "if" } else { "elseIf" })?;
self.line(level, &format!("{keyword}({condition});"))?;
for action in &branch.body {
self.action(*action, level + 1, false)?;
}
}
if let Some(else_body) = else_body {
let keyword = self.spelling(Kind::Structural, "else")?;
self.line(level, &format!("{keyword};"))?;
for action in else_body {
self.action(*action, level + 1, false)?;
}
}
// A rule-final if closes the rule without `End;` (oracle
// spelling); nested and middle-of-rule ifs keep it.
if !rule_final {
let keyword = self.spelling(Kind::Structural, "end")?;
self.line(level, &format!("{keyword};"))?;
}
}
wir::Action::While {
condition, body, ..
} => {
let mut text = String::new();
self.value(*condition, &mut text)?;
let keyword = self.spelling(Kind::Structural, "while")?;
self.line(level, &format!("{keyword}({text});"))?;
for action in body {
self.action(*action, level + 1, false)?;
}
let end = self.spelling(Kind::Structural, "end")?;
self.line(level, &format!("{end};"))?;
}
wir::Action::ForGlobalVariable {
variable,
start,
stop,
step,
body,
..
} => {
let name = self.global_name(*variable)?;
let mut start_text = String::new();
let mut stop_text = String::new();
let mut step_text = String::new();
self.value(*start, &mut start_text)?;
self.value(*stop, &mut stop_text)?;
self.value(*step, &mut step_text)?;
let keyword = self.spelling(Kind::Structural, "forGlobalVariable")?;
self.line(
level,
&format!("{keyword}({name}, {start_text}, {stop_text}, {step_text});"),
)?;
for action in body {
self.action(*action, level + 1, false)?;
}
let end = self.spelling(Kind::Structural, "end")?;
self.line(level, &format!("{end};"))?;
}
wir::Action::ForPlayerVariable {
player,
variable,
start,
stop,
step,
body,
..
} => {
let keyword = self.structural("forPlayerVariable")?;
let mut player_text = String::new();
let mut start_text = String::new();
let mut stop_text = String::new();
let mut step_text = String::new();
self.value(*player, &mut player_text)?;
self.value(*start, &mut start_text)?;
self.value(*stop, &mut stop_text)?;
self.value(*step, &mut step_text)?;
let name = self.player_name(*variable)?;
self.line(
level,
&format!(
"{}({player_text}, {name}, {start_text}, {stop_text}, {step_text});",
keyword
),
)?;
for action in body {
self.action(*action, level + 1, false)?;
}
let end = self.spelling(Kind::Structural, "end")?;
self.line(level, &format!("{end};"))?;
}
wir::Action::Debug { value, .. } => {
// `debug(value)` displays the value as HUD text. The
// reference formats values with type-aware machinery; Wright
// emits a semantically equivalent but presentation-simpler
// Create HUD Text (documented intentional difference).
self.emit_hud_text(*value, level, true)?;
}
wir::Action::Print { message, .. } => {
self.emit_hud_text(*message, level, false)?;
}
wir::Action::AssignMember {
target, op, value, ..
} => {
let mut target_text = String::new();
let mut value_text = String::new();
self.value(*target, &mut target_text)?;
self.value(*value, &mut value_text)?;
let operator = match op {
None => "=".to_string(),
Some(op) => {
let token = match op {
wir::ModifyOp::Add => "+",
wir::ModifyOp::Subtract => "-",
wir::ModifyOp::Multiply => "*",
wir::ModifyOp::Divide => "/",
wir::ModifyOp::Modulo => "%",
_ => {
return Err(WorkshopError::Unsupported {
message: format!(
"unsupported member assignment operator {op:?}"
),
span: None,
});
}
};
format!("{token}=")
}
};
self.line(level, &format!("{target_text} {operator} {value_text};"))?;
}
wir::Action::Call { name, args, .. } => {
// The chase family dispatches on the first argument's
// variable kind, mirroring the pinned reference: a global
// variable emits the global form with the argument list
// unchanged; a player variable emits the player form with
// the receiver split into `player, name` leading arguments
// (the frontend guarantees a variable first argument,
// issue #110).
if matches!(name.as_str(), "chaseAtRate" | "chaseOverTime") {
let player_var = args.first().and_then(|id| {
self.program
.values
.get(*id)
.and_then(|node| match &node.value {
wir::Value::PlayerVariable { player, variable } => {
Some((*player, *variable))
}
_ => None,
})
});
let spelling = if let Some((player, variable)) = player_var {
let id = if name == "chaseAtRate" {
"chasePlayerVariableAtRate"
} else {
"chasePlayerVariableOverTime"
};
let spelling = self.spelling(Kind::Action, id)?;
// `Chase Player Variable At Rate(player, name, …)`:
// the receiver splits into `player, name` leading
// arguments (the pinned oracle's spelling).
let mut text = String::new();
self.value(player, &mut text)?;
let mut parts = vec![text, self.player_name(variable)?];
for arg in args.iter().skip(1) {
let mut part = String::new();
self.value(*arg, &mut part)?;
parts.push(part);
}
return self.line(level, &format!("{spelling}({});", parts.join(", ")));
} else {
self.spelling(Kind::Action, name)?
};
let mut args_text = String::new();
self.args(args, &mut args_text)?;
return self.line(level, &format!("{spelling}({args_text});"));
}
if name == "stopChasingPlayerVariable" {
let Some((player, variable)) = args.first().and_then(|id| {
self.program
.values
.get(*id)
.and_then(|node| match &node.value {
wir::Value::PlayerVariable { player, variable } => {
Some((*player, *variable))
}
_ => None,
})
}) else {
return Err(WorkshopError::Malformed {
message: "Stop Chasing Player Variable requires a player variable"
.into(),
span: None,
});
};
let spelling = self.spelling(Kind::Action, name)?;
let mut player_text = String::new();
self.value(player, &mut player_text)?;
return self.line(
level,
&format!(
"{spelling}({player_text}, {});",
self.player_name(variable)?
),
);
}
// Native `.opy` action names map to canonical catalog ids at
// emission (presentation concern).
let canonical = match name.as_str() {
"createBeam" => Some("createBeamEffect"),
_ => None,
};
let spelling = if let Some(canonical) = canonical {
self.spelling(Kind::Action, canonical)?
} else {
self.spelling(Kind::Action, name)?
};
if args.is_empty() {
self.line(level, &format!("{spelling};"))?;
} else {
let mut args_text = String::new();
for (index, arg) in args.iter().enumerate() {
if index > 0 {
args_text.push_str(", ");
}
let variable_position = match name.as_str() {
"setGlobalVariableAtIndex" | "modifyGlobalVariableAtIndex" => {
index == 0
}
"setPlayerVariableAtIndex" | "modifyPlayerVariableAtIndex" => {
index == 1
}
_ => false,
};
if variable_position {
if let Some(node) = self.program.values.get(*arg) {
match &node.value {
wir::Value::GlobalVariable(variable) => {
args_text.push_str(&self.global_name(*variable)?);
continue;
}
wir::Value::PlayerVariable { variable, .. } => {
args_text.push_str(&self.player_name(*variable)?);
continue;
}
_ => {}
}
}
}
self.value(*arg, &mut args_text)?;
}
self.line(level, &format!("{spelling}({args_text});"))?;
}
}
}
Ok(())
}
/// Emit a `debug`/`print` action as a `Create HUD Text` effect.
///
/// `debug` renders the value into the HUD body; `print` renders the
/// message directly (a `format` value already carries the text). Every
/// fixed token resolves through the catalog, so the effect is
/// locale-correct by data and fails explicitly on missing target-locale
/// mappings.
fn emit_hud_text(&mut self, value: wir::ValueId, level: usize, is_debug: bool) -> Result<()> {
let mut body = String::new();
if is_debug {
// Display the value in the HUD body: Custom String("{0}", value).
body.push_str(&self.spelling(Kind::Value, "customString")?);
body.push_str("(\"{0}\", ");
self.value(value, &mut body)?;
body.push(')');
} else {
self.value(value, &mut body)?;
}
// Create HUD Text(All Players(All Teams), Null, header, body, text,
// location, sort order, header color, subheader color, text color,
// reevaluation, spectators) — the canonical catalog layout (probe P6
// emission), so the emitted text reparses against the catalog's
// expected enum domains at the canonical positions.
let mut line = String::new();
line.push_str(&self.spelling(Kind::Action, "createHudText")?);
line.push('(');
line.push_str(&self.spelling(Kind::Value, "allPlayers")?);
line.push('(');
line.push_str(&self.enum_spelling("Team", "ALL")?);
line.push_str("), Null, ");
line.push_str(&body);
line.push_str(", Null, ");
line.push_str(&self.enum_spelling("HudPosition", "LEFT")?);
line.push_str(", -9999, Color(");
line.push_str(&self.enum_spelling("Color", "WHITE")?);
line.push_str("), Color(");
line.push_str(&self.enum_spelling("Color", "WHITE")?);
line.push_str("), Color(");
line.push_str(&self.enum_spelling("Color", "WHITE")?);
line.push_str("), ");
line.push_str(&self.enum_spelling("HudReeval", "VISIBILITY_AND_STRING")?);
line.push_str(", ");
line.push_str(&self.enum_spelling("SpecVisibility", "VISIBLE_ALWAYS")?);
line.push_str(");");
self.line(level, &line)?;
Ok(())
}
fn args(&mut self, args: &[wir::ValueId], out: &mut String) -> Result<()> {
for (index, arg) in args.iter().enumerate() {
if index > 0 {
out.push_str(", ");
}
self.value(*arg, out)?;
}
Ok(())
}
fn value(&mut self, id: wir::ValueId, out: &mut String) -> Result<()> {
let Some(node) = self.program.values.get(id) else {
return Err(WorkshopError::Malformed {
message: format!("dangling value {id}"),
span: None,
});
};
match &node.value {
wir::Value::Number { text, .. } => {
// Literal spellings carry through (the oracle preserves the
// source spelling, e.g. `0.0`; computed values carry the
// formatted spelling, #87).
out.push_str(text);
}
wir::Value::String(value) => {
// Value-position strings wrap in `Custom String("...")` with
// re-escaped content and long-string splitting, the pinned
// oracle's spelling (evidence: array elements, initializers,
// assignments, call arguments, comparisons — #87). The only
// bare string value is the `Custom String` text argument,
// handled in the call arm below.
self.emit_string_value(value, out)?;
}
wir::Value::LocalizedString(id) => {
out.push_str(&self.spelling(Kind::Value, "string")?);
out.push('(');
let spelling = self.localized_string_spelling(id)?;
write!(out, "\"{}\"", escape_value_string(&spelling)).unwrap();
out.push(')');
}
wir::Value::Bool(true) => out.push_str("True"),
wir::Value::Bool(false) => out.push_str("False"),
wir::Value::Null => out.push_str("Null"),
wir::Value::Array(elements) => {
if elements.is_empty() {
// The canonical empty-array constant (reference emission).
out.push_str(&self.spelling(Kind::Value, "emptyArray")?);
} else {
out.push_str(&self.spelling(Kind::Value, "array")?);
out.push('(');
self.args(elements, out)?;
out.push(')');
}
}
wir::Value::Vector { x, y, z } => {
out.push_str(&self.spelling(Kind::Value, "vector")?);
out.push('(');
self.value(*x, out)?;
out.push_str(", ");
self.value(*y, out)?;
out.push_str(", ");
self.value(*z, out)?;
out.push(')');
}
wir::Value::Enum { value_type, value } => {
let spelling = self.enum_spelling(value_type, value)?;
// Color, Team, and Hero values use the constructor form;
// other domains use bare member spellings (the canonical
// corpus form). The
// Team/Color spelling collision (`Team 2` is both a Team and
// a Team color) is the one ambiguity unpinned by the
// catalog's paramDomains, so Team members qualify with the
// constructor form and the emitted text reparses
// deterministically (round-trip contract; pinned P4
// evidence).
if matches!(value_type.as_str(), "Color" | "Map" | "Team")
|| value_type == "Hero"
&& (spelling.contains('.')
|| self.locale != *self.catalog.primary_locale()
|| (self.force_hero_constructors
&& self
.program
.global_variables
.iter()
.any(|variable| variable.name == spelling)))
{
let domain = self
.catalog
.enum_domain(value_type)
.and_then(|entry| entry.spelling(&self.locale))
.unwrap_or(value_type);
write!(out, "{domain}({spelling})").unwrap();
} else {
out.push_str(&spelling);
}
}
wir::Value::GlobalVariable(variable) => {
let name = self.global_name(*variable)?;
write!(out, "Global.{name}").unwrap();
}
wir::Value::PlayerVariable { player, variable } => {
// The oracle's spelling parenthesizes the receiver:
// `Set Global Variable(g, (Event Player).p)` (#87).
out.push('(');
self.value(*player, out)?;
out.push(')');
let name = self.player_name(*variable)?;
write!(out, ".{name}").unwrap();
}
wir::Value::Subroutine(subroutine) => {
let name = self
.program
.subroutines
.get(*subroutine)
.map(|value| value.name.clone())
.ok_or_else(|| WorkshopError::Malformed {
message: format!("dangling subroutine value {subroutine}"),
span: None,
})?;
out.push_str(&name);
}
wir::Value::EventPlayer => out.push_str(&self.spelling(Kind::Value, "eventPlayer")?),
wir::Value::Call { name, args } => {
if name == "memberAccess" {
if args.len() < 2 || args.len() > 3 {
return Err(WorkshopError::Malformed {
message: "memberAccess expects two or three arguments".to_string(),
span: node.span,
});
}
let Some(wir::ValueNode {
value: wir::Value::String(member),
..
}) = self.program.values.get(args[1])
else {
return Err(WorkshopError::Malformed {
message: "memberAccess member must be a string".to_string(),
span: node.span,
});
};
let bare_event_player = self
.program
.values
.get(args[0])
.is_some_and(|node| matches!(node.value, wir::Value::EventPlayer));
if !bare_event_player {
out.push('(');
}
self.value(args[0], out)?;
if !bare_event_player {
out.push(')');
}
write!(out, ".{member}").unwrap();
if let Some(index) = args.get(2) {
out.push('[');
self.value(*index, out)?;
out.push(']');
}
return Ok(());
}
if is_comparison_operator(name) {
// Canonical form: Compare(a, op, b).
if args.len() != 2 {
return Err(WorkshopError::Malformed {
message: format!("comparison call '{name}' must have 2 args"),
span: None,
});
}
out.push_str(&self.spelling(Kind::Value, "compare")?);
out.push('(');
self.value(args[0], out)?;
write!(out, ", {name}, ").unwrap();
self.value(args[1], out)?;
out.push(')');
return Ok(());
}
// Unary minus renders as Multiply(-1, x); the reference folds
// literal negation, handled by the compat constant-fold pass.
if name == "-" && args.len() == 1 {
out.push_str(&self.spelling(Kind::Value, "multiply")?);
out.push_str("(-1, ");
self.value(args[0], out)?;
out.push(')');
return Ok(());
}
// `getAllPlayers()` is OverPy's All Players(All Teams).
if name == "getAllPlayers" && args.is_empty() {
out.push_str(&self.spelling(Kind::Value, "allPlayers")?);
out.push('(');
out.push_str(&self.enum_spelling("Team", "ALL")?);
out.push(')');
return Ok(());
}
// Binary arithmetic operators and native `.opy` source names
// map to canonical catalog ids at emission (presentation
// concern; the compat pass folds constants to match the
// reference exactly).
let canonical = match name.as_str() {
"+" => Some("add"),
"-" => Some("subtract"),
"*" => Some("multiply"),
"/" => Some("divide"),
"len" => Some("countOf"),
"abs" => Some("absoluteValue"),
"sqrt" => Some("squareRoot"),
"createBeam" => Some("createBeamEffect"),
"random.uniform" => Some("randomReal"),
"random.choice" => Some("randomValueInArray"),
"format" => Some("customString"),
_ => None,
};
let spelling = if let Some(canonical) = canonical {
self.spelling(Kind::Value, canonical)?
} else {
self.spelling(Kind::Value, name)?
};
// `format` (frontend) and `customString` (parsed ws text) are
// the same node.
let is_custom_string = canonical == Some("customString") || name == "customString";
if name == "string" {
out.push_str(&spelling);
out.push('(');
if let Some(first) = args.first() {
self.localized_string_value(*first, out)?;
if args.len() > 1 {
out.push_str(", ");
self.args(&args[1..], out)?;
}
}
out.push(')');
} else if args.is_empty() {
// Constants (e.g. Empty Array) emit as bare spellings.
out.push_str(&spelling);
} else if is_custom_string {
// `.format()` calls canonicalize: constant numeric
// arguments fold into the substituted text, implicit
// `{}` placeholders renumber to the oracle's explicit
// form, and remaining variable arguments wrap (the
// oracle spelling, #87). The canonical text feeds the
// value-string path (re-escaping/splitting) when no
// arguments remain.
match self.canonicalize_format_call(args)? {
Some((text, variable_args)) => {
if variable_args.is_empty() {
self.emit_string_value(&text, out)?;
} else {
out.push_str(&spelling);
out.push('(');
write!(out, "\"{}\"", escape_value_string(&text)).unwrap();
if !variable_args.is_empty() {
out.push_str(", ");
}
self.args(&variable_args, out)?;
out.push(')');
}
}
None => {
// The `Custom String` text argument stays bare
// (the oracle spelling); the remaining arguments
// are values and wrap (#87).
out.push_str(&spelling);
out.push('(');
self.bare_string_value(args[0], out)?;
if args.len() > 1 {
out.push_str(", ");
}
self.args(&args[1..], out)?;
out.push(')');
}
}
} else {
out.push_str(&spelling);
out.push('(');
self.args(args, out)?;
out.push(')');
}
}
}
Ok(())
}
fn localized_string_value(&mut self, id: wir::ValueId, out: &mut String) -> Result<()> {
let Some(node) = self.program.values.get(id) else {
return Err(WorkshopError::Malformed {
message: format!("dangling value {id}"),
span: None,
});
};
let wir::Value::LocalizedString(id) = &node.value else {
return Err(WorkshopError::Unsupported {
message: "value 'string' argument 1 must be localized string text".to_string(),
span: node.span,
});
};
let spelling = self.localized_string_spelling(id)?;
write!(out, "\"{}\"", escape_value_string(&spelling)).unwrap();
Ok(())
}
/// Fold a `Custom String` call whose text argument and constant numeric
/// arguments are all literals into the substituted text (the oracle's
/// Canonicalize a `Custom String`/`.format()` call (#87): constant
/// numeric arguments fold into the substituted text (the oracle's
/// spelling), implicit `{}` placeholders renumber positionally to the
/// explicit `{N}` form, and the remaining variable arguments are
/// returned in placeholder order. Returns `None` (rendered unchanged)
/// when nothing canonicalizes: explicit-only texts without constants,
/// texts mixing implicit and explicit placeholders (the oracle rejects
/// those), out-of-range placeholders, or non-String text arguments.
fn canonicalize_format_call(
&self,
args: &[wir::ValueId],
) -> Result<Option<(String, Vec<wir::ValueId>)>> {
if args.len() < 2 {
return Ok(None);
}
let Some(text) = self.program.values.get(args[0]) else {
return Ok(None);
};
let wir::Value::String(text) = &text.value else {
return Ok(None);
};
let format_args = &args[1..];
// Classify the placeholders: implicit `{}` consumes the next
// argument, explicit `{N}` references argument N.
let mut has_implicit = false;
let mut has_explicit = false;
let mut out_of_range = false;
let mut cursor = 0usize;
let mut chars = text.chars().peekable();
while let Some(ch) = chars.next() {
if ch == '{' {
let mut inner = String::new();
let mut closed = false;
for next in chars.by_ref() {
if next == '}' {
closed = true;
break;
}
inner.push(next);
}
if !closed {
break; // unterminated brace: literal text
}
if inner.is_empty() {
if cursor >= format_args.len() {
out_of_range = true;
}
cursor += 1;
has_implicit = true;
} else if inner.chars().all(|c| c.is_ascii_digit()) {
match inner.parse::<usize>() {
Ok(index) if index < format_args.len() => has_explicit = true,
_ => out_of_range = true,
}
} else {
out_of_range = true;
}
}
}
if out_of_range || (has_implicit && has_explicit) {
return Ok(None);
}
let mut any_constant = false;
for id in format_args {
let Some(node) = self.program.values.get(*id) else {
return Ok(None);
};
if matches!(node.value, wir::Value::Number { .. }) {
any_constant = true;
}
}
if !has_implicit && !any_constant {
return Ok(None);
}
// Canonicalize: fold constants inline at their placeholder, renumber
// variable placeholders positionally, keep variable arguments in
// placeholder order.
let mut canonical = String::with_capacity(text.len());
let mut variable_args = Vec::new();
let mut variable_index = 0usize;
let mut cursor = 0usize;
let mut chars = text.chars().peekable();
while let Some(ch) = chars.next() {
if ch == '{' {
let mut inner = String::new();
let mut closed = false;
for next in chars.by_ref() {
if next == '}' {
closed = true;
break;
}
inner.push(next);
}
if !closed {
canonical.push('{');
canonical.push_str(&inner);
break;
}
let index = if inner.is_empty() {
let index = cursor;
cursor += 1;
index
} else {
match inner.parse::<usize>() {
Ok(index) => index,
Err(_) => {
canonical.push('{');
canonical.push_str(&inner);
canonical.push('}');
continue;
}
}
};
let Some(arg) = format_args.get(index).copied() else {
canonical.push('{');
canonical.push_str(&inner);
canonical.push('}');
continue;
};
let node = self.program.values.get(arg);
if let Some(wir::Value::Number { value, .. }) = node.map(|node| &node.value) {
canonical.push_str(&fold_number(*value));
} else {
write!(canonical, "{{{variable_index}}}").unwrap();
variable_index += 1;
variable_args.push(arg);
}
} else {
canonical.push(ch);
}
}
Ok(Some((canonical, variable_args)))
}
/// The localized spelling of a modify operator, resolved through the
/// catalog (fallback-aware).
fn modify_op_spelling(&mut self, op: wir::ModifyOp) -> Result<String> {
let id = match op {
wir::ModifyOp::Add => "add",
wir::ModifyOp::Subtract => "subtract",
wir::ModifyOp::Multiply => "multiply",
wir::ModifyOp::Divide => "divide",
wir::ModifyOp::Modulo => "modulo",
wir::ModifyOp::RaiseToPower => "raiseToPower",
wir::ModifyOp::AppendToArray => "appendToArray",
wir::ModifyOp::RemoveFromArray => "removeFromArray",
wir::ModifyOp::RemoveFromArrayByIndex => "removeFromArrayByIndex",
};
self.spelling(Kind::Operator, id)
}
/// The localized spelling of a canonical builtin id, resolving through
/// the catalog: a dangling id is `Unknown`, an id without a target-locale
/// mapping is `MissingMapping` unless an opt-in fallback locale declares
/// one (recorded in [`Emitter::fallback_ids`]).
fn spelling(&mut self, kind: Kind, id: &str) -> Result<String> {
let Some(entry) = self.catalog.entry(kind, id) else {
return Err(WorkshopError::Unknown {
kind: kind.as_str(),
spelling: id.to_string(),
locale: self.locale.clone(),
span: None,
});
};
if let Some(spelling) = entry.spelling(&self.locale) {
return Ok(spelling.to_string());
}
if let Some(fallback) = &self.fallback {
if let Some(spelling) = entry.spelling(fallback) {
self.fallback_ids.push(id.to_string());
return Ok(spelling.to_string());
}
}
Err(WorkshopError::MissingMapping {
kind: kind.as_str(),
id: id.to_string(),
locale: self.locale.clone(),
})
}
fn localized_string_spelling(&mut self, id: &str) -> Result<String> {
if let Some(spelling) = self.catalog.localized_string_spelling(&self.locale, id) {
return Ok(spelling.to_string());
}
if let Some(fallback) = &self.fallback {
if let Some(spelling) = self.catalog.localized_string_spelling(fallback, id) {
self.fallback_ids.push(format!("localizedString.{id}"));
return Ok(spelling.to_string());
}
}
if self.catalog.localized_strings().any(|entry| entry.id == id) {
return Err(WorkshopError::MissingMapping {
kind: "localized string",
id: id.to_string(),
locale: self.locale.clone(),
});
}
Err(WorkshopError::Unknown {
kind: "localized string",
spelling: id.to_string(),
locale: self.locale.clone(),
span: None,
})
}
fn structural(&mut self, id: &str) -> Result<String> {
self.spelling(Kind::Structural, id)
}
/// The localized spelling of a canonical enum member, resolving through
/// the catalog (fallback-aware; see [`Emitter::spelling`]).
fn enum_spelling(&mut self, domain: &str, member: &str) -> Result<String> {
let Some(domain_entry) = self.catalog.enum_domain(domain) else {
return Err(WorkshopError::Unknown {
kind: "enum domain",
spelling: domain.to_string(),
locale: self.locale.clone(),
span: None,
});
};
let Some(member_entry) = domain_entry.members.iter().find(|m| m.member == member) else {
return Err(WorkshopError::Unknown {
kind: "enum member",
spelling: format!("{domain}.{member}"),
locale: self.locale.clone(),
span: None,
});
};
if let Some(spelling) = member_entry.spelling(&self.locale) {
return Ok(spelling.to_string());
}
if let Some(fallback) = &self.fallback {
if let Some(spelling) = member_entry.spelling(fallback) {
self.fallback_ids.push(format!("{domain}.{member}"));
return Ok(spelling.to_string());
}
}
Err(WorkshopError::MissingMapping {
kind: "enum member",
id: format!("{domain}.{member}"),
locale: self.locale.clone(),
})
}
/// Render a value that must stay a bare string (the `Custom String` text
/// argument). Any non-string value falls back to the normal renderer.
fn bare_string_value(&mut self, id: wir::ValueId, out: &mut String) -> Result<()> {
let Some(node) = self.program.values.get(id) else {
return Err(WorkshopError::Malformed {
message: format!("dangling value {id}"),
span: None,
});
};
if let wir::Value::String(value) = &node.value {
write!(out, "\"{}\"", escape_value_string(value)).unwrap();
return Ok(());
}
self.value(id, out)
}
/// Emit a value-position string as `Custom String("...")`, splitting it
/// into a continuation chain when it exceeds the Workshop 128-char limit.
fn emit_string_value(&mut self, value: &str, out: &mut String) -> Result<()> {
let spelling = self.spelling(Kind::Value, "customString")?;
let segments = split_string(value);
emit_string_chain(&spelling, &segments, out);
Ok(())
}
fn global_name(&self, id: wir::GlobalVarId) -> Result<String> {
self.program
.global_variables
.get(id)
.map(|variable| variable.name.clone())
.ok_or_else(|| WorkshopError::Unknown {
kind: "global variable",
spelling: format!("<{id}>"),
locale: self.locale.clone(),
span: None,
})
}
fn player_name(&self, id: wir::PlayerVarId) -> Result<String> {
self.program
.player_variables
.get(id)
.map(|variable| variable.name.clone())
.ok_or_else(|| WorkshopError::Unknown {
kind: "player variable",
spelling: format!("<{id}>"),
locale: self.locale.clone(),
span: None,
})
}
fn line(&mut self, level: usize, text: &str) -> Result<()> {
for _ in 0..level {
self.out.push_str(" ");
}
self.out.push_str(text);
self.out.push('\n');
Ok(())
}
}
/// Format a float like the reference frontend: integers print without a
/// decimal point, and non-integers print the shortest round-trip
/// representation truncated to 16 significant digits (OverPy behavior;
/// evidence: the pinned oracle snapshots).
fn is_comparison_operator(name: &str) -> bool {
matches!(name, "==" | "!=" | "<" | "<=" | ">" | ">=")
}
fn escape_string(value: &str) -> String {
value.replace('"', "\\\"")
}
/// Re-escape a decoded value string the way the pinned oracle does (#87):
/// `\`, `"`, newline, and carriage return re-escape; tabs pass through raw
/// (byte-measured oracle behavior: `a\tb` emits a real tab, `a\nb` emits the
/// literal two-character `\n`).
fn escape_value_string(value: &str) -> String {
let mut out = String::with_capacity(value.len());
for ch in value.chars() {
match ch {
'\\' => out.push_str("\\\\"),
'"' => out.push_str("\\\""),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
other => out.push(other),
}
}
out
}
/// Split a decoded string per the oracle's long-string rule (#87): when the
/// decoded length exceeds the Workshop 128-char limit, non-final segments
/// hold exactly 125 decoded chars and are emitted with a `{0}` continuation
/// placeholder (128 total text chars), chained as nested `Custom String`
/// arguments; the final segment holds the remainder without a placeholder.
/// Segment texts are re-escaped. Byte-measured basis: chunk sizes are
/// counted on the decoded string (70 escaped newlines — 140 escaped chars,
/// 70 decoded — emit unsplit; 129 decoded newlines split at 125 decoded).
fn split_string(value: &str) -> Vec<String> {
if value.chars().count() <= 128 {
return vec![escape_value_string(value)];
}
let mut segments = Vec::new();
let mut rest = value;
while rest.chars().count() > 125 {
let chunk: String = rest.chars().take(125).collect();
let mut text = escape_value_string(&chunk);
text.push_str("{0}");
segments.push(text);
rest = &rest[chunk.len()..];
}
if !rest.is_empty() {
segments.push(escape_value_string(rest));
}
segments
}
/// Escape a settings string value the way the pinned oracle does: every
/// decode the JSONC parser performed is re-escaped, so decoded values
/// round-trip to the oracle's spelling. Evidence: the inputhud description
/// (`\n` in the source block) is emitted by the oracle as the literal
/// two-character sequence `\n` in the Workshop settings section.
fn escape_settings_string(value: &str) -> String {
let mut out = String::with_capacity(value.len());
for ch in value.chars() {
match ch {
'\\' => out.push_str("\\\\"),
'"' => out.push_str("\\\""),
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
'\r' => out.push_str("\\r"),
other => out.push(other),
}
}
out
}
/// Emit the nested continuation chain
/// `Custom String(seg0, Custom String(seg1, ...))`; segment texts are
/// pre-escaped, non-final segments carry the `{0}` placeholder. Iterative:
/// every segment except the first opens a `Custom String` level, then all
/// levels close.
fn emit_string_chain(spelling: &str, segments: &[String], out: &mut String) {
let Some((first, rest)) = segments.split_first() else {
return;
};
out.push_str(spelling);
out.push('(');
write!(out, "\"{first}\"").unwrap();
for segment in rest {
out.push_str(", ");
out.push_str(spelling);
out.push('(');
write!(out, "\"{segment}\"").unwrap();
}
for _ in 0..=rest.len() {
out.push(')');
}
}
/// Render a constant format argument the way the oracle folds it: integers
/// without decimals, non-integers with exactly two decimals (JS `toFixed(2)`
/// rounding: `0.5` -> `0.50`, `0.125` -> `0.13`, #87).
fn fold_number(value: f64) -> String {
if value.fract() == 0.0 && value.abs() < 1e15 {
format!("{}", value as i64)
} else {
let scaled = (value * 100.0).round();
let sign = if scaled < 0.0 { "-" } else { "" };
let scaled = scaled.abs() as i64;
format!("{sign}{}.{:02}", scaled / 100, scaled % 100)
}
}