flm-core 0.6.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
//! The checks of the registry build's validate phase, which run over the
//! collected declarations ([`Roster`]) before anything is numbered, and the
//! resolution of the peer declarations.
//!
//! Every check here works on names alone, over the declarations the feature
//! builders recorded. Every problem found is collected, not raised, so that
//! one build reports every problem of the phase at once. The declarations are
//! numbered into the frozen registry only after these checks pass.
//!
//! # The checks of [`validate`]
//!
//! - Duplicate declarations in every namespace: features, presentation
//!   elements (including a presentation element that reuses the name of an
//!   element a document can contain), capabilities, tables, collections,
//!   argument roles, stages, lowering rules, backends, outputs, option types,
//!   workflows, and the peer declarations of one feature. For a peer declaration, only a repeat with
//!   another signature is a duplicate; [`merge_repeated_peers`] has already
//!   merged an identical repeat into the first declaration.
//! - The namespace that capabilities, tables and collections share.
//! - References to entities that no feature declares, from every place where
//!   one can be written: the capability a capability refines; a stage's
//!   provided capabilities and written tables (with the value type each write
//!   expects); a collection member; a rule's element, and what it produces,
//!   requires and reads; the backend in a rule's default mark; a backend's
//!   native elements; an ordering edge's stage and capabilities; an output's
//!   capability and table; a workflow's `extends`, outputs, demands,
//!   preferred stages, the backends of its lowering selections and their
//!   preferred lowering rules, and the backends and elements of its list of
//!   elements accepted as unrenderable; the element of an aspect
//!   attachment; and the role of an argument of an element declaration
//!   (including the arguments of its tack-on fields and of the declarations
//!   of scoped packages), which must be declared by some feature or declared
//!   as a peer by the feature whose declaration holds the argument.
//! - Chains of capability refinements and chains of workflows that lead back
//!   to themselves.
//! - At most one default refinement per capability, and no default
//!   refinement without a parent.
//! - A check stage that declares a write, and any stage that writes an
//!   external table.
//! - A collection where a capability is expected: a collection can be
//!   demanded, never provided.
//! - At most one default lowering rule per element and backend.
//! - An output whose capability is neither its table's capability nor a
//!   refinement of it, and an output whose table does not hold an artifact
//!   set.
//! - A native-set implication whose required element no feature declares.
//! - A part of a style or script definition taken from a table
//!   ([`DefContent::Table`]) that names a table no feature declares, or a
//!   table that does not hold [`DefinitionText`].
//! - A workflow's render option value whose option type no feature declares,
//!   or whose option type cannot be set on a render request.
//!
//! [`validate`] does not report three kinds of reference as undeclared: a
//! backend in a rule's default mark, an element in the rule's `produces`, and
//! a table in the rule's `reads` or `reads_opt`, when the rule's own feature
//! made a [peer declaration](crate::core::registry::PeerName) of that name.
//! [`resolve_peers`] handles those; it runs *before* [`validate`] over the
//! same declarations, resolves every peer declaration against what the
//! features declared, reports each signature mismatch, and marks as set
//! aside (excluded from rule selection) the rules that depend on an
//! unresolved name.
//!
//! Every table a rule reads is checked, whether or not the rule is set aside:
//! the name must be a table that some feature of the registry declares, or a
//! peer declaration of the rule's own feature, and any other name is an
//! undeclared reference. A feature can therefore ship a lowering rule for
//! another feature's backend that reads a third feature's table (for
//! example, a mathematics environment written back to LaTeX with the label
//! keys the references feature assigns) and still be registered alone, while
//! a misspelled table name is still caught wherever it is written.
//!
//! One check runs apart from the others, after the aspects that features
//! attach to other features' elements have been merged into the element
//! values: [`native_implications`], which checks every backend's native set
//! against every declared native-set implication.
//!
//! By then, the build has already dropped, without any diagnostic, every
//! member added to a collection that no feature declares; the checks above
//! check the remaining members.
//!
//! The documentation texts of element types are checked apart too, before
//! the peer element values are resolved: [`element_type_texts`] refuses a
//! text from a feature that does not declare its element type and a second
//! text for one element type.
//!
//! # Checks that run when a plan is built
//!
//! What a stage requires and reads is a need of one plan, not of the
//! registry: one registry can serve a plan in which a requirement can be
//! satisfied and a plan in which it cannot. These checks therefore run when a
//! plan is built: whether every requirement can be satisfied, whether a
//! stage requires a capability that shares an ancestor with one it provides,
//! whether a rewrite stage declares a read of computed data, and whether a
//! stage's requirements list a collection.

use std::any::TypeId;
use std::collections::{BTreeMap, BTreeSet};

use crate::core::artifact::ArtifactSet;
use crate::model::element::ElementSpec;
use crate::model::names::{
    BackendName, CapName, ElementName, FeatureName, Name, RuleName, StageName, WorkflowName,
};
use crate::model::options::{BindSite, OptionKey};
use crate::model::options::TypeKey;
use crate::core::registry::builder::{ArgumentPlace, BuildError, Roster, Site};
use crate::core::registry::frozen::ElementTypeText;
use crate::core::registry::declarations::arguments_of;
use crate::core::registry::entities::{DefContent, DefinitionText, NativeImplicationKind};
use crate::core::registry::entities::PeerName;
use crate::core::stage::Effect;
use crate::core::data::table::{TableRef, TableType};
use crate::lang::mint::{ElementDef, SyntaxDef};
use crate::lang::structural::StructuralElements;

/// The kind of declaration that took a name in the namespace that
/// capabilities, tables and collections share.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CapKind {
    /// A capability declared on its own.
    Explicit,
    /// A table, whose name is also a capability.
    Table,
    /// A collection, which may be demanded but never provided.
    Collection,
}

/// What the checks need to know about one name in the namespace that
/// capabilities, tables and collections share.
struct CapInfo {
    /// The feature that declared it.
    owner: FeatureName,
    /// Which kind of declaration it was.
    kind: CapKind,
    /// The capability it refines, if the declaration gives one.
    refines: Option<CapName>,
    /// Whether it is marked as its parent's default refinement.
    default: bool,
}

/// The command that the element declaration `def` defines, as an author
/// writes it, for a message: `\name` for a macro, `\begin{name}` for an
/// environment (the first of its names), the trigger of a special character
/// sequence, and the element's name for a declaration with no syntax.
fn written_command(def: &ElementDef) -> String {
    let first = def.names.first().map(Name::as_str).unwrap_or_default();
    match &def.syntax {
        SyntaxDef::Macro { .. } | SyntaxDef::Inclusion { .. } => format!("\\{first}"),
        SyntaxDef::Environment { .. } => format!("\\begin{{{first}}}"),
        SyntaxDef::Specials { trigger, .. } => trigger.clone(),
        SyntaxDef::Synthesized => def.element.name.to_string(),
    }
}

