flm-core 0.7.0

FLM semantic markup framework — core library, built on techy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
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
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
//! [`mint_packages`], which builds the techy packages and the fallback provider
//! from the features' declarations, and reports as [`MintError`] values the
//! declarations that do not fit.
//!
//! [`mint_packages`] takes the declarations of every feature and returns the
//! [`MintedProviders`] that the language build
//! ([`build_language`](crate::lang::build_language)) installs. Every
//! specification a parse can resolve comes from here. The [module
//! documentation](super) explains minting and the terms techy package,
//! specification and scope stack.
//!
//! # What minting builds
//!
//! - **The features' techy packages**, holding every element declaration
//!   under every name it is written under. A feature has one techy package
//!   per weakness ([`ElementDef::weak`]) and distinct set of parsing modes
//!   its declarations list, in the order these first appear. The first is
//!   named after the feature, and is the only one when all of the feature's
//!   declarations have the same weakness and list the same modes; each
//!   further one is named `<feature>#<n>`, with `n` counting from 2. The
//!   language build puts on the scope stack every package of weak
//!   declarations under every package of ordinary declarations. Each of the
//!   two parts is in registration order (each feature at the place of its
//!   first element declaration, so that the declarations a feature makes
//!   from a finalizer join its others), with a feature's own packages in the
//!   order they first appear, so a later feature's package shadows an
//!   earlier one's.
//!
//!   Because a techy package holds one entry per callable kind and name,
//!   these several packages let one feature declare one name twice in
//!   parsing modes that do not overlap (a text-only `\vec` and a
//!   mathematics-only `\vec`). Declaring one name twice in modes that
//!   overlap is reported ([`MintError::Redeclared`]).
//! - **The scoped packages**, one techy package per [`ScopedPackageDef`].
//!   They are not on the scope stack: an environment body or an argument that
//!   refers to one adds it to the scope stack while that body or argument is
//!   parsed. Each is built after the scoped packages its own declarations
//!   refer to (in an environment's body or in any argument), so a reference
//!   always finds a package that already exists.
//! - **The fallback provider** ([`FlmFallbackProvider`]), at the bottom of
//!   the scope stack, which resolves a command that no declaration defines.
//! - **The fields package**, holding the specifications of tack-on fields.
//!
//! Every specification is one of the types of [`super::specs`] and carries a
//! provenance stamp (techy's
//! [`SpecProvenance`](techy::core::specs::SpecProvenance)): the record,
//! issued by the techy package the specification is inserted into, of that
//! package and of the key the specification is held under. A serialized tree
//! ([`crate::lang::serialize`]) refers to a specification through its stamp.
//!
//! # Two features that define one name
//!
//! Minting detects clashes on the built techy packages themselves, asking
//! each for the names it registers, per callable kind and per parsing mode.
//! Each parsing mode is decided on its own.
//!
//! A declaration is ordinary or weak ([`ElementDef::weak`]). Where one or
//! more features declare a name ordinarily in a mode, the weak declarations
//! of that name play no part in that mode, whatever the order of the
//! features: their packages are under every package of ordinary
//! declarations on the scope stack, and nothing is reported about them. The
//! rules below then decide among the ordinary declarations; where only weak
//! declarations of the name exist in the mode, they decide among the weak
//! ones in the same way. The feature order, its chains and the overrides
//! never make a weak declaration apply over an ordinary one.
//!
//! Where two or more features define a name in one mode (among the
//! declarations that the previous paragraph leaves), registration order
//! decides which definition applies in that mode: the later feature's techy
//! package is innermost on the scope stack and shadows the others. The
//! registration order is the final order of the features, which the chains
//! of the feature order decide ([`crate::core::registry::order`]).
//!
//! Such a collision is allowed in a mode when the feature registered last
//! among the features that define the name in that mode is explicitly after
//! every other of them in the feature order (`a < b` lets `b` define a name
//! `a` defines), or when that feature declared an override ([`OverrideDef`]):
//! the collision is then intended and is not reported. Otherwise it is one
//! [`MintError::Clash`] for that mode, which lists every feature that defines
//! the name in it and the chains of the feature order that would settle it
//! without contradicting the explicit order in force. Only the override of
//! the definition that applies is consulted: an override that another of
//! those features declared has no effect.
//!
//! Definitions in different modes never clash: a `\vec` for text and a `\vec`
//! for mathematics are two different commands. A feature that defines a name
//! in text mode only and another that defines it in math mode only are
//! therefore never in a collision, even where a third feature defines the name
//! in both modes; that third feature then meets each of them in one mode.
//!
//! One feature that declares one name twice in parsing modes that overlap is
//! reported ([`MintError::Redeclared`]), whatever the weakness of the two
//! declarations. A declaration with no syntax ignores the mark, as it ignores
//! its modes.
//!
//! A declaration in a scoped package may not be weak
//! ([`MintError::WeakInScopedPackage`]): whoever adds a scoped package to a
//! scope stack chooses its place, above the features' packages, so minting
//! cannot place it under the ordinary declarations.
//!
//! Scoped packages are not checked for clashes, neither against one another
//! nor against the features' own packages, because a scoped package is on no
//! scope stack until something adds it: a body or an argument that refers to
//! it, or a program that adds it to a parsing state. Two
//! scoped packages that declare one name (two features each giving `\\` a
//! meaning inside its own environment, in text mode) are therefore available
//! in separate places, unless one is used inside the other; the inner one then
//! shadows the outer one while its body or argument is parsed, as any techy
//! package added later does. Only two scoped packages with the same package
//! name clash ([`ClashKind::ScopedPackage`]), since a body refers to a
//! package by its name.
//!
//! # The fallback package and the fields package
//!
//! Two techy packages are never on the scope stack.
//!
//! **The fallback package**, named [`FALLBACK_PACKAGE_NAME`], holds the
//! fallback specifications under keys built from the owner, the callable kind
//! and the position of each fallback. It exists so that those specifications
//! carry provenance stamps like every other and can be serialized and read
//! back. The scope stack holds the fallback provider instead, which returns a
//! specification from this package in the declared modes only. The fallback
//! provider resolves *any* name and so cannot list its entries; a [reading
//! session](crate::dump::session) is given the package beside it, and
//! [`BuiltLang::providers`](crate::lang::BuiltLang::providers) lists it.
//!
//! After every fallback a feature declares, the fallback provider consults
//! the language's own two, each applying in every mode: a macro that no declaration
//! defines resolves to a specification carrying `flm.unknown.macro` and is
//! reported, and an environment likewise to one carrying `flm.unknown.environment`.
//! A feature's fallback for a mode shadows the language's in that mode. This is how
//! mathematics accepts any command without a report when a mathematics feature is
//! registered, while text mode still reports unknown commands.
//!
//! **The fields package**, named [`FIELDS_PACKAGE_NAME`], holds the
//! specifications of [tack-on fields](super::TackOnField). Each carries the
//! language's field element
//! ([`StructuralElements::field`](crate::lang::structural::StructuralElements::field)).
//! A field's node records such a specification, but no name lookup ever reaches it: the
//! parser that absorbs the fields holds it directly. The package exists so
//! that these specifications too carry provenance stamps and can be
//! serialized. Their keys are built from the declaration alone, so adding an
//! unrelated declaration elsewhere does not change the key a serialized tree
//! refers to.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::Arc;

use techy::core::constructs::{ArgumentParser, TackOnFieldsArgumentParser};
use techy::core::specs::{
    ArgumentSpec, CallableQuery, CallableSpec, Package, ProviderError, SpecsProvider,
};
use techy::core::{ClosedVocabulary, ParsingState, ParsingStateDelta};
use techy::latexlike::{MacroSpec, Mode, SpecialsSpec};

use crate::model::element::ElementSpec;
use crate::model::names::{ElementName, FeatureName, Name};
use crate::lang::flm::{Flm, FlmCallableType, FlmEvent};
use crate::lang::mint::decl::{
    ArgDef, ArgLayout, BodyDef, BodyLayout, CallableKind, ElementDef, FallbackDef,
    FallbackKind, OverrideDef, ScopedPackageDef, SyntaxDef, TackOnField,
};
use crate::lang::mint::opaque::OpaqueWrapperReader;
use crate::lang::mint::specs::{
    FlmCallable, FlmEnvironment, FlmUnknownEnvironmentBehavior, FlmUnknownMacroSpec,
};
use crate::lang::input::InputSpec;
use crate::lang::structural::StructuralElements;

/// One registered command name: its callable kind and the name itself (the
/// trigger, for a special character sequence).
///
/// Its `Display` text, such as ``macro `vec` ``, appears in error messages.
///
/// It is written to data with `Serialize`; see [serialized
/// forms](crate::core::registry#serialized-forms).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(serde::Serialize, schemars::JsonSchema)]
pub struct Symbol {
    /// The callable kind of the name.
    pub kind: CallableKind,
    /// The name without its escape character, or the trigger.
    pub name: String,
}

impl fmt::Display for Symbol {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} `{}`", self.kind, self.name)
    }
}

/// What was declared more than once, in a [`MintError::Clash`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClashKind {
    /// Two or more features define one command name in parsing modes that
    /// overlap.
    Symbol,
    /// Two fallbacks for one callable kind, declared by one feature or by
    /// two, apply in parsing modes that overlap.
    Fallback,
    /// A scoped package name is declared twice, by one feature or by two.
    ScopedPackage,
}