/// Every element type that the declarations `roster` create, once for each
/// declaration that creates it, with the feature that declares it, in the
/// sense of
/// [`FeatureBuilder::peer_element_value`](crate::core::registry::FeatureBuilder::peer_element_value):
/// the language ([`LANGUAGE_OWNER`](crate::lang::mint::LANGUAGE_OWNER)) for
/// the structural element names `structural`, and a feature for each element
/// that one of its declarations creates (an element declaration, an element
/// of a scoped package, a fallback, a presentation element, and the field
/// element for a tack-on field of an argument).
///
/// The element declarations at the positions `set_apart` of
/// [`Roster::elements`] are left out: a caller passes the positions of the
/// peer element values, which create no element type.
fn element_declarations(
    roster: &Roster,
    structural: &[&str],
    set_apart: &BTreeSet<usize>,
) -> Vec<(ElementName, FeatureName)> {
    let language = FeatureName::from(crate::lang::mint::LANGUAGE_OWNER);
    let mut pairs: Vec<(ElementName, FeatureName)> =
        structural.iter().map(|name| (ElementName::from(*name), language.clone())).collect();
    let field = ElementName::from(crate::lang::structural::FIELD);
    let mut declaration = |def: &ElementDef| {
        pairs.push((def.element.name.clone(), def.owner.clone()));
        let mut arguments = Vec::new();
        arguments_of(def, None, &mut arguments);
        let tack_on = arguments
            .iter()
            .any(|argument| argument.arg.kind.tack_on_fields().is_some_and(|fields| !fields.is_empty()));
        if tack_on {
            pairs.push((field.clone(), def.owner.clone()));
        }
    };
    for (position, def) in roster.elements.iter().enumerate() {
        if !set_apart.contains(&position) {
            declaration(def);
        }
    }
    for package in &roster.scoped_packages {
        for def in &package.elements {
            declaration(def);
        }
    }
    for fallback in &roster.fallbacks {
        pairs.push((fallback.element.name.clone(), fallback.owner.clone()));
    }
    for pres in &roster.presentation {
        pairs.push((pres.element.name.clone(), pres.owner.clone()));
    }
    pairs
}

/// Every element type name that the declarations `roster` create
/// ([`element_declarations`], with every element declaration of
/// [`Roster::elements`] counted).
///
/// A reference to an element type outside this set is a reference to an
/// element that no feature declares.
pub(crate) fn declared_elements(roster: &Roster, structural: &[&str]) -> BTreeSet<ElementName> {
    element_declarations(roster, structural, &BTreeSet::new()).into_iter().map(|(name, _)| name).collect()
}

/// The cycle found while following a chain of parent links, given the chain
/// followed so far (`chain`) and the name that appeared a second time
/// (`repeated`).
///
/// The result starts at the first name of the cycle in name order, so one
/// cycle is always reported the same way, wherever the walk entered it, and
/// two builds produce the same messages.
fn canonical_cycle<N: Clone + Ord>(chain: &[N], repeated: &N) -> Vec<N> {
    let start = chain.iter().position(|name| name == repeated).unwrap_or(0);
    let mut cycle: Vec<N> = chain[start..].to_vec();
    let least = cycle
        .iter()
        .enumerate()
        .min_by(|(_, a), (_, b)| a.cmp(b))
        .map(|(index, _)| index)
        .unwrap_or(0);
    cycle.rotate_left(least);
    cycle
}

/// Merges into the earlier declaration every peer declaration that repeats
/// it identically (the same feature, the same name and, for an element or a
/// table, the same signature type); the earlier declaration's documentation
/// text is kept.
///
/// A peer declaration registers nothing; it states an expectation, and
/// stating the same expectation twice changes nothing. A function that
/// declares on a feature's behalf may therefore declare every name it needs
/// without checking what the feature declared already. A repeat with another
/// signature stays, and [`validate`] refuses it as
/// [`BuildError::Duplicate`].
///
/// Runs before [`resolve_peers`] and [`validate`], so that each of them sees
/// one entry per declared expectation.
pub(crate) fn merge_repeated_peers(roster: &mut Roster) {
    let mut backends: BTreeSet<(FeatureName, BackendName)> = BTreeSet::new();
    roster
        .peer_backends
        .retain(|record| backends.insert((record.owner.clone(), record.name.clone())));
    let mut elements: BTreeSet<(FeatureName, ElementName, TypeId)> = BTreeSet::new();
    roster.peer_elements.retain(|record| {
        elements.insert((record.owner.clone(), record.name.clone(), record.payload.type_id()))
    });
    let mut tables: BTreeSet<(FeatureName, CapName, TypeId)> = BTreeSet::new();
    roster.peer_tables.retain(|record| {
        tables.insert((record.owner.clone(), record.name.clone(), record.value.type_id()))
    });
    let mut packages: BTreeSet<(FeatureName, Name)> = BTreeSet::new();
    roster
        .peer_scoped_packages
        .retain(|record| packages.insert((record.owner.clone(), record.name.clone())));
    let mut roles: BTreeSet<(FeatureName, Name)> = BTreeSet::new();
    roster
        .peer_argument_roles
        .retain(|record| roles.insert((record.owner.clone(), record.name.clone())));
}

/// Every element type that the declarations `roster` create, each with the
/// features that declare it ([`element_declarations`], with the peer element
/// values set apart).
///
/// Reads the positions of the peer element values in
/// [`Roster::elements`], so it runs before
/// [`resolve_peer_element_values`] drops any of them.
fn element_type_declarers(
    roster: &Roster,
    structural: &[&str],
) -> BTreeMap<ElementName, BTreeSet<FeatureName>> {
    let peers: BTreeSet<usize> = roster.peer_element_values.iter().map(|record| record.position).collect();
    let mut declarers: BTreeMap<ElementName, BTreeSet<FeatureName>> = BTreeMap::new();
    for (name, owner) in element_declarations(roster, structural, &peers) {
        declarers.entry(name).or_default().insert(owner);
    }
    declarers
}

/// Checks the documentation texts that features gave to element types
/// ([`FeatureBuilder::element_type_text`](crate::core::registry::FeatureBuilder::element_type_text))
/// and completes them, in [`Roster::element_type_texts`], with the texts of
/// the language's structural element types (`structural`) and of the
/// presentation elements.
///
/// A text from a feature that does not declare the element type
/// ([`element_type_declarers`]) is a
/// [`BuildError::UndeclaredElementTypeText`] and is dropped; a second text
/// for one element type, after the language's, a presentation element's or
/// a feature's, is a [`BuildError::DuplicateElementTypeText`]. Of the
/// presentation elements of one name, a duplicate that [`validate`] reports,
/// the first gives the text.
///
/// Runs before [`resolve_peer_element_values`], which moves the peer element
/// values that [`element_type_declarers`] sets apart.
pub(crate) fn element_type_texts(roster: &mut Roster, structural: &[&str]) -> Vec<BuildError> {
    let declarers = element_type_declarers(roster, structural);
    let mut errors: Vec<BuildError> = Vec::new();
    let mut texts: Vec<ElementTypeText> = Vec::new();
    let language = FeatureName::from(crate::lang::mint::LANGUAGE_OWNER);
    for name in structural {
        if let Some(docs) = crate::lang::structural::type_text(name) {
            texts.push(ElementTypeText {
                element: ElementName::from(*name),
                docs: crate::kept_docs(docs),
                owner: language.clone(),
            });
        }
    }
    for pres in &roster.presentation {
        if texts.iter().all(|text| text.element != pres.element.name) {
            texts.push(ElementTypeText {
                element: pres.element.name.clone(),
                docs: pres.docs.clone(),
                owner: pres.owner.clone(),
            });
        }
    }
    for text in std::mem::take(&mut roster.element_type_texts) {
        let declaring = declarers.get(&text.element);
        if !declaring.is_some_and(|owners| owners.contains(&text.owner)) {
            errors.push(BuildError::UndeclaredElementTypeText {
                feature: text.owner,
                element: text.element,
                declarers: declaring.map(|owners| owners.iter().cloned().collect()).unwrap_or_default(),
            });
            continue;
        }
        if let Some(first) = texts.iter().find(|given| given.element == text.element) {
            errors.push(BuildError::DuplicateElementTypeText {
                element: text.element,
                first: first.owner.clone(),
                second: text.owner,
            });
            continue;
        }
        texts.push(text);
    }
    roster.element_type_texts = texts;
    errors
}