/// A problem with the declarations that minting found.
///
/// [`mint_packages`] collects every problem in
/// [`MintedProviders::errors`] and still builds everything that is sound;
/// each variant says what was found and, where a choice had to be made, which
/// declaration applies. The language build reports each one as a
/// [`LangBuildError::Mint`](crate::lang::LangBuildError::Mint), and the
/// registry build refuses a language with any such error: it fails in its
/// language phase
/// ([`BuildPhase::Language`](crate::core::registry::BuildPhase::Language)).
/// The `userdefs` feature, which mints a language for the templates of [user
/// definitions](crate::lang::rewrites::userdefs::Definition), reports these
/// errors as diagnostics of those user definitions.
///
/// The `Display` text states the problem for the author of the feature or of
/// the user definition; it identifies, where the problem concerns them, the
/// declaring feature and the element by name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MintError {
    /// Two or more features declare the same thing where it matters. For a
    /// command name: two or more features define it in one parsing mode
    /// (ordinarily, or weakly where no feature defines it ordinarily in that
    /// mode), and the feature registered last among them in that mode is
    /// neither placed by the feature order explicitly after every other of
    /// them nor declares an override. There is one error per name and parsing
    /// mode.
    Clash {
        /// What was declared twice.
        kind: ClashKind,
        /// The name concerned: the command name; for a fallback, the name of
        /// the callable kind; for a scoped package, the package's name.
        symbol: Symbol,
        /// The parsing modes in which the declarations overlap, in the modes'
        /// fixed order: for a command name, the one mode concerned. Empty for a
        /// scoped package, which is not tied to parsing modes.
        modes: Vec<Mode>,
        /// Every feature whose declaration is available in one of `modes`, in
        /// registration order: for a command name, the features that declare
        /// it ordinarily in that mode, or those that declare it weakly when
        /// none declares it ordinarily.
        owners: Vec<FeatureName>,
        /// The feature whose declaration applies despite the clash: for a
        /// command name the last of `owners`, since a later feature's package
        /// shadows an earlier one's; for a fallback or a scoped package the
        /// first, since a later overlapping one is not installed.
        winner: FeatureName,
        /// For a command name, the chains of the feature order that settle
        /// the clash, each making the definition of its last feature apply.
        /// Each lists the other features of `owners` in registration order,
        /// then that feature. A chain is listed only when the explicit order
        /// in force places none of its features before an earlier one of the
        /// chain, so that adding it makes no cycle. Empty for a fallback or a
        /// scoped package, which no chain settles.
        chains: Box<[Vec<FeatureName>]>,
    },
    /// An environment body or an argument refers to a scoped package that no
    /// feature declares and that the feature declaring the element did not
    /// declare as a peer. (A package declared as a peer that no feature
    /// declares makes nothing available and is reported by the registry build
    /// as a Note, not here.)
    UnknownScopedPackage {
        /// The element whose declaration refers to the package.
        element: ElementName,
        /// The feature declaring the element.
        owner: FeatureName,
        /// `None` when the environment's body refers to the package; the
        /// argument's position, counting from zero, when an argument does, in
        /// the argument list that declares it: the element's own, or that of
        /// the tack-on field given by `field`.
        argument: Option<usize>,
        /// The name of the [tack-on field](TackOnField) whose own argument
        /// list holds the argument; `None` when the argument is the element's
        /// own.
        field: Option<String>,
        /// The package name that was not found.
        package: Name,
    },
    /// Scoped packages refer to each other in a cycle, each through one of its
    /// declarations (an environment's body or an argument), so there is no
    /// order in which each is built after the ones it refers to. Minting
    /// breaks the cycle at the reference that closes it.
    ScopedPackageCycle {
        /// The packages of the cycle, each referring to the next, the last to
        /// the first.
        packages: Vec<Name>,
    },
    /// A special character sequence declaration lists command names. It may
    /// list none: its trigger is how it is written.
    SpecialsWithNames {
        /// The declaring feature.
        owner: FeatureName,
        /// The trigger of the declaration.
        trigger: String,
    },
    /// A declaration with no syntax ([`SyntaxDef::Synthesized`]) lists command
    /// names. It may list none, since nothing in the source writes it.
    SynthesizedWithNames {
        /// The declaring feature.
        owner: FeatureName,
        /// The element concerned.
        element: ElementName,
    },
    /// A file-inclusion macro ([`SyntaxDef::Inclusion`]) declares no argument
    /// named [`REFERENCE_ARGUMENT`](crate::lang::input::REFERENCE_ARGUMENT), so
    /// it has no argument to read the file's reference from.
    NoReferenceArgument {
        /// The declaring feature.
        owner: FeatureName,
        /// The element concerned.
        element: ElementName,
        /// A description of the declared arguments, such as "it declares no
        /// argument".
        detail: String,
    },
    /// One feature declares one command name twice in parsing modes that
    /// overlap, so in the overlapping modes only one of the two declarations
    /// could apply, whatever the weakness of the two
    /// ([`ElementDef::weak`]). Two declarations of one name whose modes do
    /// *not* overlap are sound and are built into two of the feature's techy
    /// packages.
    Redeclared {
        /// The name concerned.
        symbol: Symbol,
        /// The feature declaring it twice.
        owner: FeatureName,
        /// The parsing modes both declarations are available in, in the modes'
        /// fixed order.
        modes: Vec<Mode>,
    },
    /// A macro or environment declaration lists no name, so nothing can be
    /// registered for it.
    NoNames {
        /// The declaring feature.
        owner: FeatureName,
        /// The element concerned.
        element: ElementName,
    },
    /// An argument declared with an opaque wrapper
    /// ([`ArgDef::opaque_wrapper`]) declares a [layout](ArgLayout) other than
    /// [`ArgLayout::Inline`]. The [block-structure
    /// pass](crate::lang::rewrites::blocks) carries the content of an opaque
    /// wrapper over as written, so the declaration could never take effect.
    /// The argument is built with the inline layout.
    LayoutOnOpaqueWrappedArgument {
        /// The declaring feature.
        owner: FeatureName,
        /// The element whose declaration holds the argument.
        callable: ElementName,
        /// The argument's position, counting from zero, in the argument list
        /// that declares it: the element's own, or that of the tack-on field
        /// given by `field`.
        index: usize,
        /// The name of the [tack-on field](TackOnField) whose own argument
        /// list holds the argument; `None` when the argument is the element's
        /// own.
        field: Option<String>,
    },
    /// An argument read in mathematics mode ([`ArgDef::mode`]) declares the
    /// layout [`ArgLayout::Blocks`]. The [block-structure
    /// pass](crate::lang::rewrites::blocks) carries mathematics over
    /// untouched, so the declaration could never take effect. The argument is
    /// built with the inline layout.
    BlocksOnMathArgument {
        /// The declaring feature.
        owner: FeatureName,
        /// The element whose declaration holds the argument.
        callable: ElementName,
        /// The argument's position, counting from zero, in the argument list
        /// that declares it: the element's own, or that of the tack-on field
        /// given by `field`.
        index: usize,
        /// The name of the [tack-on field](TackOnField) whose own argument
        /// list holds the argument; `None` when the argument is the element's
        /// own.
        field: Option<String>,
    },
    /// A tack-on argument declares two fields ([`TackOnField`]) of one name,
    /// so a macro of that name written after the command could be read as
    /// either. The second field is left out of the argument.
    FieldDeclaredTwice {
        /// The declaring feature.
        owner: FeatureName,
        /// The element whose declaration holds the tack-on argument.
        callable: ElementName,
        /// The tack-on argument's position, counting from zero, in the
        /// argument list that declares it: the element's own, or that of the
        /// tack-on field given by `field`.
        index: usize,
        /// The name of the [tack-on field](TackOnField) whose own argument
        /// list holds the tack-on argument; `None` when the argument is the
        /// element's own.
        field: Option<String>,
        /// The name the two fields share.
        name: String,
    },
    /// A declaration in a [scoped package](ScopedPackageDef) is marked weak
    /// ([`ElementDef::weak`]). A scoped package is placed on a scope stack by
    /// whoever adds it (a body, an argument or a program), above the features'
    /// packages, so no place under the ordinary declarations exists for it.
    /// The declaration is built as an ordinary one.
    WeakInScopedPackage {
        /// The feature declaring the scoped package.
        owner: FeatureName,
        /// The scoped package.
        package: Name,
        /// The element of the weak declaration.
        element: ElementName,
    },
    /// An environment's body declared with an opaque wrapper
    /// ([`BodyDef::opaque_wrapper`]) declares a [layout](BodyDef::layout)
    /// other than [`FromRole`](super::BodyLayout::FromRole). The
    /// [block-structure pass](crate::lang::rewrites::blocks) carries the
    /// content of an opaque wrapper over as written, so the declaration could
    /// never take effect.
    LayoutOnOpaqueWrappedBody {
        /// The declaring feature.
        owner: FeatureName,
        /// The environment's element.
        element: ElementName,
    },
}

/// Returns the words that identify the tack-on field an argument belongs to,
/// for a message: empty for an element's own argument.
fn of_field(field: &Option<String>) -> String {
    field.as_ref().map(|name| format!(" of the field `{name}`")).unwrap_or_default()
}

/// Returns feature names written as `` feature `a` `` or
/// `` features `a`, `b` and `c` ``, for a message.
fn owner_list(owners: &[FeatureName]) -> String {
    match owners {
        [] => String::from("no feature"),
        [one] => format!("feature `{one}`"),
        [head @ .., last] => {
            let head: Vec<String> = head.iter().map(|owner| format!("`{owner}`")).collect();
            format!("features {} and `{last}`", head.join(", "))
        }
    }
}

/// Returns parsing modes written as `mode Text` or `modes Text and Math`, for
/// a message (an empty list, which no declaration carries, reads `no mode`).
fn mode_list(modes: &[Mode]) -> String {
    match modes {
        [] => String::from("no mode"),
        [one] => format!("mode {one:?}"),
        [head @ .., last] => {
            let head: Vec<String> = head.iter().map(|mode| format!("{mode:?}")).collect();
            format!("modes {} and {last:?}", head.join(", "))
        }
    }
}

/// Returns items written as `a`, `a and b` or `a, b, and c` (with `or` for
/// `and` when `conjunction` says so), for a message.
fn series(items: &[String], conjunction: &str) -> String {
    match items {
        [] => String::new(),
        [one] => one.clone(),
        [first, second] => format!("{first} {conjunction} {second}"),
        [head @ .., last] => format!("{}, {conjunction} {last}", head.join(", ")),
    }
}

/// Returns parsing modes written as `in math mode` or `in text and math
/// modes`, for a message.
fn in_modes(modes: &[Mode]) -> String {
    let words: Vec<String> = modes.iter().map(|mode| format!("{mode:?}").to_lowercase()).collect();
    match words.as_slice() {
        [] => String::from("in no mode"),
        [one] => format!("in {one} mode"),
        [head @ .., last] => format!("in {} and {last} modes", head.join(", ")),
    }
}

impl fmt::Display for MintError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MintError::Clash { kind: ClashKind::Symbol, symbol, modes, owners, chains, .. } => {
                let construct = match symbol.kind {
                    CallableKind::Macro => format!("‘\\{}’", symbol.name),
                    CallableKind::Environment => format!("environment ‘{}’", symbol.name),
                    CallableKind::Specials => format!("‘{}’", symbol.name),
                };
                let features: Vec<String> =
                    owners.iter().map(|owner| format!("‘{owner}’")).collect();
                let choices: Vec<String> = chains
                    .iter()
                    .filter_map(|chain| {
                        let chosen = chain.last()?;
                        let chain: Vec<&str> = chain.iter().map(|owner| owner.as_str()).collect();
                        Some(format!(
                            "‘flm: feature_order: ['{}']’ for the definition of ‘{chosen}’",
                            chain.join(" < ")
                        ))
                    })
                    .collect();
                write!(
                    f,
                    "Duplicate definition of {construct} {} (features {})",
                    in_modes(modes),
                    series(&features, "and")
                )?;
                if choices.is_empty() {
                    return Ok(());
                }
                write!(f, "; in the front matter, set {}", series(&choices, "or"))
            }
            MintError::Clash { kind: ClashKind::Fallback, symbol, modes, owners, .. } => {
                write!(
                    f,
                    "the fallbacks for unknown {}s declared by {} overlap in {}; only one \
                     fallback for unknown {}s may apply in a parsing mode",
                    symbol.name,
                    owner_list(owners),
                    mode_list(modes),
                    symbol.name
                )
            }
            MintError::Clash { kind: ClashKind::ScopedPackage, symbol, owners, .. } => write!(
                f,
                "the scoped package name `{}` is declared more than once (by {}); a \
                 scoped package name may be declared only once",
                symbol.name,
                owner_list(owners)
            ),
            MintError::Redeclared { symbol, owner, modes } => write!(
                f,
                "feature `{owner}` declares {symbol} twice in {}; a feature may declare a \
                 name only once per parsing mode",
                mode_list(modes)
            ),
            MintError::UnknownScopedPackage { element, owner, argument: None, package, .. } => write!(
                f,
                "the body of `{element}` (an element of the feature `{owner}`) refers to \
                 the scoped package `{package}`, which no registered feature declares; a \
                 feature that refers to another feature's scoped package must declare it \
                 with `FeatureBuilder::peer_scoped_package`"
            ),
            MintError::UnknownScopedPackage {
                element,
                owner,
                argument: Some(index),
                field,
                package,
            } => {
                write!(
                    f,
                    "argument {}{} of `{element}` (an element of the feature `{owner}`) \
                     refers to the scoped package `{package}`, which no registered feature \
                     declares; a feature that refers to another feature's scoped package \
                     must declare it with `FeatureBuilder::peer_scoped_package`",
                    index + 1,
                    of_field(field)
                )
            }
            MintError::ScopedPackageCycle { packages } => {
                let names: Vec<String> = packages.iter().map(|name| format!("`{name}`")).collect();
                write!(
                    f,
                    "scoped packages must not refer to each other in a cycle; the cycle is \
                     {}, the last referring back to the first",
                    names.join(" → ")
                )
            }
            MintError::SpecialsWithNames { owner, trigger } => write!(
                f,
                "feature `{owner}`: the special character sequence `{trigger}` must not \
                 declare command names; it is written as `{trigger}`"
            ),
            MintError::SynthesizedWithNames { owner, element } => write!(
                f,
                "feature `{owner}`: the element `{element}`, declared as never written in a \
                 document (`SyntaxDef::Synthesized`), must not declare command names"
            ),
            MintError::NoReferenceArgument { owner, element, detail } => write!(
                f,
                "feature `{owner}`: the file-inclusion macro of the element `{element}` must \
                 declare an argument named `reference` ({detail})"
            ),
            MintError::NoNames { owner, element } => {
                write!(
                    f,
                    "feature `{owner}`: the macro or environment declaration of the element \
                     `{element}` must list at least one name"
                )
            }
            MintError::LayoutOnOpaqueWrappedArgument { owner, callable, index, field } => write!(
                f,
                "feature `{owner}`: argument {}{} of `{callable}` must be laid out inline, \
                 because it is declared with an opaque wrapper",
                index + 1,
                of_field(field)
            ),
            MintError::BlocksOnMathArgument { owner, callable, index, field } => write!(
                f,
                "feature `{owner}`: argument {}{} of `{callable}` must not be laid out as \
                 blocks, because it is read in mathematics mode",
                index + 1,
                of_field(field)
            ),
            MintError::FieldDeclaredTwice { owner, callable, index, field, name } => write!(
                f,
                "feature `{owner}`: the fields of argument {}{} of `{callable}` must have \
                 distinct names, and `{name}` is declared twice",
                index + 1,
                of_field(field)
            ),
            MintError::WeakInScopedPackage { owner, package, element } => write!(
                f,
                "Misconfigured feature ‘{owner}’: the declaration of ‘{element}’ in scoped \
                 package ‘{package}’ may not be weak"
            ),
            MintError::LayoutOnOpaqueWrappedBody { owner, element } => write!(
                f,
                "feature `{owner}`: the body of `{element}` must not declare a layout, because \
                 it is declared with an opaque wrapper"
            ),
        }
    }
}

impl std::error::Error for MintError {}

// --- the fallback provider --------------------------------------------------------------

/// The name of the fallback provider ([`FlmFallbackProvider`]) as a
/// specification provider on the scope stack, `_fallback.gate`.
pub const FALLBACK_PROVIDER_NAME: &str = "_fallback.gate";

/// The name of the techy package holding the fallback specifications
/// ([`FlmFallbackProvider::package`]), `_fallback`.
pub const FALLBACK_PACKAGE_NAME: &str = "_fallback";

/// The name of the techy package holding the specifications of tack-on fields
/// ([`MintedProviders::fields`]), `_fields`; see the [module
/// documentation](self).
pub const FIELDS_PACKAGE_NAME: &str = "_fields";

/// The feature name recorded as the owner of the language's own declarations,
/// `flm`: the fallbacks for an unknown macro and an unknown environment. No
/// registered feature has this name; [`FlmFallbackProvider::entries`] lists
/// these two fallbacks under it.
pub const LANGUAGE_OWNER: &str = "flm";

/// One fallback the fallback provider holds: the feature that declared it, the modes it
/// applies in, the callable kind it applies to, and its key in the fallback
/// package.
struct FallbackEntry {
    owner: FeatureName,
    modes: Vec<Mode>,
    kind: FallbackKind,
    key: String,
}

/// A fallback while it is being collected, before the package is built.
struct PendingFallback {
    owner: FeatureName,
    modes: Vec<Mode>,
    kind: FallbackKind,
    element: Arc<ElementSpec>,
    /// Whether this is one of the language's own fallbacks, which report the
    /// unknown callable, rather than a feature's, which passes it silently.
    recovery: bool,
}