/// Resolves every peer declaration of an element value
/// ([`FeatureBuilder::peer_element_value`](crate::core::registry::FeatureBuilder::peer_element_value))
/// against the element types that the other declarations of `roster` create
/// ([`element_declarations`], with `structural` giving the names of the
/// language's structural elements and the peer declarations themselves set
/// apart). A declaration is resolved when its element type's name is among
/// them.
///
/// Each record is marked as resolved or not, and the unresolved declarations
/// are removed from [`Roster::elements`], so that no later step sees them;
/// the resolved ones stay where they were declared.
///
/// Returns each pair of feature and element type left unresolved, once, in
/// declaration order.
// An unresolved declaration is dropped, not refused: a feature that adds a value of
// another feature's element type must not make the registry unusable where that
// feature is absent.
pub(crate) fn resolve_peer_element_values(
    roster: &mut Roster,
    structural: &[&str],
) -> Vec<(FeatureName, ElementName)> {
    let peers: BTreeSet<usize> = roster.peer_element_values.iter().map(|record| record.position).collect();
    let declared: BTreeSet<ElementName> =
        element_declarations(roster, structural, &peers).into_iter().map(|(name, _)| name).collect();
    let mut dropped: BTreeSet<usize> = BTreeSet::new();
    let mut unresolved: Vec<(FeatureName, ElementName)> = Vec::new();
    for record in &mut roster.peer_element_values {
        record.resolved = declared.contains(&record.element);
        if record.resolved {
            continue;
        }
        dropped.insert(record.position);
        let key = (record.owner.clone(), record.element.clone());
        if !unresolved.contains(&key) {
            unresolved.push(key);
        }
    }
    let mut position = 0;
    roster.elements.retain(|_| {
        let keep = !dropped.contains(&position);
        position += 1;
        keep
    });
    unresolved
}