/// The fallback provider: the specification provider that resolves a macro or
/// an environment that no declaration defines, according to the fallbacks
/// ([`FallbackDef`]) declared for the current parsing mode.
///
/// techy's own fallback provider cannot be restricted to parsing modes, so
/// minting builds this provider instead. The language build puts it at the
/// bottom of the scope stack, so every defined name shadows it. It returns
/// specifications from the techy package it holds
/// ([`FlmFallbackProvider::package`]).
///
/// The fallbacks are consulted in declaration order, with the language's own
/// two last, so a feature's fallback for a mode applies in that mode. In a
/// mode no feature's fallback covers, the language's own fallbacks apply: the
/// command is reported and its node carries `flm.unknown.macro` or
/// `flm.unknown.environment`. Text mode therefore reports unknown commands,
/// while mathematics mode, with a mathematics feature registered, does not.
///
/// It resolves *any* name, so it cannot list its entries; the package
/// beside it is therefore listed separately in [`BuiltLang::providers`].
///
/// [`BuiltLang::providers`]: crate::lang::BuiltLang::providers
pub struct FlmFallbackProvider {
    name: Box<str>,
    package: Arc<Package<Flm>>,
    entries: Vec<FallbackEntry>,
}

impl FlmFallbackProvider {
    /// Builds the fallback package and the fallback provider from the
    /// collected fallbacks, keeping their order.
    fn build(pending: &[PendingFallback]) -> FlmFallbackProvider {
        let mut entries = Vec::with_capacity(pending.len());
        let package = Package::new_shared(FALLBACK_PACKAGE_NAME, |pkg| {
            for (index, fallback) in pending.iter().enumerate() {
                let key = format!("{}.{}.{index}", fallback.owner, fallback.kind);
                let callable_type = fallback.kind.callable_type();
                let stamp = pkg.provenance_for(callable_type, key.as_str());
                match fallback.kind {
                    FallbackKind::Macro => {
                        let mut callable = if fallback.recovery {
                            FlmCallable::new(
                                FlmUnknownMacroSpec::new(),
                                Arc::clone(&fallback.element),
                            )
                        } else {
                            FlmCallable::new(
                                MacroSpec::<Flm>::new(Vec::new()),
                                Arc::clone(&fallback.element),
                            )
                        };
                        if let Some(stamp) = stamp {
                            callable = callable.with_provenance(stamp);
                        }
                        pkg.insert(callable_type, key.as_str(), callable);
                    }
                    FallbackKind::Environment => {
                        // The language layer's own environment body is block
                        // content; a feature's silent passthrough follows the
                        // element's role (the default declaration).
                        let body = if fallback.recovery {
                            BodyDef::new().blocks().parser(FlmUnknownEnvironmentBehavior::new())
                        } else {
                            BodyDef::default()
                        };
                        let environment =
                            FlmEnvironment::new(Vec::new(), Arc::clone(&fallback.element), body);
                        let mut spec = environment.into_spec();
                        if let Some(stamp) = stamp {
                            spec = spec.with_provenance(stamp);
                        }
                        pkg.insert(callable_type, key.as_str(), spec);
                    }
                }
                entries.push(FallbackEntry {
                    owner: fallback.owner.clone(),
                    modes: fallback.modes.clone(),
                    kind: fallback.kind,
                    key,
                });
            }
        });
        FlmFallbackProvider { name: FALLBACK_PROVIDER_NAME.into(), package, entries }
    }

    /// Returns the techy package holding the fallback specifications, which
    /// their provenance stamps refer to. It is never on the scope stack.
    pub fn package(&self) -> &Arc<Package<Flm>> {
        &self.package
    }

    /// Returns the installed fallbacks as `(owner, modes, kind)`, in the order
    /// they are consulted: declaration order, with the language's own two last
    /// (owned by [`LANGUAGE_OWNER`]). A fallback reported as a
    /// [`MintError::Clash`] is not among them.
    pub fn entries(&self) -> impl Iterator<Item = (&FeatureName, &[Mode], FallbackKind)> + '_ {
        self.entries.iter().map(|entry| (&entry.owner, entry.modes.as_slice(), entry.kind))
    }

    /// Returns whether some fallback applies to `kind` in `mode`. It always
    /// returns `true`, since the language's own two fallbacks apply to both
    /// kinds in every mode.
    pub fn answers(&self, kind: FallbackKind, mode: Mode) -> bool {
        self.entries.iter().any(|entry| entry.kind == kind && entry.modes.contains(&mode))
    }

    /// Returns the specification for `kind` in `mode`: that of the first
    /// installed fallback that covers them.
    pub fn spec_for(
        &self,
        kind: FallbackKind,
        mode: Mode,
    ) -> Option<&Arc<dyn CallableSpec<Flm>>> {
        let entry = self
            .entries
            .iter()
            .find(|entry| entry.kind == kind && entry.modes.contains(&mode))?;
        self.package.get(kind.callable_type(), &entry.key)
    }
}

impl fmt::Debug for FlmFallbackProvider {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FlmFallbackProvider")
            .field("name", &self.name)
            .field("entries", &self.entries.len())
            .finish()
    }
}

impl SpecsProvider<Flm> for FlmFallbackProvider {
    fn name(&self) -> &str {
        &self.name
    }

    fn retrieve_spec(
        &self,
        query: &CallableQuery<'_, Flm>,
        state: &ParsingState<Flm>,
    ) -> Result<Option<Arc<dyn CallableSpec<Flm>>>, ProviderError> {
        let kind = match query.callable_type {
            FlmCallableType::Macro => FallbackKind::Macro,
            FlmCallableType::Environment => FallbackKind::Environment,
            _ => return Ok(None),
        };
        Ok(self.spec_for(kind, state.mode()).cloned())
    }
}

// --- argument minting ----------------------------------------------------------------

/// One declared argument list, built: the argument specifications, and the
/// layout of each argument in the same order, which the command's
/// specification records beside its element.
struct MintedArgs {
    specs: Vec<Arc<ArgumentSpec<Flm>>>,
    layouts: Vec<ArgLayout>,
}

/// The scoped packages a declaration may refer to: those already built, by
/// name; the names some feature declares, which tell a package caught in a
/// cycle (declared, and reported separately) from one that no feature
/// declares; and the names each feature declares as a peer, as (feature,
/// name), which that feature's declarations may refer to although no feature
/// declares them.
struct Scopes<'a> {
    minted: &'a BTreeMap<Name, Arc<Package<Flm>>>,
    declared: &'a BTreeSet<Name>,
    peers: &'a BTreeSet<(FeatureName, Name)>,
}

/// The fields package, which receives the specification of every tack-on
/// field, with the element each of those specifications carries: the
/// language's field element ([`StructuralElements::field`]).
struct FieldsHome<'a> {
    package: &'a mut Package<Flm>,
    element: &'a Arc<ElementSpec>,
}

/// Builds one declared argument list: the element's own when `field` is
/// `None`, else that of the tack-on field of this name, which an error
/// identifies. `home` is the fields package that receives the specifications
/// of any tack-on fields ([`FieldsHome`]), `def` the declaration they belong to, from which
/// their keys are built and which an error identifies, and `scopes` the
/// scoped packages an argument may refer to.
fn argument_specs_of(
    args: &[ArgDef],
    field: Option<&str>,
    home: &mut FieldsHome<'_>,
    def: &ElementDef,
    scopes: &Scopes<'_>,
    errors: &mut Vec<MintError>,
) -> MintedArgs {
    let mut minted = MintedArgs { specs: Vec::new(), layouts: Vec::new() };
    for (index, arg) in args.iter().enumerate() {
        minted.specs.push(argument_spec_of(arg, index, field, home, def, scopes, errors));
        minted.layouts.push(declared_layout(arg, index, field, def, errors));
    }
    minted
}

/// Returns the layout `arg` is built with: its declared one, or inline when the
/// argument can never take the declared one, which is reported
/// ([`MintError::LayoutOnOpaqueWrappedArgument`],
/// [`MintError::BlocksOnMathArgument`]).
fn declared_layout(
    arg: &ArgDef,
    index: usize,
    field: Option<&str>,
    def: &ElementDef,
    errors: &mut Vec<MintError>,
) -> ArgLayout {
    let owner = def.owner.clone();
    let callable = def.element.name.clone();
    let field = field.map(str::to_string);
    let error = if arg.opaque_wrapper && arg.layout != ArgLayout::Inline {
        MintError::LayoutOnOpaqueWrappedArgument { owner, callable, index, field }
    } else if arg.layout == ArgLayout::Blocks && arg.mode == Some(Mode::Math) {
        MintError::BlocksOnMathArgument { owner, callable, index, field }
    } else {
        return arg.layout;
    };
    errors.push(error);
    ArgLayout::Inline
}

/// Returns the key a tack-on field's specification is held under in the
/// fields package, which is also how a serialized tree refers to it.
///
/// It is built from the declaration alone, as `owner.element.field`. If that
/// key is taken (one declaration with two tack-on arguments accepting the same
/// field name), the argument's position in the declaration is appended; if
/// that is taken too, a running number is appended. The key therefore stays
/// the same when unrelated declarations change, and since `.` is not a
/// character of command names, no name written in the source can reach these
/// keys.
fn field_key(
    home: &Package<Flm>,
    def: &ElementDef,
    field: &TackOnField,
    arg_index: usize,
) -> String {
    let free = |key: &str| home.get(FlmCallableType::Macro, key).is_none();
    let base = format!("{}.{}.{}", def.owner, def.element.name, field.name);
    if free(&base) {
        return base;
    }
    let indexed = format!("{base}.{arg_index}");
    if free(&indexed) {
        return indexed;
    }
    (1..)
        .map(|number| format!("{indexed}.{number}"))
        .find(|key| free(key))
        .expect("the running numbers are unbounded, so a free key exists")
}