/// Runs every check listed in the [module documentation](self) over the
/// collected declarations `roster`, with `structural` giving the names of the
/// language's structural elements.
///
/// Returns every problem found, in the order found; an empty result means
/// that the declarations can be numbered into the frozen registry.
pub(crate) fn validate(roster: &Roster, structural: &[&str]) -> Vec<BuildError> {
    let mut errors: Vec<BuildError> = Vec::new();

    // --- features -------------------------------------------------------------------
    let mut seen_features: BTreeSet<&FeatureName> = BTreeSet::new();
    for info in &roster.features {
        if !seen_features.insert(&info.name) {
            errors.push(BuildError::DuplicateFeature { feature: info.name.clone() });
        }
    }

    // --- the capability name space ------------------------------------------------
    let mut caps: BTreeMap<CapName, CapInfo> = BTreeMap::new();
    for (owner, def) in &roster.capabilities {
        if let Some(existing) = caps.get(&def.name) {
            errors.push(BuildError::Duplicate {
                kind: "capability",
                name: def.name.name().clone(),
                first: existing.owner.clone(),
                second: owner.clone(),
            });
            continue;
        }
        caps.insert(
            def.name.clone(),
            CapInfo {
                owner: owner.clone(),
                kind: CapKind::Explicit,
                refines: def.refines.clone(),
                default: def.default,
            },
        );
    }
    let mut tables: BTreeMap<CapName, (FeatureName, TableRef, bool)> = BTreeMap::new();
    for record in &roster.tables {
        let def = &record.def;
        if let Some((first, _, _)) = tables.get(&def.name) {
            errors.push(BuildError::Duplicate {
                kind: "table",
                name: def.name.name().clone(),
                first: first.clone(),
                second: def.owner.clone(),
            });
            continue;
        }
        if let Some(existing) = caps.get(&def.name) {
            if existing.kind == CapKind::Explicit {
                errors.push(BuildError::TableCapabilityClash {
                    name: def.name.clone(),
                    table_owner: def.owner.clone(),
                    capability_owner: existing.owner.clone(),
                });
                continue;
            }
        }
        tables.insert(
            def.name.clone(),
            (
                def.owner.clone(),
                TableRef {
                    name: def.name.clone(),
                    type_id: def.ty.type_id(),
                    type_name: def.ty.type_name(),
                },
                record.external,
            ),
        );
        caps.insert(
            def.name.clone(),
            CapInfo {
                owner: def.owner.clone(),
                kind: CapKind::Table,
                refines: record.refines.clone(),
                default: record.default,
            },
        );
    }
    for (owner, def) in &roster.collections {
        if let Some(existing) = caps.get(&def.name) {
            errors.push(BuildError::Duplicate {
                kind: if existing.kind == CapKind::Collection {
                    "collection"
                } else {
                    "capability"
                },
                name: def.name.name().clone(),
                first: existing.owner.clone(),
                second: owner.clone(),
            });
            continue;
        }
        caps.insert(
            def.name.clone(),
            CapInfo {
                owner: owner.clone(),
                kind: CapKind::Collection,
                refines: None,
                default: false,
            },
        );
    }
    let cap_roster: Vec<Name> = caps
        .iter()
        .filter(|(_, info)| info.kind != CapKind::Collection)
        .map(|(name, _)| name.name().clone())
        .collect();
    let collection_roster: Vec<Name> = caps
        .iter()
        .filter(|(_, info)| info.kind == CapKind::Collection)
        .map(|(name, _)| name.name().clone())
        .collect();
    let table_roster: Vec<Name> = tables.keys().map(|name| name.name().clone()).collect();
    let is_cap = |name: &CapName| {
        caps.get(name).map(|info| info.kind != CapKind::Collection).unwrap_or(false)
    };
    let is_collection = |name: &CapName| {
        caps.get(name).map(|info| info.kind == CapKind::Collection).unwrap_or(false)
    };

    let undeclared_cap =
        |feature: &FeatureName, site: Site, name: &CapName, errors: &mut Vec<BuildError>| {
            if !is_cap(name) {
                errors.push(BuildError::Undeclared {
                    feature: feature.clone(),
                    kind: "capability",
                    site,
                    name: name.name().clone(),
                    roster: cap_roster.clone(),
                });
            }
        };
    let check_table = |feature: &FeatureName,
                       site: Site,
                       table: &TableRef,
                       errors: &mut Vec<BuildError>|
     -> bool {
        match tables.get(&table.name) {
            None => {
                errors.push(BuildError::Undeclared {
                    feature: feature.clone(),
                    kind: "table",
                    site,
                    name: table.name.name().clone(),
                    roster: table_roster.clone(),
                });
                false
            }
            Some((_, declared, _)) if declared.type_id != table.type_id => {
                errors.push(BuildError::TableTypeMismatch {
                    feature: feature.clone(),
                    site,
                    table: table.name.clone(),
                    declared: declared.short_type_name(),
                    referenced: table.short_type_name(),
                });
                false
            }
            Some(_) => true,
        }
    };

    // Refinement chains: parents declared and not collections, no cycles, one
    // default per parent, default only with a parent.
    let mut defaults: BTreeMap<CapName, CapName> = BTreeMap::new();
    for (name, info) in &caps {
        match &info.refines {
            Some(parent) => {
                if !is_cap(parent) {
                    errors.push(BuildError::Undeclared {
                        feature: info.owner.clone(),
                        kind: "capability",
                        site: Site::CapabilityRefines { capability: name.clone() },
                        name: parent.name().clone(),
                        roster: cap_roster.clone(),
                    });
                } else if info.default {
                    if let Some(first) = defaults.get(parent) {
                        errors.push(BuildError::TwoDefaults {
                            parent: parent.clone(),
                            first: first.clone(),
                            second: name.clone(),
                        });
                    } else {
                        defaults.insert(parent.clone(), name.clone());
                    }
                }
            }
            None if info.default => {
                errors.push(BuildError::DefaultWithoutParent { name: name.clone() })
            }
            None => {}
        }
    }
    let mut cycles: BTreeSet<Vec<CapName>> = BTreeSet::new();
    for name in caps.keys() {
        let mut chain = vec![name.clone()];
        let mut seen: BTreeSet<CapName> = BTreeSet::new();
        seen.insert(name.clone());
        let mut current = name.clone();
        while let Some(Some(parent)) = caps.get(&current).map(|info| info.refines.clone()) {
            if !is_cap(&parent) {
                break;
            }
            if !seen.insert(parent.clone()) {
                cycles.insert(canonical_cycle(&chain, &parent));
                break;
            }
            chain.push(parent.clone());
            current = parent;
        }
    }
    for cycle in cycles {
        errors.push(BuildError::RefinesCycle { cycle });
    }

    // --- elements -------------------------------------------------------------------
    let elements = declared_elements(roster, structural);
    let element_roster: Vec<Name> = elements.iter().map(|name| name.name().clone()).collect();
    let undeclared_element =
        |feature: &FeatureName, site: Site, name: &ElementName, errors: &mut Vec<BuildError>| {
            if !elements.contains(name) {
                errors.push(BuildError::Undeclared {
                    feature: feature.clone(),
                    kind: "element",
                    site,
                    name: name.name().clone(),
                    roster: element_roster.clone(),
                });
            }
        };
    // Every source-side element name with the feature that first declared it,
    // so a presentation element reusing such a name names both owners.
    let mut source_owners: BTreeMap<ElementName, FeatureName> = BTreeMap::new();
    {
        let mut note = |name: ElementName, owner: &FeatureName| {
            source_owners.entry(name).or_insert_with(|| owner.clone());
        };
        let language_owner = FeatureName::from(crate::lang::mint::LANGUAGE_OWNER);
        for name in structural {
            note(ElementName::from(*name), &language_owner);
        }
        for def in &roster.elements {
            note(def.element.name.clone(), &def.owner);
        }
        for fallback in &roster.fallbacks {
            note(fallback.element.name.clone(), &fallback.owner);
        }
        for package in &roster.scoped_packages {
            for def in &package.elements {
                note(def.element.name.clone(), &def.owner);
            }
        }
    }
    let mut seen_pres: BTreeMap<ElementName, FeatureName> = BTreeMap::new();
    for pres in &roster.presentation {
        let name = &pres.element.name;
        if let Some(first) = seen_pres.get(name) {
            errors.push(BuildError::Duplicate {
                kind: "presentation element",
                name: name.name().clone(),
                first: first.clone(),
                second: pres.owner.clone(),
            });
            continue;
        }
        if let Some(first) = source_owners.get(name) {
            errors.push(BuildError::Duplicate {
                kind: "element",
                name: name.name().clone(),
                first: first.clone(),
                second: pres.owner.clone(),
            });
        }
        seen_pres.insert(name.clone(), pres.owner.clone());
    }
    for attachment in &roster.attachments {
        undeclared_element(
            &attachment.owner,
            Site::Attachment { aspect: attachment.aspect_name },
            &attachment.element,
            &mut errors,
        );
    }

    // --- argument roles ----------------------------------------------------------------
    // A role name is declared once in its namespace. A role set on an argument
    // must be declared by some feature, or declared as a peer by the feature
    // whose declaration holds the argument: the rule every other namespace
    // follows for a reference to another feature's entity.
    let mut role_owners: BTreeMap<&Name, &FeatureName> = BTreeMap::new();
    for (owner, def) in &roster.argument_roles {
        if let Some(first) = role_owners.get(&def.name) {
            errors.push(BuildError::Duplicate {
                kind: "argument role",
                name: def.name.clone(),
                first: (*first).clone(),
                second: owner.clone(),
            });
            continue;
        }
        role_owners.insert(&def.name, owner);
    }
    let peer_roles: BTreeSet<(&FeatureName, &Name)> =
        roster.peer_argument_roles.iter().map(|record| (&record.owner, &record.name)).collect();
    let role_roster: Vec<Name> = role_owners.keys().map(|name| (*name).clone()).collect();
    let mut arguments = Vec::new();
    for def in &roster.elements {
        arguments_of(def, None, &mut arguments);
    }
    for package in &roster.scoped_packages {
        for def in &package.elements {
            arguments_of(def, Some(package), &mut arguments);
        }
    }
    for argument in &arguments {
        let Some(role) = &argument.arg.role else { continue };
        let owner = &argument.declaration.owner;
        if role_owners.contains_key(role) || peer_roles.contains(&(owner, role)) {
            continue;
        }
        errors.push(BuildError::UndeclaredArgumentRole {
            feature: owner.clone(),
            place: Box::new(ArgumentPlace {
                command: written_command(argument.declaration),
                field: argument.field.map(|field| field.name.clone()),
                argument: argument.arg.name.clone(),
                index: argument.index,
            }),
            role: role.clone(),
            roster: role_roster.clone(),
        });
    }

    // --- collections' members -------------------------------------------------------
    // A member of a collection no feature declares was already dropped by the
    // build module's `drop_members_of_undeclared_collections`; what remains is
    // checked for its capability.
    for (owner, collection, member) in &roster.members {
        undeclared_cap(
            owner,
            Site::CollectionMember { collection: collection.clone(), member: member.clone() },
            member,
            &mut errors,
        );
    }

    // --- stages ---------------------------------------------------------------------
    let mut stage_owners: BTreeMap<Name, FeatureName> = BTreeMap::new();
    for record in &roster.stages {
        let decl = &record.decl;
        if let Some(first) = stage_owners.get(decl.name.name()) {
            errors.push(BuildError::Duplicate {
                kind: "stage",
                name: decl.name.name().clone(),
                first: first.clone(),
                second: record.owner.clone(),
            });
            continue;
        }
        stage_owners.insert(decl.name.name().clone(), record.owner.clone());
        for capability in &decl.provides {
            if is_collection(capability) {
                errors.push(BuildError::CollectionAsCapability {
                    stage: decl.name.clone(),
                    site: Site::StageProvides { stage: decl.name.clone() },
                    collection: capability.clone(),
                });
                continue;
            }
            undeclared_cap(
                &record.owner,
                Site::StageProvides { stage: decl.name.clone() },
                capability,
                &mut errors,
            );
        }
        for table in &decl.writes {
            if decl.effect == Effect::Check {
                errors.push(BuildError::CheckWrites {
                    stage: decl.name.clone(),
                    table: table.name.clone(),
                });
            }
            if check_table(
                &record.owner,
                Site::StageWrites { stage: decl.name.clone() },
                table,
                &mut errors,
            ) {
                if let Some((_, _, true)) = tables.get(&table.name) {
                    errors.push(BuildError::ExternalTableWritten {
                        stage: decl.name.clone(),
                        table: table.name.clone(),
                    });
                }
            }
        }
    }
    let stage_roster: Vec<Name> = stage_owners.keys().cloned().collect();
    for (owner, ordering) in &roster.orderings {
        if !stage_owners.contains_key(ordering.stage.name()) {
            errors.push(BuildError::Undeclared {
                feature: owner.clone(),
                kind: "stage",
                site: Site::OrderingEdges,
                name: ordering.stage.name().clone(),
                roster: stage_roster.clone(),
            });
        }
        for capability in ordering.after.iter().chain(&ordering.before) {
            undeclared_cap(
                owner,
                Site::OrderingEdge { stage: ordering.stage.clone() },
                capability,
                &mut errors,
            );
        }
    }

    // --- backends ---------------------------------------------------------------------
    let mut backend_owners: BTreeMap<BackendName, FeatureName> = BTreeMap::new();
    for backend in &roster.backends {
        if let Some(first) = backend_owners.get(&backend.name) {
            errors.push(BuildError::Duplicate {
                kind: "backend",
                name: backend.name.name().clone(),
                first: first.clone(),
                second: backend.owner.clone(),
            });
            continue;
        }
        backend_owners.insert(backend.name.clone(), backend.owner.clone());
        for element in &backend.native {
            undeclared_element(
                &backend.owner,
                Site::BackendNative { backend: backend.name.clone() },
                element,
                &mut errors,
            );
        }
    }
    let backend_roster: Vec<Name> = backend_owners.keys().map(|name| name.name().clone()).collect();

    // --- native-set implications ------------------------------------------------------
    for (owner, implication) in &roster.native_implications {
        undeclared_element(owner, Site::NativeImplication, &implication.must_claim, &mut errors);
    }

    // --- peer declarations ------------------------------------------------------------
    // A declaration counts for its own feature alone, so the namespace is keyed by
    // (feature, name): one feature declaring a name twice under two signatures is a
    // duplicate, as in every other namespace (an identical repeat was merged by
    // `merge_repeated_peers`); two features each declaring the same name are not. A
    // rule's reference to a name its own feature declared is left to `resolve_peers`.
    let mut peer_backends: BTreeSet<(&FeatureName, &BackendName)> = BTreeSet::new();
    for record in &roster.peer_backends {
        if !peer_backends.insert((&record.owner, &record.name)) {
            errors.push(BuildError::Duplicate {
                kind: "peer backend",
                name: record.name.name().clone(),
                first: record.owner.clone(),
                second: record.owner.clone(),
            });
        }
    }
    let mut peer_elements: BTreeSet<(&FeatureName, &ElementName)> = BTreeSet::new();
    for record in &roster.peer_elements {
        if !peer_elements.insert((&record.owner, &record.name)) {
            errors.push(BuildError::Duplicate {
                kind: "peer element",
                name: record.name.name().clone(),
                first: record.owner.clone(),
                second: record.owner.clone(),
            });
        }
    }
    let mut peer_tables: BTreeSet<(&FeatureName, &CapName)> = BTreeSet::new();
    for record in &roster.peer_tables {
        if !peer_tables.insert((&record.owner, &record.name)) {
            errors.push(BuildError::Duplicate {
                kind: "peer table",
                name: record.name.name().clone(),
                first: record.owner.clone(),
                second: record.owner.clone(),
            });
        }
    }
    let mut peer_packages: BTreeSet<(&FeatureName, &Name)> = BTreeSet::new();
    for record in &roster.peer_scoped_packages {
        if !peer_packages.insert((&record.owner, &record.name)) {
            errors.push(BuildError::Duplicate {
                kind: "peer scoped package",
                name: record.name.clone(),
                first: record.owner.clone(),
                second: record.owner.clone(),
            });
        }
    }

    // --- rules ----------------------------------------------------------------------
    let mut rule_owners: BTreeMap<RuleName, FeatureName> = BTreeMap::new();
    let mut general_defaults: BTreeMap<ElementName, RuleName> = BTreeMap::new();
    let mut specific_defaults: BTreeMap<(ElementName, BackendName), RuleName> = BTreeMap::new();
    for (owner, rule) in &roster.rules {
        if let Some(first) = rule_owners.get(&rule.name) {
            errors.push(BuildError::Duplicate {
                kind: "lowering rule",
                name: rule.name.name().clone(),
                first: first.clone(),
                second: owner.clone(),
            });
            continue;
        }
        rule_owners.insert(rule.name.clone(), owner.clone());
        undeclared_element(
            owner,
            Site::RuleLowers { rule: rule.name.clone() },
            &rule.element,
            &mut errors,
        );
        for produced in &rule.decl.produces {
            if peer_elements.contains(&(owner, produced)) {
                continue;
            }
            undeclared_element(
                owner,
                Site::RuleProduces { rule: rule.name.clone() },
                produced,
                &mut errors,
            );
        }
        for capability in &rule.decl.requires {
            undeclared_cap(
                owner,
                Site::RuleRequires { rule: rule.name.clone() },
                capability,
                &mut errors,
            );
        }
        // Every table a rule reads is checked, set aside or not: a table this
        // registry declares must hold what the rule expects, and a table it
        // does not declare must be a peer declaration of the rule's own
        // feature — which is how a rule reads another feature's table in a
        // registry that does not hold that feature. Anything else is a
        // misspelled name, reported here.
        for table in rule.decl.reads.iter().chain(&rule.decl.reads_opt) {
            if peer_tables.contains(&(owner, &table.name)) && !tables.contains_key(&table.name) {
                continue;
            }
            check_table(owner, Site::RuleReads { rule: rule.name.clone() }, table, &mut errors);
        }
        match &rule.default {
            crate::core::lowering::DefaultMark::Everywhere => {
                if let Some(first) = general_defaults.get(&rule.element) {
                    errors.push(BuildError::TwoDefaultRules {
                        element: rule.element.clone(),
                        backend: None,
                        first: first.clone(),
                        second: rule.name.clone(),
                    });
                } else {
                    general_defaults.insert(rule.element.clone(), rule.name.clone());
                }
            }
            crate::core::lowering::DefaultMark::OnBackends(backends) => {
                for backend in backends {
                    if !backend_owners.contains_key(backend)
                        && !peer_backends.contains(&(owner, backend))
                    {
                        errors.push(BuildError::Undeclared {
                            feature: owner.clone(),
                            kind: "backend",
                            site: Site::RuleDefaultMark { rule: rule.name.clone() },
                            name: backend.name().clone(),
                            roster: backend_roster.clone(),
                        });
                        continue;
                    }
                    let key = (rule.element.clone(), backend.clone());
                    if let Some(first) = specific_defaults.get(&key) {
                        errors.push(BuildError::TwoDefaultRules {
                            element: rule.element.clone(),
                            backend: Some(backend.clone()),
                            first: first.clone(),
                            second: rule.name.clone(),
                        });
                    } else {
                        specific_defaults.insert(key, rule.name.clone());
                    }
                }
            }
            crate::core::lowering::DefaultMark::Never => {}
        }
    }
    let rule_roster: Vec<Name> = rule_owners.keys().map(|name| name.name().clone()).collect();

    // --- outputs ----------------------------------------------------------------------
    let refines_or_is = |capability: &CapName, table: &CapName| -> bool {
        let mut current = capability.clone();
        let mut seen: BTreeSet<CapName> = BTreeSet::new();
        loop {
            if &current == table {
                return true;
            }
            if !seen.insert(current.clone()) {
                return false;
            }
            match caps.get(&current).and_then(|info| info.refines.clone()) {
                Some(parent) => current = parent,
                None => return false,
            }
        }
    };
    let mut output_owners: BTreeMap<Name, FeatureName> = BTreeMap::new();
    for (owner, output) in &roster.outputs {
        if let Some(first) = output_owners.get(output.name.name()) {
            errors.push(BuildError::Duplicate {
                kind: "output",
                name: output.name.name().clone(),
                first: first.clone(),
                second: owner.clone(),
            });
            continue;
        }
        output_owners.insert(output.name.name().clone(), owner.clone());
        undeclared_cap(
            owner,
            Site::OutputCapability { output: output.name.clone() },
            &output.capability,
            &mut errors,
        );
        match tables.get(&output.table) {
            None => errors.push(BuildError::Undeclared {
                feature: owner.clone(),
                kind: "table",
                site: Site::OutputTable { output: output.name.clone() },
                name: output.table.name().clone(),
                roster: table_roster.clone(),
            }),
            Some((_, declared, _)) => {
                if declared.type_id != TypeId::of::<ArtifactSet>() {
                    errors.push(BuildError::OutputTableNotArtifactSet {
                        output: output.name.clone(),
                        table: output.table.clone(),
                        ty: declared.short_type_name(),
                    });
                }
                if is_cap(&output.capability) && !refines_or_is(&output.capability, &output.table) {
                    errors.push(BuildError::OutputCapabilityMismatch {
                        output: output.name.clone(),
                        capability: output.capability.clone(),
                        table: output.table.clone(),
                    });
                }
            }
        }
    }
    let output_roster: Vec<Name> = output_owners.keys().cloned().collect();
    for (owner, output) in &roster.outputs {
        for source in &output.made_from {
            if !output_owners.contains_key(source.name()) {
                errors.push(BuildError::Undeclared {
                    feature: owner.clone(),
                    kind: "output",
                    site: Site::OutputMadeFrom { output: output.name.clone() },
                    name: source.name().clone(),
                    roster: output_roster.clone(),
                });
            }
        }
    }

    // --- the parts of style and script definitions taken from a table -----------------
    let styles = roster.styles.iter().map(|(_, def)| ("style", &def.id, &def.content));
    let scripts = roster.scripts.iter().map(|(_, def)| ("script", &def.id, &def.content));
    for (kind, definition, content) in styles.chain(scripts) {
        for part in content {
            let DefContent::Table(table) = part else { continue };
            let found = match tables.get(table) {
                None => None,
                Some((_, declared, _)) if declared.type_id == TypeId::of::<DefinitionText>() => continue,
                Some((_, declared, _)) => Some(declared.short_type_name()),
            };
            errors.push(BuildError::DefinitionPartTable {
                kind,
                definition: definition.clone(),
                table: table.clone(),
                found,
            });
        }
    }

    // --- options ----------------------------------------------------------------------
    let mut option_decls: BTreeMap<OptionKey, &crate::model::options::OptionDecl> = BTreeMap::new();
    for decl in &roster.options {
        if let Some(first) = option_decls.get(&decl.key) {
            errors.push(BuildError::Duplicate {
                kind: "option type",
                name: Name::from(decl.key.short_name()),
                first: first.owner.clone(),
                second: decl.owner.clone(),
            });
            continue;
        }
        option_decls.insert(decl.key.clone(), decl);
    }
    let option_roster: Vec<OptionKey> = option_decls.keys().cloned().collect();

    // --- workflows --------------------------------------------------------------------
    let mut workflows: BTreeMap<WorkflowName, (FeatureName, Option<WorkflowName>)> =
        BTreeMap::new();
    for (owner, workflow) in &roster.workflows {
        if let Some((first, _)) = workflows.get(&workflow.name) {
            errors.push(BuildError::Duplicate {
                kind: "workflow",
                name: workflow.name.name().clone(),
                first: first.clone(),
                second: owner.clone(),
            });
            continue;
        }
        workflows.insert(workflow.name.clone(), (owner.clone(), workflow.extends.clone()));
    }
    let workflow_roster: Vec<Name> = workflows.keys().map(|name| name.name().clone()).collect();
    for (owner, workflow) in &roster.workflows {
        if let Some(parent) = &workflow.extends {
            if !workflows.contains_key(parent) {
                errors.push(BuildError::Undeclared {
                    feature: owner.clone(),
                    kind: "workflow",
                    site: Site::WorkflowExtends { workflow: workflow.name.clone() },
                    name: parent.name().clone(),
                    roster: workflow_roster.clone(),
                });
            }
        }
        for output in &workflow.outputs {
            if !output_owners.contains_key(output.name()) {
                errors.push(BuildError::Undeclared {
                    feature: owner.clone(),
                    kind: "output",
                    site: Site::WorkflowOutputs { workflow: workflow.name.clone() },
                    name: output.name().clone(),
                    roster: output_roster.clone(),
                });
            }
        }
        for demand in &workflow.demands {
            if !caps.contains_key(demand) {
                errors.push(BuildError::Undeclared {
                    feature: owner.clone(),
                    kind: "capability",
                    site: Site::WorkflowDemands { workflow: workflow.name.clone() },
                    name: demand.name().clone(),
                    roster: cap_roster.iter().chain(&collection_roster).cloned().collect(),
                });
            }
        }
        for stage in &workflow.prefer {
            if !stage_owners.contains_key(stage.name()) {
                errors.push(BuildError::Undeclared {
                    feature: owner.clone(),
                    kind: "stage",
                    site: Site::WorkflowPrefers { workflow: workflow.name.clone() },
                    name: stage.name().clone(),
                    roster: stage_roster.clone(),
                });
            }
        }
        for (backend, selection) in &workflow.lowering {
            if !backend_owners.contains_key(backend) {
                errors.push(BuildError::Undeclared {
                    feature: owner.clone(),
                    kind: "backend",
                    site: Site::WorkflowLoweringSelection { workflow: workflow.name.clone() },
                    name: backend.name().clone(),
                    roster: backend_roster.clone(),
                });
            }
            for rule in &selection.prefer {
                if !rule_owners.contains_key(rule) {
                    errors.push(BuildError::Undeclared {
                        feature: owner.clone(),
                        kind: "lowering rule",
                        site: Site::WorkflowLoweringPreference { workflow: workflow.name.clone() },
                        name: rule.name().clone(),
                        roster: rule_roster.clone(),
                    });
                }
            }
        }
        for (backend, holes) in &workflow.unsupported {
            if !backend_owners.contains_key(backend) {
                errors.push(BuildError::Undeclared {
                    feature: owner.clone(),
                    kind: "backend",
                    site: Site::WorkflowUnsupported { workflow: workflow.name.clone() },
                    name: backend.name().clone(),
                    roster: backend_roster.clone(),
                });
            }
            for element in holes {
                undeclared_element(
                    owner,
                    Site::WorkflowUnsupported { workflow: workflow.name.clone() },
                    element,
                    &mut errors,
                );
            }
        }
        for error in crate::model::options::validate_values(
            &workflow.render_options,
            BindSite::Render,
            |key| option_decls.get(key).copied(),
            &option_roster,
            Some(&workflow.name),
        ) {
            errors.push(BuildError::Feature { feature: owner.clone(), detail: error.to_string() });
        }
    }
    let mut extends_cycles: BTreeSet<Vec<WorkflowName>> = BTreeSet::new();
    for name in workflows.keys() {
        let mut chain = vec![name.clone()];
        let mut seen: BTreeSet<WorkflowName> = BTreeSet::new();
        seen.insert(name.clone());
        let mut current = name.clone();
        while let Some(Some(parent)) = workflows.get(&current).map(|(_, parent)| parent.clone()) {
            if !workflows.contains_key(&parent) {
                break;
            }
            if !seen.insert(parent.clone()) {
                extends_cycles.insert(canonical_cycle(&chain, &parent));
                break;
            }
            chain.push(parent.clone());
            current = parent;
        }
    }
    for cycle in extends_cycles {
        errors.push(BuildError::ExtendsCycle { cycle });
    }

    errors
}