/// Builds the specification of one tack-on field and inserts it into the
/// fields package under its [`field_key`], with that package's provenance
/// stamp. The specification carries the language's field element, and its
/// node is named as the field is written, which is how the construct that
/// declared the field reads it ([`field_name`](super::field_name)). It returns
/// the value the package holds, so a field node records the same
/// specification that a serialized tree finds again by its key.
fn field_spec(
    field: &TackOnField,
    home: &mut FieldsHome<'_>,
    def: &ElementDef,
    arg_index: usize,
    scopes: &Scopes<'_>,
    errors: &mut Vec<MintError>,
) -> Arc<dyn CallableSpec<Flm>> {
    let args = argument_specs_of(&field.args, Some(&field.name), home, def, scopes, errors);
    let syntax = MacroSpec::<Flm>::new(args.specs);
    let key = field_key(home.package, def, field, arg_index);
    let mut callable =
        FlmCallable::new(syntax, Arc::clone(home.element)).with_arg_layouts(args.layouts);
    if let Some(stamp) = home.package.provenance_for(FlmCallableType::Macro, key.as_str()) {
        callable = callable.with_provenance(stamp);
    }
    home.package.insert(FlmCallableType::Macro, key.as_str(), callable);
    let spec = home
        .package
        .get(FlmCallableType::Macro, &key)
        .expect("the field's specification was just inserted");
    Arc::clone(spec)
}

/// Builds one declared argument, the `arg_index`-th of its declaration, as a
/// techy argument specification: its parser, and the change of parsing state
/// its declared mode, scoped packages and state events ask for. `field`,
/// `home`, `def` and
/// `scopes` are as for [`argument_specs_of`].
///
/// The parser is the declaration's own object ([`ArgDef::kind`]), except for
/// a tack-on argument: its fields are declarations whose specifications are
/// built here into `home`, so the reader that absorbs them is built here from
/// those specifications ([`tack_on_reader`]). When the declaration asks for an
/// opaque wrapper ([`ArgDef::opaque_wrapper`]), the chosen parser is wrapped
/// so that what it reads is placed under one ([`OpaqueWrapperReader`]). The
/// declared mode, scoped packages and state events apply around the parser,
/// whatever it is,
/// as the state change of the argument's specification, so a parser of a
/// feature's own receives them exactly as a standard kind does.
fn argument_spec_of(
    arg: &ArgDef,
    arg_index: usize,
    field: Option<&str>,
    home: &mut FieldsHome<'_>,
    def: &ElementDef,
    scopes: &Scopes<'_>,
    errors: &mut Vec<MintError>,
) -> Arc<ArgumentSpec<Flm>> {
    let parser: Arc<dyn ArgumentParser<Flm>> = match arg.kind.tack_on_fields() {
        Some(fields) => Arc::new(tack_on_reader(fields, field, home, def, arg_index, scopes, errors)),
        None => arg.kind.clone(),
    };
    let parser: Arc<dyn ArgumentParser<Flm>> = if arg.opaque_wrapper {
        Arc::new(OpaqueWrapperReader::new(parser))
    } else {
        parser
    };
    let spec = match arg.name.as_deref() {
        Some(name) => ArgumentSpec::new(parser, name),
        None => ArgumentSpec::new_unnamed(parser),
    };
    let unknown = |package: &Name| MintError::UnknownScopedPackage {
        element: def.element.name.clone(),
        owner: def.owner.clone(),
        argument: Some(arg_index),
        field: field.map(str::to_string),
        package: package.clone(),
    };
    let spec = match region_delta(arg.mode, &arg.scoped, &arg.events, &def.owner, scopes, unknown, errors) {
        Some(delta) => spec.with_state_delta(delta),
        None => spec,
    };
    Arc::new(spec)
}

/// Builds the reader of a tack-on argument, the `arg_index`-th of `def` (in
/// the argument list of the tack-on field named `within`, when it is not
/// `None`): techy's tack-on reader, configured with the specification of each
/// of `fields`, which [`field_spec`] builds into `home`. A field whose name an
/// earlier field has is reported ([`MintError::FieldDeclaredTwice`]) and left
/// out.
// The minting builds this reader, not the argument's parser object: the fields'
// specifications are minted into the registry's fields package, and a parser object,
// built before any registry exists and shared across registries, cannot hold them.
fn tack_on_reader(
    fields: &[TackOnField],
    within: Option<&str>,
    home: &mut FieldsHome<'_>,
    def: &ElementDef,
    arg_index: usize,
    scopes: &Scopes<'_>,
    errors: &mut Vec<MintError>,
) -> TackOnFieldsArgumentParser<Flm> {
    let mut parser = TackOnFieldsArgumentParser::<Flm>::new(FlmCallableType::Macro);
    for (position, field) in fields.iter().enumerate() {
        if fields[..position].iter().any(|earlier| earlier.name == field.name) {
            errors.push(MintError::FieldDeclaredTwice {
                owner: def.owner.clone(),
                callable: def.element.name.clone(),
                index: arg_index,
                field: within.map(str::to_string),
                name: field.name.clone(),
            });
            continue;
        }
        let spec = field_spec(field, home, def, arg_index, scopes, errors);
        parser = if field.repeatable {
            parser.with_repeatable_field(field.name.as_str(), spec)
        } else {
            parser.with_field(field.name.as_str(), spec)
        };
    }
    parser
}

// --- package minting ----------------------------------------------------------------

/// The result of [`mint_packages`]: the techy packages and the fallback provider
/// that the language build installs, the table of registered command names,
/// and the problems found.
pub struct MintedProviders {
    /// The features' techy packages, in the order of the scope stack,
    /// outermost first: every package of weak declarations
    /// ([`ElementDef::weak`]), then every package of ordinary declarations,
    /// each part in registration order, so a later feature's package shadows
    /// an earlier one's and an ordinary declaration shadows every weak one. A
    /// feature has one package per weakness and distinct set of parsing modes
    /// its declarations list (see the [module documentation](self)), in the
    /// order these first appear.
    pub packages: Vec<Arc<Package<Flm>>>,
    /// The scoped packages, keyed by the name by which an environment body or
    /// an argument refers to them.
    pub scoped: BTreeMap<Name, Arc<Package<Flm>>>,
    /// The fallback provider, which resolves a command that no declaration
    /// defines. It always holds at least the language's own two fallbacks.
    pub fallback: Arc<FlmFallbackProvider>,
    /// The techy package holding the specifications of tack-on fields
    /// ([`FIELDS_PACKAGE_NAME`]). It is never on the scope stack; the language
    /// build lists it so that a [reading session](crate::dump::session) can
    /// find those specifications when it reads a serialized tree.
    pub fields: Arc<Package<Flm>>,
    /// Every command name the features' techy packages register, with the
    /// feature whose definition applies: the one registered last among those
    /// that declare the name ordinarily, or, when every declaration of the
    /// name is weak ([`ElementDef::weak`]), the one registered last.
    pub symbols: BTreeMap<Symbol, FeatureName>,
    /// The problems found; empty when every declaration was sound.
    pub errors: Vec<MintError>,
}

impl fmt::Debug for MintedProviders {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MintedProviders")
            .field("packages", &self.packages.len())
            .field("scoped", &self.scoped.keys().collect::<Vec<_>>())
            .field("fallback", &self.fallback)
            .field("symbols", &self.symbols.len())
            .field("errors", &self.errors)
            .finish()
    }
}

/// One feature's definitions of one name: the parsing modes in which it
/// declares the name ordinarily, and those in which it declares it weakly.
struct Definer {
    owner: FeatureName,
    ordinary: Vec<Mode>,
    weak: Vec<Mode>,
}

impl Definer {
    /// Returns whether the feature declares the name in `mode`, ordinarily
    /// when `weak` is false and weakly otherwise.
    fn defines(&self, mode: Mode, weak: bool) -> bool {
        if weak { self.weak.contains(&mode) } else { self.ordinary.contains(&mode) }
    }
}

/// Returns whether `def` is weak: marked weak ([`ElementDef::weak`]) and
/// written in documents. A declaration with no syntax ignores the mark.
pub(crate) fn is_weak(def: &ElementDef) -> bool {
    def.weak && def.syntax.kind().is_some()
}

/// The features that own the element declarations `elements`, in the order
/// [`mint_packages`] puts their techy packages on the scope stack: the order
/// of each feature's first declaration in `elements`. A later feature's
/// package shadows an earlier one's.
///
/// The registry's retained declarations
/// ([`Declarations`](crate::core::registry::Declarations)) are kept in this
/// order too, so that the last declaration of a name is the one in force.
pub(crate) fn feature_stack_order(elements: &[ElementDef]) -> Vec<FeatureName> {
    let mut owners: Vec<FeatureName> = Vec::new();
    for def in elements {
        if !owners.contains(&def.owner) {
            owners.push(def.owner.clone());
        }
    }
    owners
}

/// Builds every techy package and the fallback provider from the features'
/// declarations, and reports the declarations that do not fit.
///
/// `elements`, `fallbacks`, `scoped_packages` and `overrides` are the
/// declarations of every feature, in registration order. `explicitly_before`
/// holds the pairs `(a, b)` of features such that the feature order places `a`
/// explicitly before `b` ([`crate::core::registry::order`]); it decides which
/// features may define one name without an override. `peer_scoped_packages`
/// lists, as (feature, name), the scoped packages each feature declared as a
/// peer: that feature's bodies and arguments may refer to such a package even
/// when no feature declares it, in which case the reference adds nothing to
/// the parsing state and nothing is reported here. `structural` supplies the
/// elements that the language's own two fallbacks carry
/// (`flm.unknown.macro`, `flm.unknown.environment`), and the field element
/// that every tack-on field's specification carries (`flm.field`).
///
/// It never fails: every problem is collected in
/// [`MintedProviders::errors`] as a [`MintError`], and the rest is built. The
/// rules (the order of the packages, how two features that define one name are
/// handled, the two packages kept off the scope stack) are in the [module
/// documentation](self).
///
/// The language build ([`build_language`](crate::lang::build_language)) calls
/// it with the registry's declarations. Call it directly only to build techy
/// packages from declarations outside a registry, as the `userdefs` feature
/// does for the language of its templates
/// ([`TemplateLanguage`](crate::lang::rewrites::userdefs::TemplateLanguage)).
pub fn mint_packages(
    elements: &[ElementDef],
    fallbacks: &[FallbackDef],
    scoped_packages: &[ScopedPackageDef],
    overrides: &[OverrideDef],
    explicitly_before: &BTreeSet<(FeatureName, FeatureName)>,
    peer_scoped_packages: &[(FeatureName, Name)],
    structural: &StructuralElements,
) -> MintedProviders {
    let mut errors = Vec::new();

    // Scoped packages first — each after the scoped packages its bodies name —
    // so the environment bodies referring to them by name find them minted; then
    // the features' own packages, in registration order, one per weakness and
    // set of parsing modes a feature's declarations name. Both are minted inside
    // the fields package's builder, which receives the specs of every tack-on
    // field. A feature may need several packages because a package holds one
    // entry per callable form and name: a name declared once for text and once
    // for mathematics would otherwise keep only the later declaration, and a
    // package's declarations stand at one place of the scope stack, where weak
    // and ordinary declarations stand apart.
    let declared: BTreeSet<Name> = scoped_packages.iter().map(|p| p.name.clone()).collect();
    let peers: BTreeSet<(FeatureName, Name)> = peer_scoped_packages.iter().cloned().collect();
    let order = scoped_mint_order(scoped_packages, &mut errors);
    let owners = feature_stack_order(elements);
    for owner in &owners {
        report_redeclarations(owner, elements, &mut errors);
    }
    let mut scoped: BTreeMap<Name, Arc<Package<Flm>>> = BTreeMap::new();
    // Each minted package of the features, in registration order, with its
    // owner and whether its declarations are weak: a feature has one package
    // per weakness and distinct set of parsing modes its declarations name.
    let mut minted_packages: Vec<(FeatureName, bool, Arc<Package<Flm>>)> =
        Vec::with_capacity(owners.len());
    let fields = Package::new_shared(FIELDS_PACKAGE_NAME, |fields| {
        let mut home = FieldsHome { package: fields, element: &structural.field };
        for index in order {
            let package = &scoped_packages[index];
            let minted = Package::new_shared(package.name.as_str(), |pkg| {
                for def in &package.elements {
                    if is_weak(def) {
                        errors.push(MintError::WeakInScopedPackage {
                            owner: package.owner.clone(),
                            package: package.name.clone(),
                            element: def.element.name.clone(),
                        });
                    }
                    let scopes = Scopes { minted: &scoped, declared: &declared, peers: &peers };
                    insert_element(pkg, def, &scopes, &mut errors, &mut home);
                }
            });
            scoped.insert(package.name.clone(), minted);
        }
        for owner in &owners {
            let groups = mode_groups(owner, elements);
            for (position, (weak, group)) in groups.iter().enumerate() {
                let name = package_name(owner, position);
                let minted = Package::new_shared(name.as_str(), |pkg| {
                    for def in group {
                        let scopes = Scopes { minted: &scoped, declared: &declared, peers: &peers };
                        insert_element(pkg, def, &scopes, &mut errors, &mut home);
                    }
                });
                minted_packages.push((owner.clone(), *weak, minted));
            }
        }
    });

    // Clash detection over the packages' own symbol enumeration, per mode.
    let mut symbols: BTreeMap<Symbol, FeatureName> = BTreeMap::new();
    let mut definers: BTreeMap<Symbol, Vec<Definer>> = BTreeMap::new();
    for (owner, weak, package) in &minted_packages {
        for &callable_type in FlmCallableType::ALL {
            let kind = match callable_type {
                FlmCallableType::Macro => CallableKind::Macro,
                FlmCallableType::Environment => CallableKind::Environment,
                FlmCallableType::Specials => CallableKind::Specials,
                _ => continue,
            };
            for &mode in Mode::ALL {
                let Some(entries) = package.iter_symbols(callable_type, mode) else {
                    continue;
                };
                for entry in entries {
                    let symbol = Symbol { kind, name: entry.name.to_string() };
                    let list = definers.entry(symbol).or_default();
                    let definer = match list.iter().position(|definer| &definer.owner == owner) {
                        Some(position) => &mut list[position],
                        None => {
                            list.push(Definer {
                                owner: owner.clone(),
                                ordinary: Vec::new(),
                                weak: Vec::new(),
                            });
                            list.last_mut().expect("just pushed")
                        }
                    };
                    let modes = if *weak { &mut definer.weak } else { &mut definer.ordinary };
                    if !modes.contains(&mode) {
                        modes.push(mode);
                    }
                }
            }
        }
    }
    for (symbol, definers) in &definers {
        // The definition that applies: the last ordinary one, or the last weak
        // one when every declaration of the name is weak.
        let applying = definers
            .iter()
            .rev()
            .find(|definer| !definer.ordinary.is_empty())
            .or_else(|| definers.last())
            .expect("a symbol has at least one definer");
        symbols.insert(symbol.clone(), applying.owner.clone());
        // Each parsing mode on its own: the features that define the name
        // ordinarily in that mode, or weakly when none does so ordinarily, and
        // the last of them, whose definition applies there. Only that feature's
        // override is consulted; the feature order allows the collision when
        // it places that feature explicitly after every other, since placing a
        // feature after another both makes its definition apply and states
        // that the collision is intended.
        for &mode in Mode::ALL {
            let weak = !definers.iter().any(|definer| definer.defines(mode, false));
            let owners_of: Vec<FeatureName> = definers
                .iter()
                .filter(|definer| definer.defines(mode, weak))
                .map(|definer| definer.owner.clone())
                .collect();
            let [_, .., winner] = owners_of.as_slice() else {
                continue;
            };
            let overridden = overrides.iter().any(|o| {
                o.owner == *winner && o.kind == symbol.kind && o.name.as_str() == symbol.name
            });
            let ordered = owners_of[..owners_of.len() - 1]
                .iter()
                .all(|other| explicitly_before.contains(&(other.clone(), winner.clone())));
            if overridden || ordered {
                continue;
            }
            let chains = owners_of
                .iter()
                .map(|chosen| {
                    owners_of
                        .iter()
                        .filter(|owner| *owner != chosen)
                        .chain([chosen])
                        .cloned()
                        .collect::<Vec<FeatureName>>()
                })
                .filter(|chain| agrees_with_explicit_order(chain, explicitly_before))
                .collect();
            errors.push(MintError::Clash {
                kind: ClashKind::Symbol,
                symbol: symbol.clone(),
                modes: vec![mode],
                winner: winner.clone(),
                owners: owners_of,
                chains,
            });
        }
    }

    // The fallbacks: the features' first (a later one overlapping an earlier one
    // of the same kind is a clash and is not installed), then the language
    // layer's own two recovery fallbacks, each for every mode. Being last, they
    // are consulted only where no feature answers.
    let mut pending: Vec<PendingFallback> = Vec::new();
    for def in fallbacks {
        let overlapping: Vec<Mode> = Mode::ALL
            .iter()
            .copied()
            .filter(|mode| {
                def.modes.contains(mode)
                    && pending.iter().any(|p| p.kind == def.kind && p.modes.contains(mode))
            })
            .collect();
        if !overlapping.is_empty() {
            let mut owners_of: Vec<FeatureName> = Vec::new();
            for earlier in &pending {
                let overlaps = earlier.kind == def.kind
                    && earlier.modes.iter().any(|mode| overlapping.contains(mode));
                if overlaps && !owners_of.contains(&earlier.owner) {
                    owners_of.push(earlier.owner.clone());
                }
            }
            owners_of.push(def.owner.clone());
            let first = owners_of[0].clone();
            errors.push(MintError::Clash {
                kind: ClashKind::Fallback,
                symbol: Symbol { kind: def.kind.callable_kind(), name: def.kind.to_string() },
                modes: overlapping,
                owners: owners_of,
                winner: first,
                chains: Box::default(),
            });
            continue;
        }
        pending.push(PendingFallback {
            owner: def.owner.clone(),
            modes: def.modes.clone(),
            kind: def.kind,
            element: Arc::clone(&def.element),
            recovery: false,
        });
    }
    pending.push(PendingFallback {
        owner: FeatureName::from(LANGUAGE_OWNER),
        modes: Mode::ALL.to_vec(),
        kind: FallbackKind::Macro,
        element: Arc::clone(&structural.unknown_macro),
        recovery: true,
    });
    pending.push(PendingFallback {
        owner: FeatureName::from(LANGUAGE_OWNER),
        modes: Mode::ALL.to_vec(),
        kind: FallbackKind::Environment,
        element: Arc::clone(&structural.unknown_environment),
        recovery: true,
    });
    let fallback = Arc::new(FlmFallbackProvider::build(&pending));

    // The scope stack's order: every package of weak declarations under every
    // package of ordinary declarations, each part in registration order.
    let (weak, ordinary): (Vec<_>, Vec<_>) =
        minted_packages.into_iter().partition(|(_, weak, _)| *weak);
    let packages = weak.into_iter().chain(ordinary).map(|(_, _, package)| package).collect();

    MintedProviders { packages, scoped, fallback, fields, symbols, errors }
}