/// The check that every backend's native set satisfies every declared
/// [native-set implication](crate::core::registry::NativeImplication).
///
/// It runs after the aspects that features attach to other features'
/// elements have been merged into the element values, so that an aspect one
/// feature attaches to another feature's element counts; `structural` holds
/// the structural elements with their merged aspects.
///
/// For each backend and each implication, both in declaration order: nothing
/// is reported when the backend's native set holds the required element;
/// otherwise one [`BuildError::NativeSetIncomplete`] is reported if the
/// implication applies to every backend, or if any element of the backend's
/// native set carries the implication's aspect, and the first such element in
/// the native set's declared order is given as the reason. A native element
/// name that several element values share makes the implication apply if any
/// of those values carries the aspect. An implication whose required element
/// no feature declares is skipped here: [`validate`] has already reported it
/// once as [`BuildError::Undeclared`], and no backend could hold the element
/// anyway.
pub(crate) fn native_implications(
    roster: &Roster,
    structural: &StructuralElements,
) -> Vec<BuildError> {
    if roster.native_implications.is_empty() {
        return Vec::new();
    }
    // The element values, under their names, from the same five sources in the
    // same order as `element_declarations` above, which gathers the names: a
    // source of element values added to one must be added to the other, and the
    // key set of this map is exactly the set `declared_elements` returns.
    let mut specs: BTreeMap<ElementName, Vec<&ElementSpec>> = BTreeMap::new();
    for element in structural.all() {
        specs.entry(element.name.clone()).or_default().push(element);
    }
    for def in &roster.elements {
        specs.entry(def.element.name.clone()).or_default().push(&def.element);
    }
    for package in &roster.scoped_packages {
        for def in &package.elements {
            specs.entry(def.element.name.clone()).or_default().push(&def.element);
        }
    }
    for fallback in &roster.fallbacks {
        specs.entry(fallback.element.name.clone()).or_default().push(&fallback.element);
    }
    for pres in &roster.presentation {
        specs.entry(pres.element.name.clone()).or_default().push(&pres.element);
    }

    let mut errors: Vec<BuildError> = Vec::new();
    for backend in &roster.backends {
        let claimed: BTreeSet<&ElementName> = backend.native.iter().collect();
        for (_, implication) in &roster.native_implications {
            if claimed.contains(&implication.must_claim) {
                continue;
            }
            if !specs.contains_key(&implication.must_claim) {
                continue;
            }
            let because = match implication.kind {
                NativeImplicationKind::Always => None,
                NativeImplicationKind::Aspect { .. } => {
                    let carries = |spec: &&ElementSpec| implication.applies_to(spec);
                    let carrier = backend.native.iter().find(|name| {
                        specs.get(*name).is_some_and(|values| values.iter().any(carries))
                    });
                    match carrier {
                        Some(name) => Some(name.clone()),
                        None => continue,
                    }
                }
            };
            errors.push(BuildError::NativeSetIncomplete {
                backend: backend.name.clone(),
                because,
                must_claim: implication.must_claim.clone(),
            });
        }
    }
    errors
}

/// The result of [`resolve_peers`]: what resolving every peer declaration
/// against the collected declarations found.
pub(crate) struct PeerResolution {
    /// The signature mismatches: one [`BuildError::PeerElementMismatch`] per
    /// peer element declaration whose name is declared with another payload
    /// type or as a source element, and one [`BuildError::PeerTableMismatch`]
    /// per peer table declaration whose name is declared holding another value
    /// type.
    pub errors: Vec<BuildError>,
    /// Every peer declaration that no declaration resolves, in declaration
    /// order: the declaring feature, the name, and the rules of that feature
    /// set aside because they depend on it, in registration order. There is
    /// one entry per feature and name, because identical repeats were merged
    /// and [`validate`] refuses other repeats.
    pub unresolved: Vec<(FeatureName, PeerName, Vec<RuleName>)>,
    /// Every rule set aside, keyed by its name, with the unresolved peer
    /// declarations of its own feature that it depends on, in the order of its
    /// default mark, then its `produces`, then its `reads`.
    pub set_aside: BTreeMap<RuleName, Vec<PeerName>>,
    /// Every stage set aside, keyed by its name: a stage that writes a table
    /// that its own feature declared as a peer and that stays unresolved. Each
    /// comes with the feature that registered it and the unresolved peer
    /// tables it writes, in the order of its declaration. A stage set aside is
    /// not registered.
    pub set_aside_stages: BTreeMap<StageName, (FeatureName, Vec<PeerName>)>,
}