/// Whether adding `chain` to the feature order makes no cycle: the explicit
/// order in force (`explicitly_before`, transitively closed) places no feature
/// of `chain` before a feature that comes earlier in `chain`.
fn agrees_with_explicit_order(
    chain: &[FeatureName],
    explicitly_before: &BTreeSet<(FeatureName, FeatureName)>,
) -> bool {
    chain.iter().enumerate().all(|(i, earlier)| {
        chain[i + 1..]
            .iter()
            .all(|later| !explicitly_before.contains(&(later.clone(), earlier.clone())))
    })
}

// --- scoped package ordering ------------------------------------------------------------

/// Returns the scoped packages the declarations of `package` refer to: in an
/// environment's body, and in any argument, a tack-on field's own arguments
/// included.
fn scoped_dependencies(package: &ScopedPackageDef) -> Vec<&Name> {
    /// Collects the packages an argument list refers to, a tack-on field's
    /// arguments included.
    fn named_by<'d>(args: &'d [ArgDef], out: &mut Vec<&'d Name>) {
        for arg in args {
            out.extend(arg.scoped.iter());
            if let Some(fields) = arg.kind.tack_on_fields() {
                for field in fields {
                    named_by(&field.args, out);
                }
            }
        }
    }
    let mut out = Vec::new();
    for def in &package.elements {
        match &def.syntax {
            SyntaxDef::Macro { args } | SyntaxDef::Inclusion { args } | SyntaxDef::Specials { args, .. } => named_by(args, &mut out),
            SyntaxDef::Environment { args, body } => {
                named_by(args, &mut out);
                out.extend(body.scoped.iter());
            }
            SyntaxDef::Synthesized => {}
        }
    }
    out
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Mark {
    Unvisited,
    Open,
    Done,
}

/// Returns the order in which the scoped packages are built: each after the
/// ones its declarations refer to. The traversal is depth-first and follows
/// declaration order, so the result is the same on every run.
///
/// A package name declared twice is reported, and only the first declaration
/// is built; a cycle is reported once and broken at the reference that
/// closes it.
fn scoped_mint_order(packages: &[ScopedPackageDef], errors: &mut Vec<MintError>) -> Vec<usize> {
    let mut by_name: BTreeMap<&Name, usize> = BTreeMap::new();
    for (index, package) in packages.iter().enumerate() {
        match by_name.get(&package.name) {
            Some(&first) => {
                let owners = vec![packages[first].owner.clone(), package.owner.clone()];
                errors.push(MintError::Clash {
                    kind: ClashKind::ScopedPackage,
                    symbol: Symbol { kind: CallableKind::Macro, name: package.name.to_string() },
                    modes: Vec::new(),
                    winner: owners[0].clone(),
                    owners,
                    chains: Box::default(),
                });
            }
            None => {
                by_name.insert(&package.name, index);
            }
        }
    }
    let mut marks = vec![Mark::Unvisited; packages.len()];
    let mut order = Vec::with_capacity(packages.len());
    let mut path = Vec::new();
    for index in 0..packages.len() {
        if by_name.get(&packages[index].name) == Some(&index) {
            visit_scoped(index, packages, &by_name, &mut marks, &mut path, &mut order, errors);
        }
    }
    order
}

/// One step of that ordering: visits the packages this one refers to, then
/// places it.
fn visit_scoped(
    index: usize,
    packages: &[ScopedPackageDef],
    by_name: &BTreeMap<&Name, usize>,
    marks: &mut [Mark],
    path: &mut Vec<usize>,
    order: &mut Vec<usize>,
    errors: &mut Vec<MintError>,
) {
    match marks[index] {
        Mark::Done => return,
        Mark::Open => {
            let start = path.iter().position(|&open| open == index).unwrap_or(0);
            let cycle = path[start..].iter().map(|&open| packages[open].name.clone()).collect();
            errors.push(MintError::ScopedPackageCycle { packages: cycle });
            return;
        }
        Mark::Unvisited => {}
    }
    marks[index] = Mark::Open;
    path.push(index);
    for name in scoped_dependencies(&packages[index]) {
        if let Some(&dependency) = by_name.get(name) {
            visit_scoped(dependency, packages, by_name, marks, path, order, errors);
        }
    }
    path.pop();
    marks[index] = Mark::Done;
    order.push(index);
}

// --- a feature's packages ---------------------------------------------------------------

/// Returns the parsing modes a declaration is available in
/// ([`ElementDef::modes`]), as positions in [`Mode::ALL`].
fn visible_modes(def: &ElementDef) -> Vec<usize> {
    (0..Mode::ALL.len()).filter(|index| def.modes.contains(&Mode::ALL[*index])).collect()
}

/// Returns the command names one declaration registers, as symbols: the
/// declaration's names for a macro or an environment, the trigger for a
/// special character sequence, nothing for an element with no syntax.
fn declared_symbols(def: &ElementDef) -> Vec<Symbol> {
    let Some(kind) = def.syntax.kind() else { return Vec::new() };
    match &def.syntax {
        SyntaxDef::Specials { trigger, .. } => {
            vec![Symbol { kind, name: trigger.clone() }]
        }
        _ => def
            .names
            .iter()
            .map(|name| Symbol { kind, name: name.to_string() })
            .collect(),
    }
}

/// Reports every name `owner` declares twice in parsing modes that overlap.
/// Both declarations of such a pair cannot apply where the modes overlap; a
/// pair whose modes are disjoint is sound and is built into two packages
/// ([`mode_groups`]).
fn report_redeclarations(
    owner: &FeatureName,
    elements: &[ElementDef],
    errors: &mut Vec<MintError>,
) {
    let mut seen: Vec<(Symbol, Vec<usize>)> = Vec::new();
    for def in elements.iter().filter(|def| &def.owner == owner) {
        let modes = visible_modes(def);
        for symbol in declared_symbols(def) {
            match seen.iter_mut().find(|(earlier, _)| earlier == &symbol) {
                Some((_, earlier_modes)) => {
                    let overlapping: Vec<Mode> = modes
                        .iter()
                        .filter(|index| earlier_modes.contains(index))
                        .map(|index| Mode::ALL[*index])
                        .collect();
                    if !overlapping.is_empty() {
                        errors.push(MintError::Redeclared {
                            symbol: symbol.clone(),
                            owner: owner.clone(),
                            modes: overlapping,
                        });
                    }
                    for index in &modes {
                        if !earlier_modes.contains(index) {
                            earlier_modes.push(*index);
                        }
                    }
                }
                None => seen.push((symbol, modes.clone())),
            }
        }
    }
}

/// Returns the declarations of `owner`, grouped by weakness ([`is_weak`])
/// and by the set of parsing modes they list, in the order the groups first
/// appear, each with its weakness. Each group becomes one package, and the
/// first group's package has the feature's own name ([`package_name`]).
///
/// Two declarations that list the same modes in a different order, or one
/// mode twice, are grouped together.
fn mode_groups<'e>(
    owner: &FeatureName,
    elements: &'e [ElementDef],
) -> Vec<(bool, Vec<&'e ElementDef>)> {
    let mut keys: Vec<(bool, Vec<usize>)> = Vec::new();
    let mut groups: Vec<(bool, Vec<&ElementDef>)> = Vec::new();
    for def in elements.iter().filter(|def| &def.owner == owner) {
        let key = (is_weak(def), visible_modes(def));
        match keys.iter().position(|seen| seen == &key) {
            Some(position) => groups[position].1.push(def),
            None => {
                groups.push((key.0, vec![def]));
                keys.push(key);
            }
        }
    }
    groups
}

/// Returns the name of a feature's package at `position` among its packages:
/// the feature's own name for the first, which is the only one a feature with
/// one set of parsing modes has, and `<feature>#<n>` for the rest, with `n`
/// counting from 2.
///
/// The names must differ, because a serialized tree records the name of the
/// package a specification came from and is read back by that name.
fn package_name(owner: &FeatureName, position: usize) -> String {
    match position {
        0 => owner.to_string(),
        other => format!("{owner}#{}", other + 1),
    }
}

// --- element insertion ------------------------------------------------------------------

/// Builds one element declaration into `pkg`, one specification per name it is
/// written under. `fields` is the fields package, which receives the
/// specifications of its tack-on fields ([`FieldsHome`]).
fn insert_element(
    pkg: &mut Package<Flm>,
    def: &ElementDef,
    scopes: &Scopes<'_>,
    errors: &mut Vec<MintError>,
    fields: &mut FieldsHome<'_>,
) {
    match &def.syntax {
        SyntaxDef::Macro { args } => {
            let args = argument_specs_of(args, None, fields, def, scopes, errors);
            let syntax: Arc<dyn CallableSpec<Flm>> = Arc::new(MacroSpec::<Flm>::new(args.specs));
            insert_callables(pkg, def, CallableKind::Macro, &syntax, &args.layouts, errors);
        }
        SyntaxDef::Inclusion { args } => {
            let args = argument_specs_of(args, None, fields, def, scopes, errors);
            match InputSpec::new(args.specs) {
                Ok(spec) => {
                    let syntax: Arc<dyn CallableSpec<Flm>> = Arc::new(spec);
                    insert_callables(pkg, def, CallableKind::Macro, &syntax, &args.layouts, errors);
                }
                Err(detail) => errors.push(MintError::NoReferenceArgument {
                    owner: def.owner.clone(),
                    element: def.element.name.clone(),
                    detail,
                }),
            }
        }
        SyntaxDef::Specials { trigger, args } => {
            let args = argument_specs_of(args, None, fields, def, scopes, errors);
            let syntax: Arc<dyn CallableSpec<Flm>> =
                Arc::new(SpecialsSpec::<Flm>::new(args.specs));
            insert_specials(pkg, def, trigger, &syntax, &args.layouts, errors);
        }
        SyntaxDef::Environment { args, body } => {
            let args = argument_specs_of(args, None, fields, def, scopes, errors);
            let environment =
                FlmEnvironment::new(args.specs, Arc::clone(&def.element), body.clone())
                    .with_arg_layouts(args.layouts);
            insert_environment(pkg, def, environment, body, scopes, errors);
        }
        SyntaxDef::Synthesized => {
            if !def.names.is_empty() {
                errors.push(MintError::SynthesizedWithNames {
                    owner: def.owner.clone(),
                    element: def.element.name.clone(),
                });
            }
        }
    }
}

/// Inserts a macro specification under each of the declaration's names,
/// restricted to its parsing modes, recording the layouts of its arguments.
fn insert_callables(
    pkg: &mut Package<Flm>,
    def: &ElementDef,
    kind: CallableKind,
    syntax: &Arc<dyn CallableSpec<Flm>>,
    layouts: &[ArgLayout],
    errors: &mut Vec<MintError>,
) {
    if def.names.is_empty() {
        errors.push(no_names(def));
        return;
    }
    let callable_type = kind.callable_type();
    for name in &def.names {
        let mut callable = FlmCallable::new(Arc::clone(syntax), Arc::clone(&def.element))
            .with_arg_layouts(layouts.to_vec());
        if let Some(provenance) = pkg.provenance_for(callable_type, name.as_str()) {
            callable = callable.with_provenance(provenance);
        }
        insert_in_modes(pkg, callable_type, name, callable, def);
    }
}

/// Inserts a special-character-sequence specification under the declaration's
/// trigger, restricted to its parsing modes, recording the layouts of its
/// arguments.
fn insert_specials(
    pkg: &mut Package<Flm>,
    def: &ElementDef,
    trigger: &str,
    syntax: &Arc<dyn CallableSpec<Flm>>,
    layouts: &[ArgLayout],
    errors: &mut Vec<MintError>,
) {
    if !def.names.is_empty() {
        errors.push(MintError::SpecialsWithNames {
            owner: def.owner.clone(),
            trigger: trigger.to_string(),
        });
    }
    let mut callable = FlmCallable::new(Arc::clone(syntax), Arc::clone(&def.element))
        .with_arg_layouts(layouts.to_vec());
    if let Some(provenance) = pkg.provenance_for_specials(FlmCallableType::Specials, trigger) {
        callable = callable.with_provenance(provenance);
    }
    pkg.insert_specials_in_modes(FlmCallableType::Specials, trigger, callable, Some(def.modes.clone()));
}

/// Inserts an environment under each of the declaration's names, with the change
/// of parsing state its body declaration asks for.
fn insert_environment(
    pkg: &mut Package<Flm>,
    def: &ElementDef,
    mut environment: FlmEnvironment,
    body: &BodyDef,
    scopes: &Scopes<'_>,
    errors: &mut Vec<MintError>,
) {
    if def.names.is_empty() {
        errors.push(no_names(def));
        return;
    }
    if body.opaque_wrapper && body.layout != BodyLayout::FromRole {
        errors.push(MintError::LayoutOnOpaqueWrappedBody {
            owner: def.owner.clone(),
            element: def.element.name.clone(),
        });
    }
    let unknown = |package: &Name| MintError::UnknownScopedPackage {
        element: def.element.name.clone(),
        owner: def.owner.clone(),
        argument: None,
        field: None,
        package: package.clone(),
    };
    if let Some(delta) = region_delta(body.mode, &body.scoped, &body.events, &def.owner, scopes, unknown, errors) {
        environment = environment.with_body_delta(delta);
    }
    let spec = environment.into_spec();
    for name in &def.names {
        let stamped = match pkg.provenance_for(FlmCallableType::Environment, name.as_str()) {
            Some(provenance) => spec.clone().with_provenance(provenance),
            None => spec.clone(),
        };
        insert_in_modes(pkg, FlmCallableType::Environment, name, stamped, def);
    }
}

/// Returns the error for a macro or environment declaration that lists no
/// name.
fn no_names(def: &ElementDef) -> MintError {
    MintError::NoNames { owner: def.owner.clone(), element: def.element.name.clone() }
}

/// Inserts a specification under one name, restricted to the declaration's
/// parsing modes.
fn insert_in_modes<M>(
    pkg: &mut Package<Flm>,
    callable_type: FlmCallableType,
    name: &Name,
    spec: impl techy::core::specs::IntoCallableSpec<Flm, M>,
    def: &ElementDef,
) {
    pkg.insert_in_modes(callable_type, name.as_str(), spec, Some(def.modes.clone()));
}

/// Returns the change of parsing state a declared parsing mode asks for, or
/// `None` when the declaration keeps the mode of the place where the command
/// is written.
///
/// This is the only place where a declared mode becomes a change of parsing
/// state, for an argument ([`ArgDef::mode`]) and for an environment's body
/// ([`BodyDef::mode`]) alike, through [`region_delta`]. `Math` enters
/// mathematics; `Text` carries the event [`FlmEvent::ExitMathContext`], which
/// restores the innermost enclosing non-mathematics context, with its mode and
/// its token rules. That change makes `\text{…}`
/// inside mathematics hold ordinary document content, and changes nothing
/// outside mathematics. The events a declaration lists of its own
/// ([`ArgDef::events`], [`BodyDef::events`]) are added after this one by
/// [`region_delta`].
fn mode_delta(mode: Option<Mode>) -> Option<ParsingStateDelta<Flm>> {
    match mode {
        Some(Mode::Math) => Some(ParsingStateDelta::new().mode(Mode::Math)),
        Some(Mode::Text) => Some(ParsingStateDelta::new().event(FlmEvent::ExitMathContext)),
        _ => None,
    }
}

/// Returns the change of parsing state that the declaration of an
/// environment's body ([`BodyDef`]) or of an argument ([`ArgDef`]) asks for:
/// the mode it enters, the scoped packages it adds to the scope stack, in
/// the order they are listed, and its state events (`events`), in the order
/// they are listed, after the event of the mode ([`mode_delta`]). Returns
/// `None` when the declaration asks for no change.
///
/// techy applies what the events resolve to before the mode and the scoped
/// packages, so one declaration can ask for the standard state, in
/// mathematics, with a scoped package of its own.
///
/// A scoped package that is declared but not yet built (one caught in a
/// cycle, which is reported separately) is skipped without a second report.
/// So is a package that no feature declares and that `owner`, the feature
/// whose declaration refers to it, declared as a peer; the registry build
/// reports that one. Any other package that no feature declares is reported
/// with the error `unknown` builds.
fn region_delta(
    mode: Option<Mode>,
    packages: &[Name],
    events: &[FlmEvent],
    owner: &FeatureName,
    scopes: &Scopes<'_>,
    unknown: impl Fn(&Name) -> MintError,
    errors: &mut Vec<MintError>,
) -> Option<ParsingStateDelta<Flm>> {
    let mut delta = mode_delta(mode).unwrap_or_default();
    let mut any = mode.is_some() || !events.is_empty();
    for event in events {
        delta = delta.event(event.clone());
    }
    for name in packages {
        match scopes.minted.get(name) {
            Some(package) => {
                let provider: Arc<dyn SpecsProvider<Flm>> = package.clone();
                delta = delta.push_provider(provider);
                any = true;
            }
            None if scopes.declared.contains(name) => {}
            None if scopes.peers.contains(&(owner.clone(), name.clone())) => {}
            None => errors.push(unknown(name)),
        }
    }
    any.then_some(delta)
}