/// Resolves every [peer declaration](crate::core::registry::PeerName) of the
/// collected declarations `roster` against what the features declared, with
/// `structural` giving the names of the language's structural elements.
///
/// A peer backend resolves when some feature registers a backend of that name.
/// A peer element resolves when some feature registers a presentation element
/// of that name whose payload type is the one the declaration gives; a
/// presentation element of another payload type, or a source element of that
/// name, is a mismatch reported as an error. A peer table resolves when some
/// feature declares a table of that name holding the value type the
/// declaration gives; one holding another type is a mismatch reported as an
/// error. A peer scoped package resolves when some feature declares a scoped
/// package of that name, and a peer argument role when some feature declares
/// an argument role of that name.
///
/// A name that resolves to nothing is unresolved, and every rule of the
/// declaring feature that *depends* on it is set aside: a rule whose default
/// mark lists the backend, whose `produces` lists the element, or whose
/// `reads` lists the table. A rule that lists the table only in `reads_opt`
/// is not set aside (it runs and finds the table absent), but the unresolved
/// declaration is still reported.
///
/// A stage of the declaring feature that *writes* an unresolved peer table is
/// set aside too: without the table it has nowhere to write, and the feature
/// that would read the table is absent.
///
/// A declaration counts for its own feature only: [`validate`] reports a rule
/// of another feature that refers to the same undeclared entity like any
/// other undeclared reference. [`merge_repeated_peers`] has merged identical
/// repeats before this function runs, and [`validate`] refuses a repeat with
/// another signature, so this function records one entry per declaration.
pub(crate) fn resolve_peers(roster: &Roster, structural: &[&str]) -> PeerResolution {
    let backends: BTreeSet<&BackendName> = roster.backends.iter().map(|b| &b.name).collect();
    let presentation: BTreeMap<&ElementName, TypeKey> =
        roster.presentation.iter().map(|record| (&record.element.name, record.payload)).collect();
    let table_types: BTreeMap<&CapName, &TableType> =
        roster.tables.iter().map(|record| (&record.def.name, &record.def.ty)).collect();
    let elements = declared_elements(roster, structural);

    let mut errors: Vec<BuildError> = Vec::new();
    let mut unresolved: Vec<(FeatureName, PeerName, Vec<RuleName>)> = Vec::new();
    for record in &roster.peer_backends {
        if !backends.contains(&record.name) {
            unresolved.push((
                record.owner.clone(),
                PeerName::Backend(record.name.clone()),
                Vec::new(),
            ));
        }
    }
    for record in &roster.peer_elements {
        match presentation.get(&record.name) {
            Some(payload) if payload.type_id() == record.payload.type_id() => {}
            Some(payload) => errors.push(BuildError::PeerElementMismatch {
                feature: record.owner.clone(),
                element: record.name.clone(),
                declared: Some(payload.short_name()),
                expected: record.payload.short_name(),
            }),
            None if elements.contains(&record.name) => {
                errors.push(BuildError::PeerElementMismatch {
                    feature: record.owner.clone(),
                    element: record.name.clone(),
                    declared: None,
                    expected: record.payload.short_name(),
                })
            }
            None => unresolved.push((
                record.owner.clone(),
                PeerName::Element(record.name.clone()),
                Vec::new(),
            )),
        }
    }
    for record in &roster.peer_tables {
        match table_types.get(&record.name) {
            Some(declared) if declared.type_id() == record.value.type_id() => {}
            Some(declared) => errors.push(BuildError::PeerTableMismatch {
                feature: record.owner.clone(),
                table: record.name.clone(),
                declared: declared.short_name(),
                expected: record.value.short_name(),
            }),
            None => unresolved.push((
                record.owner.clone(),
                PeerName::Table(record.name.clone()),
                Vec::new(),
            )),
        }
    }
    let packages: BTreeSet<&Name> = roster.scoped_packages.iter().map(|p| &p.name).collect();
    for record in &roster.peer_scoped_packages {
        if !packages.contains(&record.name) {
            unresolved.push((
                record.owner.clone(),
                PeerName::ScopedPackage(record.name.clone()),
                Vec::new(),
            ));
        }
    }
    let roles: BTreeSet<&Name> = roster.argument_roles.iter().map(|(_, def)| &def.name).collect();
    for record in &roster.peer_argument_roles {
        if !roles.contains(&record.name) {
            unresolved.push((
                record.owner.clone(),
                PeerName::ArgumentRole(record.name.clone()),
                Vec::new(),
            ));
        }
    }

    let mut set_aside: BTreeMap<RuleName, Vec<PeerName>> = BTreeMap::new();
    for (owner, rule) in &roster.rules {
        // What the rule depends on: the backend it is the default on, the
        // elements it produces, and the tables it reads as a hard dependency.
        // A table read optionally is deliberately absent — such a rule runs
        // and sees the table as absent.
        let mut refers: Vec<PeerName> = Vec::new();
        if let crate::core::lowering::DefaultMark::OnBackends(backends) = &rule.default {
            refers.extend(backends.iter().cloned().map(PeerName::Backend));
        }
        refers.extend(rule.decl.produces.iter().cloned().map(PeerName::Element));
        refers.extend(rule.decl.reads.iter().map(|table| PeerName::Table(table.name.clone())));
        let mut names: Vec<PeerName> = Vec::new();
        for name in refers {
            let unresolved_here = unresolved
                .iter_mut()
                .find(|(feature, known, _)| feature == owner && *known == name);
            if let Some((_, _, rules)) = unresolved_here {
                if !rules.contains(&rule.name) {
                    rules.push(rule.name.clone());
                }
                if !names.contains(&name) {
                    names.push(name);
                }
            }
        }
        if !names.is_empty() {
            set_aside.insert(rule.name.clone(), names);
        }
    }
    let mut set_aside_stages: BTreeMap<StageName, (FeatureName, Vec<PeerName>)> = BTreeMap::new();
    for record in &roster.stages {
        let names: Vec<PeerName> = record
            .decl
            .writes
            .iter()
            .map(|table| PeerName::Table(table.name.clone()))
            .filter(|name| {
                unresolved.iter().any(|(feature, known, _)| *feature == record.owner && known == name)
            })
            .collect();
        if !names.is_empty() {
            set_aside_stages.insert(record.decl.name.clone(), (record.owner.clone(), names));
        }
    }
    PeerResolution { errors, unresolved, set_aside, set_aside_stages }
}