openusd-build 0.8.0

Generates Rust schema views from OpenUSD schema.usda files, for use as a build dependency
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
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
//! The Rust a schema library is generated as.
//!
//! [`lower`] settles every name a schema implies — what each type and trait is
//! called, which traits a view implements, which accessors it offers — and is
//! the only place that does, so a name is decided once and can be checked for
//! collisions there. [`emitter`] writes the views from that, [`family`] writes
//! the schema data from the declarations beside it, and [`render`] lays the
//! result out as text.
//!
//! The file is written to be included bare into whatever module a consumer
//! chooses, through `openusd::include_schema!`. That is what decides its shape:
//! it carries no `use` block, since one would apply to the module it lands in
//! and could collide with what the consumer already imports, so every path in it
//! is spelled in full.

mod emitter;
mod family;
mod lower;
mod nodes;
mod value;

use proc_macro2::{Ident, Span, TokenStream};

use crate::Views;
use crate::decl;
use crate::model::Library;
use crate::{Externs, TokenEnum, error::Error};

pub use nodes::nodes;

/// One library's generated file, `schema` naming what it came from.
///
/// With [`Views::Skip`] it carries the tokens and the schema data alone, which is
/// what a library asking for `skipCodeGeneration` wants and what a crate whose
/// API is written by hand asks for through
/// [`Builder::schema_data`](crate::Builder::schema_data). The data is not
/// optional either way: it is what a registry is built from, so a file without
/// it would leave the schemas unregisterable.
pub fn emit(
    model: &Library,
    externs: &Externs,
    schema: &str,
    views: Views,
    enums: &[TokenEnum],
) -> Result<String, Error> {
    let lowered = match views {
        Views::Generate => lower::library(model, externs, enums)?,
        Views::Skip => lower::tokens(model, enums)?,
    };
    let declarations = decl::with_family(model, family::declarations)?;
    render(emitter::library(&lowered, &declarations), schema)
}

/// The items the generated file declares at its top level, by name.
///
/// [`emitter`] and [`family`] write them under these names and [`lower`]
/// refuses a schema that would reach one, so the two cannot disagree about what
/// is taken: a name added or renamed here changes both.
pub(super) mod items {
    /// The module holding the token constants.
    pub const TOKENS: &str = "tokens";
    /// The constant naming the library.
    pub const LIBRARY_NAME: &str = "LIBRARY_NAME";
    /// The constant holding the declarations a registry takes.
    pub const SCHEMAS: &str = "SCHEMAS";
    /// The traits reading and writing a library's metadata fields, one per
    /// kind of handle.
    pub const PRIM_METADATA: &str = "PrimMetadata";
    pub const ATTRIBUTE_METADATA: &str = "AttributeMetadata";
    pub const RELATIONSHIP_METADATA: &str = "RelationshipMetadata";
    pub const STAGE_METADATA: &str = "StageMetadata";

    /// All of them, for the collision check.
    pub const ALL: [&str; 7] = [
        TOKENS,
        LIBRARY_NAME,
        SCHEMAS,
        PRIM_METADATA,
        ATTRIBUTE_METADATA,
        RELATIONSHIP_METADATA,
        STAGE_METADATA,
    ];
}

/// A doc comment's text as one `#[doc]` value per line, each opening with the
/// space a `///` comment has after it.
fn doc_lines(text: &str) -> impl Iterator<Item = String> + '_ {
    text.lines().map(|line| format!(" {line}"))
}

/// One generated item, by the name it is written under.
fn ident(name: &str) -> Ident {
    Ident::new(name, Span::call_site())
}

/// A path as a reader writes it, segment by segment.
///
/// `quote!` spaces a path's tokens apart, and documentation needs the spelling
/// a reader would type.
fn path_text(path: &syn::Path) -> String {
    let leading = match path.leading_colon.is_some() {
        true => "::",
        false => "",
    };
    let segments: Vec<String> = path.segments.iter().map(|segment| segment.ident.to_string()).collect();
    format!("{leading}{}", segments.join("::"))
}

/// An item of the module at `home`, as a reader writes it: `home::name`.
fn within(home: &syn::Path, name: &str) -> String {
    format!("{}::{name}", path_text(home))
}

/// The header every generated file opens with, as upstream marks its own.
const GENERATED_BY: &str = "WARNING: THIS FILE IS GENERATED BY openusd-build. DO NOT EDIT.";

/// The tokens as a formatted file, with the header above them.
///
/// Each top-level item is laid out on its own so that a blank line falls
/// between them: `prettyplease` reads a syntax tree, which has no blank lines of
/// its own to keep.
fn render(file: TokenStream, schema: &str) -> Result<String, Error> {
    let parsed: syn::File = syn::parse2(file).map_err(|cause| Error::Malformed {
        schema: schema.to_owned(),
        cause: cause.to_string(),
    })?;
    let items: Vec<String> = parsed
        .items
        .into_iter()
        .map(|item| {
            let one = syn::File {
                shebang: None,
                frontmatter: None,
                attrs: Vec::new(),
                items: vec![item],
            };
            prettyplease::unparse(&one)
        })
        .collect();

    Ok(format!(
        "// {GENERATED_BY}\n// Generated from {schema}.\n\n{}",
        items.join("\n")
    ))
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::path::Path;
    use std::sync::LazyLock;

    use super::*;
    use crate::configure;
    use crate::error::Error;
    use crate::tests::{TAG_API, read_source, schema};
    use crate::validate::Violation;
    use crate::{TokenEnum, TokenEnumError};

    /// A library covering the kinds that emit differently.
    const KINDS: &str = r#"#usda 1.0

def "GLOBAL" (
    customData = {
        string libraryName = "testEmit"
    }
)
{
}

class "Typed" {}

class "APISchemaBase" {}

class "Shape" (
    inherits = </Typed>
) {
    color3f color = (1, 1, 1)
}

class Ball "Ball" (
    inherits = </Shape>
) {
    double radius = 1
}

class "TagAPI" (
    inherits = </APISchemaBase>
    customData = {
        token apiSchemaType = "singleApply"
    }
) {
    string tag = ""
}

class "SlotAPI" (
    inherits = </APISchemaBase>
    customData = {
        token apiSchemaType = "multipleApply"
        token propertyNamespacePrefix = "slot"
    }
) {
    int depth = 0
}
"#;

    /// A library whose accessors exercise the shapes that differ.
    const ACCESSORS: &str = r#"#usda 1.0

def "GLOBAL" (
    customData = {
        string libraryName = "testAccessors"
    }
)
{
}

class "Typed" {}

class "Held" (
    inherits = </Typed>
) {
    double radius = 1 (
        doc = "The radius."
    )
    uniform token mode = "a" (
        allowedTokens = ["a", "b"]
    )
    custom float temp
    rel target
    int hidden (
        customData = {
            string apiName = ""
        }
    )
}
"#;

    /// A library declaring a versioned spelling of a schema root.
    const VERSIONED_ROOT: &str = r#"#usda 1.0

def "GLOBAL" (
    customData = {
        string libraryName = "testRoot"
    }
)
{
}

class "Typed" {}

class "Typed_1" {}
"#;

    /// The body of a view's inherent `impl` block, which is where its
    /// constructors are written.
    fn impl_block<'a>(text: &'a str, name: &str) -> &'a str {
        let opened = format!("impl {name} {{");
        let (_, rest) = text
            .split_once(&opened)
            .unwrap_or_else(|| panic!("{name} has an impl block"));
        let (body, _) = rest
            .split_once(
                "
}",
            )
            .unwrap_or_else(|| panic!("{name}'s impl block ends"));
        body
    }

    /// A library whose documentation points at its own API, the way upstream's
    /// does.
    const REFERENCES: &str = r#"#usda 1.0

def "GLOBAL" (
    customData = {
        string libraryName = "testRefs"
    }
)
{
}

class "Typed" {}

class RefsCrate "RefsCrate" (
    doc = """A TestRefsCrate holds a TestRefsBox.
    See GetWeightAttr(), GetSizeAttr() and TestRefsBox::GetSizeAttr()."""
    inherits = </Typed>
    customData = {
        string className = "Crate"
    }
) {
}

class Tin "Tin" (
    doc = "Another thing with a size."
    inherits = </Typed>
) {
    double size = 1
}

class Box "Box" (
    doc = """A TestRefsBox, which knows its own size.
    \\sa GetSizeAttr()
    \\sa ComputeNothing()"""
    inherits = </Typed>
) {
    double size = 1
    double weight = 1
}
"#;

    /// One schema library's accessors with every space removed, so a generated
    /// chain can be matched as it is written rather than as `prettyplease` laid
    /// it out.
    fn packed_accessors() -> String {
        packed(accessors())
    }

    /// `text` with its whitespace removed, so an assertion reads as the call
    /// chain rather than as the layout `prettyplease` chose for it.
    fn packed(text: &str) -> String {
        text.chars().filter(|c| !c.is_whitespace()).collect()
    }

    /// What one schema library generates.
    fn emitted(source: &str) -> String {
        let dir = tempfile::tempdir().expect("tempdir");
        let model = read_source(dir.path(), source).expect("resolves");
        emit(&model, &Externs::new(), "schema.usda", Views::Generate, &[]).expect("emits")
    }

    /// The kinds fixture, emitted once for the tests that read it.
    fn kinds() -> &'static str {
        static ONCE: LazyLock<String> = LazyLock::new(|| emitted(KINDS));
        &ONCE
    }

    /// The accessors fixture, likewise.
    fn accessors() -> &'static str {
        static ONCE: LazyLock<String> = LazyLock::new(|| emitted(ACCESSORS));
        &ONCE
    }

    /// The references fixture, likewise.
    fn references() -> &'static str {
        static ONCE: LazyLock<String> = LazyLock::new(|| emitted(REFERENCES));
        &ONCE
    }

    /// The values fixture, likewise. It lives as a file because
    /// `tests/values.rs` compiles what it generates.
    fn values() -> &'static str {
        static ONCE: LazyLock<String> = LazyLock::new(|| {
            let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/values");
            let library = configure()
                .search_path(&dir)
                .read(&dir.join("schema.usda"), &[])
                .map(|(library, _)| library)
                .expect("the values fixture resolves");
            emit(&library, &Externs::new(), "schema.usda", Views::Generate, &[]).expect("emits")
        });
        &ONCE
    }

    /// Every value a schema can declare reaches the table, dictionaries and
    /// the matrix types whose `gf` names differ from their variants included.
    /// A value with no literal stops the build, so this passing is what says
    /// the writer covers what a schema can say.
    #[test]
    fn every_value_written() {
        let text = values();
        for expected in [
            // A dictionary, written in key order and holding a value of its own.
            "::openusd::sdf::Dictionary::from(",
            "::openusd::sdf::Value::DoubleVec(",
            // The three matrices, each through the `gf` type that carries it.
            "::openusd::gf::Mat2d([",
            "::openusd::gf::Mat3d([",
            "::openusd::gf::Matrix4d([",
            "::openusd::gf::quath(",
            "::openusd::sdf::TimeCode(",
            "::openusd::gf::f16::from_bits(",
            "::openusd::sdf::AssetPath::new(",
            // A blocked default is a value, not a missing one.
            "::openusd::sdf::Value::ValueBlock",
            // A bare `rel` is uniform and a `varying rel` is not, and each is
            // written as whichever differs from the constructor's own default.
            "::openusd::usd::PropertyDecl::relationship(\"plain\")",
            "::openusd::usd::PropertyDecl::relationship(\"loose\").varying()",
        ] {
            assert!(text.contains(expected), "{expected} is missing from:\n{text}");
        }
    }

    /// Every schema is a view struct under its own name plus the trait its own
    /// accessors live on, abstract and concrete alike, and a view derives from
    /// the trait of each class behind it.
    #[test]
    fn kinds_take_their_shapes() {
        let text = kinds();
        assert!(
            text.contains("pub trait ShapeSchema: ::openusd::usd::Typed {"),
            "{text}"
        );
        assert!(text.contains("pub trait BallSchema: ShapeSchema {"), "{text}");
        assert!(text.contains("pub struct Shape(::openusd::usd::Prim);"), "{text}");
        assert!(text.contains("pub struct Ball(::openusd::usd::Prim);"), "{text}");
        assert!(text.contains("impl BallSchema for Ball {}"), "{text}");
        assert!(text.contains("impl ShapeSchema for Ball {}"), "{text}");
        assert!(text.contains("impl ::openusd::usd::Typed for Shape {}"), "{text}");
    }

    /// An abstract schema names no type a prim can be defined as, so its view
    /// recognises a prim without defining one.
    #[test]
    fn abstract_constructors() {
        let text = kinds();
        assert!(
            text.contains("prim.is_a(tokens::SHAPE)?.then_some(Self(prim))"),
            "{text}"
        );
        assert!(!impl_block(text, "Shape").contains("fn define"), "{text}");
    }

    /// A concrete view is a prim type, so it defines and recognises one.
    #[test]
    fn concrete_constructors() {
        let text = kinds();
        assert!(text.contains("stage.define_typed_prim(path, tokens::BALL)?"), "{text}");
        assert!(
            text.contains("prim.is_a(tokens::BALL)?.then_some(Self(prim))"),
            "{text}"
        );
        // A caller holding a prim asks it directly, and looking one up by path
        // is that question over the prim at the path.
        assert!(text.contains("Self::from_prim(stage.prim(path)?)"), "{text}");
    }

    /// An applied API schema is applied rather than defined, and a
    /// multiple-apply one carries the instance name it was applied under.
    #[test]
    fn applied_constructors() {
        let text = kinds();
        assert!(text.contains("prim.clone().apply_api(tokens::TAG_API)?"), "{text}");
        assert!(
            text.contains("prim.has_api_schema(tokens::TAG_API)?.then_some(Self(prim))"),
            "{text}"
        );
        assert!(text.contains("name: ::openusd::tf::Token,"), "{text}");
        assert!(text.contains("make_applied_name(tokens::SLOT_API"), "{text}");
    }

    /// A multiple-apply schema's properties are templates, so its accessors put
    /// the view's own instance name into one.
    #[test]
    fn instanced_accessors() {
        let text = kinds();
        assert!(
            text.contains("make_multiple_apply_name_instance("),
            "the template is instantiated: {text}"
        );
        assert!(text.contains("tokens::SLOT_MULTIPLE_APPLY_TEMPLATE_DEPTH"), "{text}");
        assert!(text.contains("self.name.as_str()"), "{text}");
    }

    /// A multiple-apply schema reads an instance back out of a property path
    /// of one, which means knowing the names it declares itself.
    #[test]
    fn instances_decode_from_a_path() {
        let text = packed(kinds());
        assert!(
            text.contains(r#"is_schema_property_base_name(base_name:&str)->bool{::std::matches!(base_name,"depth")"#),
            "the names it declares are the ones an instance may not end with: {text}"
        );
        assert!(
            text.contains(r#"property.strip_prefix("slot")?.strip_prefix(':')?"#),
            "an instance is what follows the schema's namespace: {text}"
        );
        // A single-apply schema names its properties without an instance, so
        // there is nothing to read back out of one.
        assert!(!impl_block(kinds(), "TagAPI").contains("instance_at_path"), "{text}");
    }

    /// The file carries no `use` block, every path being spelled in full, since
    /// it is included into a module it knows nothing about.
    #[test]
    fn no_imports() {
        let text = kinds();
        assert!(!text.contains("\nuse "), "{text}");
    }

    /// The schema data is a declaration table, so registering a family reads
    /// no file and parses nothing.
    #[test]
    fn schema_data_is_declared() {
        let text = kinds();
        assert!(text.contains("pub const LIBRARY_NAME: &str = \"testEmit\";"), "{text}");
        assert!(
            text.contains("pub const SCHEMAS: &::openusd::usd::SchemaFamily<'static>"),
            "{text}"
        );
        assert!(text.contains("::openusd::usd::SchemaDecl::new("), "{text}");
        assert!(text.contains("::openusd::usd::SchemaKind::ConcreteTyped"), "{text}");
        assert!(
            text.contains("::openusd::usd::PropertyDecl::attribute(\"radius\", \"double\")"),
            "{text}"
        );
        assert!(!text.contains("include_bytes!"), "{text}");
    }

    /// A reader reaches the property, and the creator declares it with the type
    /// the schema gave it.
    #[test]
    fn attribute_pair() {
        let text = accessors();
        assert!(
            text.contains("fn radius_attr(&self) -> ::openusd::usd::Attribute {"),
            "{text}"
        );
        assert!(text.contains("self.prim().attribute(tokens::RADIUS)"), "{text}");
        assert!(text.contains("::openusd::sdf::ValueTypeName::DOUBLE"), "{text}");
    }

    /// What the schema declared is what the creator authors. Authoring leaves a
    /// property `custom`, so every creator says whether it is one; a uniform
    /// property says that too.
    #[test]
    fn creator_authors_declaration() {
        let text = packed_accessors();
        // The declaration is one builder, so whoever takes it can give it a
        // value and reach the stage in one edit. It says only what the schema
        // declares differently from a bare property.
        assert!(
            text.contains("attribute_builder(tokens::RADIUS,::openusd::sdf::ValueTypeName::DOUBLE).custom(false)}"),
            "a schema's property is not custom, and varies by default: {text}"
        );
        assert!(
            text.contains("attribute_builder(tokens::MODE,::openusd::sdf::ValueTypeName::TOKEN).custom(false).variability(::openusd::sdf::Variability::Uniform)}"),
            "a uniform property says so: {text}"
        );
        assert!(
            text.contains("attribute_builder(tokens::TEMP,::openusd::sdf::ValueTypeName::FLOAT)}"),
            "a `custom` property takes the defaults: {text}"
        );
        assert!(
            text.contains("::std::result::Result::Ok(self.radius_attr_builder().build()?)"),
            "the creator is that declaration, authored: {text}"
        );
    }

    /// A relationship reads as a relationship, not as an attribute.
    #[test]
    fn relationship_pair() {
        let text = accessors();
        assert!(
            text.contains("fn target_rel(&self) -> ::openusd::usd::Relationship {"),
            "{text}"
        );
        assert!(
            packed_accessors().contains("relationship_builder(tokens::TARGET).custom(false)}"),
            "{text}"
        );
        assert!(
            packed_accessors().contains("::std::result::Result::Ok(self.target_rel_builder().build()?)"),
            "{text}"
        );
    }

    /// A library whose token properties an enum can be sourced from.
    const TOKEN_ENUMS: &str = r#"#usda 1.0

def "GLOBAL" (
    customData = {
        string libraryName = "testTokenEnums"
    }
)
{
}

class "Typed" {}

class "Held" (
    inherits = </Typed>
) {
    uniform token mode = "a" (
        allowedTokens = ["a", "b"]
        doc = "Which way it runs."
    )

    uniform token axis = "X" (
        allowedTokens = ["X", "Y", "Z"]
    )

    uniform token style (
        allowedTokens = ["", "plain"]
    )

    uniform token phase (
        allowedTokens = ["start", "end"]
    )

    uniform token outcome = "ok" (
        allowedTokens = ["ok", "error"]
    )

    double radius = 1
}
"#;

    /// Generates the library above with `enums` configured, or says why it
    /// would not.
    fn with_enums(enums: Vec<TokenEnum>) -> Result<String, Error> {
        let dir = tempfile::tempdir().expect("tempdir");
        let model = read_source(dir.path(), TOKEN_ENUMS).expect("the schema reads");
        emit(&model, &Externs::new(), "schema.usda", Views::Generate, &enums)
    }

    /// What a configured enum generates: a variant per allowed token, defined
    /// in terms of the constants rather than repeating their strings.
    #[test]
    fn token_enum_over_allowed_tokens() {
        let text = with_enums(vec![TokenEnum::new("Mode", "testTokenEnums", "Held.mode")]).expect("generates");

        assert!(text.contains("pub enum Mode {"), "{text}");
        assert!(text.contains("A,"), "{text}");
        assert!(text.contains("B,"), "{text}");
        assert!(text.contains("Self::A => tokens::A"), "{text}");
        assert!(
            text.contains("tokens::A => ::std::option::Option::Some(Self::A)"),
            "{text}"
        );
        // Nothing is derived for the other token properties, which no
        // configuration named.
        assert!(!text.contains("pub enum Axis"), "{text}");
        assert!(!text.contains("pub enum Style"), "{text}");
    }

    /// A token set carries no default, so one is generated only where the
    /// configuration asked for the source property's fallback.
    #[test]
    fn default_is_opt_in() {
        let plain = with_enums(vec![TokenEnum::new("Mode", "testTokenEnums", "Held.mode")]).expect("generates");
        assert!(!plain.contains("::std::default::Default"), "{plain}");
        assert!(!plain.contains("#[default]"), "{plain}");

        let defaulted = with_enums(vec![
            TokenEnum::new("Mode", "testTokenEnums", "Held.mode").with_default(),
        ])
        .expect("generates");
        assert!(defaulted.contains("::std::default::Default"), "{defaulted}");
        assert!(defaulted.contains("#[default]"), "{defaulted}");
    }

    /// Asking for a default from a property that declares no fallback stops
    /// generation rather than inventing one.
    #[test]
    fn default_without_fallback_rejected() {
        let error = with_enums(vec![
            TokenEnum::new("Phase", "testTokenEnums", "Held.phase").with_default(),
        ])
        .expect_err("phase declares no fallback");

        assert!(
            matches!(
                error,
                Error::TokenEnum {
                    cause: TokenEnumError::NoFallback { .. },
                    ..
                }
            ),
            "{error}"
        );
    }

    /// A token Rust has no name for is named by the caller or not at all.
    #[test]
    fn unnameable_token_rejected() {
        let error =
            with_enums(vec![TokenEnum::new("Style", "testTokenEnums", "Held.style")]).expect_err("`\"\"` has no name");
        assert!(
            matches!(
                error,
                Error::TokenEnum {
                    cause: TokenEnumError::UnnameableToken { .. },
                    ..
                }
            ),
            "{error}"
        );

        let text = with_enums(vec![
            TokenEnum::new("Style", "testTokenEnums", "Held.style").variant("", "Unset"),
        ])
        .expect("generates with the name the caller gave");
        assert!(text.contains("Unset"), "{text}");
    }

    /// Reading and authoring an enum as a value is the core's own macro, so an
    /// enum written here and one written by hand convert alike. What the macro
    /// expands to is `openusd`'s to test, including the token spelled `error`
    /// that gives an enum an `Error` variant.
    #[test]
    fn conversions_come_from_the_core() {
        let text = with_enums(vec![TokenEnum::new("Outcome", "testTokenEnums", "Held.outcome")]).expect("generates");

        assert!(text.contains("Error,"), "the token is still a variant: {text}");
        assert!(text.contains("::openusd::sdf::impl_token_value!(Outcome);"), "{text}");
        assert!(!text.contains("impl ::std::convert::TryFrom"), "{text}");
    }

    /// The generated file declares a token module, a library name and a
    /// declaration table of its own, so an enum may not take one of those
    /// names: the file would carry two items under it, and the consumer's
    /// build would be the first to say so.
    #[test]
    fn reserved_name_rejected() {
        for name in items::ALL {
            let error = with_enums(vec![TokenEnum::new(name, "testTokenEnums", "Held.mode")]).expect_err(name);
            assert!(
                matches!(
                    error,
                    Error::TokenEnum {
                        cause: TokenEnumError::ReservedName,
                        ..
                    }
                ),
                "{name}: {error}"
            );
        }
    }

    /// Configuration that names nothing the schema declares stops generation,
    /// saying which part of it could not be found.
    #[test]
    fn unknown_source_rejected() {
        for (source, expected) in [
            ("Nope.mode", "class `Nope`"),
            ("Held.nope", "`Held.nope`"),
            ("Held.radius", "allowedTokens"),
            ("Held", "Class.property"),
        ] {
            let error = with_enums(vec![TokenEnum::new("Mode", "testTokenEnums", source)]).expect_err(source);
            assert!(error.to_string().contains(expected), "{source}: {error}");
        }
    }

    /// An empty `apiName` asks for no accessor, so none is written.
    #[test]
    fn suppressed_has_none() {
        let text = accessors();
        assert!(!text.contains("fn hidden"), "{text}");
    }

    /// An attribute is read by value as the type it is declared with, at the
    /// default time and at a given one.
    #[test]
    fn typed_read_emitted() {
        let text = packed_accessors();
        assert!(
            text.contains(
                "fnradius(&self)->::openusd::Result<::std::option::Option<f64>>{self.radius_attr().get::<f64>()}"
            ),
            "{text}"
        );
        assert!(
            text.contains(
                "fnradius_at(&self,time:impl::std::convert::Into<::std::option::Option<::openusd::usd::TimeCode>>,)->::openusd::Result<::std::option::Option<f64>>{self.radius_attr().get_at::<f64>(time)}"
            ),
            "{text}"
        );
    }

    /// A uniform attribute holds no samples, so it is read at the default time
    /// alone; a relationship holds no value, so it is read by neither.
    #[test]
    fn uniform_read_untimed() {
        let text = packed_accessors();
        assert!(
            text.contains("fnmode(&self)->::openusd::Result<::std::option::Option<::openusd::tf::Token>>"),
            "{text}"
        );
        assert!(!text.contains("fnmode_at("), "{text}");
        assert!(!text.contains("fntarget(") && !text.contains("fntarget_at("), "{text}");
    }

    /// A property whose value read would take a name every view already has
    /// from `usd::SchemaBase` gets none, the view's own method keeping the
    /// name; its attribute still reads it.
    #[test]
    fn root_method_kept() {
        let text = packed(&emitted(&schema(
            "testRoot",
            r#"class "Thing" (
    inherits = </Typed>
) {
    string path = ""
}"#,
        )));
        assert!(!text.contains("fnpath(") && !text.contains("fnpath_at("), "{text}");
        assert!(text.contains("fnpath_attr(&self)"), "{text}");
    }

    /// An applied API schema's accessors land on its view beside the
    /// constructors, so a property whose value read would be called `get`
    /// gets none, and the constructor keeps the name.
    #[test]
    fn constructor_name_kept() {
        let text = packed(&emitted(&schema(
            "testCtor",
            r#"class "GetAPI" (
    inherits = </APISchemaBase>
    customData = { token apiSchemaType = "singleApply" }
) {
    string get = ""
}"#,
        )));
        assert_eq!(text.matches("pubfnget(").count(), 1, "the constructor alone: {text}");
        assert!(!text.contains("fnget_at("), "{text}");
        assert!(text.contains("fnget_attr(&self)"), "{text}");
    }

    /// A typed read named by a Rust keyword takes a trailing underscore.
    #[test]
    fn keyword_read_escaped() {
        let text = emitted(&schema(
            "testKeyword",
            r#"class "Thing" (
    inherits = </Typed>
) {
    token type = "a"
}"#,
        ));
        let text = packed(&text);
        assert!(text.contains("fntype_(&self)"), "{text}");
        assert!(text.contains("fntype_at(&self"), "{text}");
        assert!(text.contains("fntype_attr(&self)"), "{text}");
    }

    /// The documentation says what the property is, beyond what the schema
    /// wrote about it, and the declaration is the one `sdf` would write.
    #[test]
    fn documents_the_declaration() {
        let text = accessors();
        assert!(text.contains("The radius."), "{text}");
        assert!(text.contains("Declared `double radius = 1.0`."), "{text}");
        assert!(
            text.contains("Declared `uniform token mode = \"a\"`. One of `a`, `b`."),
            "{text}"
        );
    }

    /// Two token identifiers can reach one Rust constant, which upstream does
    /// on purpose where a schema and a property share a name. The library
    /// declares the pair happily, and the second constant takes an underscore.
    #[test]
    fn two_ids_one_constant() {
        let dir = tempfile::tempdir().expect("tempdir");
        let library = read_source(
            dir.path(),
            r#"#usda 1.0

def "GLOBAL" (
    customData = {
        string libraryName = "testConstants"
        dictionary libraryTokens = {
            dictionary drawMode = {
                string value = "a"
            }
            dictionary draw_mode = {
                string value = "b"
            }
        }
    }
)
{
}

class "Typed" {}
"#,
        )
        .expect("the library itself is well formed");

        let text = emit(&library, &Externs::new(), "schema.usda", Views::Generate, &[]).expect("both are named");
        // `draw_mode` sorts before `drawMode`, so it is the one that keeps the
        // name; both say which string they hold.
        assert!(text.contains("pub const DRAW_MODE: &str = \"b\";"), "{text}");
        assert!(text.contains("pub const DRAW_MODE_: &str = \"a\";"), "{text}");
    }

    /// Two properties of one class can ask for one accessor name, and Rust has
    /// no way to hold both.
    #[test]
    fn two_properties_one_method() {
        let dir = tempfile::tempdir().expect("tempdir");
        let library = read_source(
            dir.path(),
            r#"#usda 1.0

def "GLOBAL" (
    customData = {
        string libraryName = "testMethods"
    }
)
{
}

class "Typed" {}

class "Held" (
    inherits = </Typed>
) {
    int one (
        customData = {
            string apiName = "same"
        }
    )
    int two (
        customData = {
            string apiName = "same"
        }
    )
}
"#,
        )
        .expect("the library itself is well formed");

        match emit(&library, &Externs::new(), "schema.usda", Views::Generate, &[]) {
            Err(Error::Definition {
                violation: Violation::MethodCollision { method, .. },
                ..
            }) => assert_eq!(method, "same_attr"),
            other => panic!("{:?}", other.map(|_| "emitted")),
        }
    }

    /// A schema may call its class anything USD admits, including a word Rust
    /// has taken, which is refused where it is named rather than where it is
    /// written out.
    #[test]
    fn keyword_class_name() {
        let dir = tempfile::tempdir().expect("tempdir");
        let library = read_source(
            dir.path(),
            r#"#usda 1.0

def "GLOBAL" (
    customData = {
        string libraryName = "testKeywords"
    }
)
{
}

class "Typed" {}

class "Held" (
    inherits = </Typed>
    customData = {
        string className = "type"
    }
) {
}
"#,
        )
        .expect("the library itself is well formed");

        match emit(&library, &Externs::new(), "schema.usda", Views::Generate, &[]) {
            Err(Error::Definition {
                violation: Violation::NotAnIdentifier { name },
                ..
            }) => assert_eq!(name, "type"),
            other => panic!("{:?}", other.map(|_| "emitted")),
        }
    }

    /// The schema roots are the core's own traits, so a library that declares
    /// one — as the core `usd` library itself does — generates nothing for it.
    #[test]
    fn roots_are_not_generated() {
        let text = kinds();
        assert!(!text.contains("trait Typed"), "{text}");
        assert!(!text.contains("trait APISchemaBase"), "{text}");
        assert!(
            text.contains("::openusd::usd::Typed"),
            "the core's is what a view answers to: {text}"
        );
    }

    /// A reference upstream wrote about its own API reads as a link to
    /// whatever answers for it here; one to something only C++ has keeps the
    /// name it was written with.
    #[test]
    fn references_become_links() {
        let text = references();
        assert!(text.contains("[`size_attr`](BoxSchema::size_attr)"), "{text}");
        assert!(text.contains("[`Box`]"), "{text}");
        assert!(text.contains("`ComputeNothing()`"), "{text}");
    }

    /// Upstream names a class by the class name it declared, not by the
    /// identifier it is registered under, so that is what the C++ spelling is
    /// built from: `RefsCrate` is `TestRefsCrate` there and `Crate` here.
    #[test]
    fn class_name_builds_symbol() {
        let text = references();
        assert!(text.contains("A [`Crate`] holds a [`Box`]."), "{text}");
    }

    /// A name reached from outside the declaring class's chain is answered by
    /// the library, which pairs a name only one class declares. `Crate` is
    /// under neither `Box` nor `Tin`, and both declare a `size`.
    #[test]
    fn library_answers_unique_names() {
        let text = references();
        // The sentence wraps, so it is read whole rather than by line, and to
        // wherever the paragraph it is in ends.
        let at = text.find("See [").expect("the sentence that references them");
        let rest = &text[at..];
        let sentence = rest.split_once("\n    ///\n").map_or(rest, |(paragraph, _)| paragraph);
        assert!(
            sentence.contains("[`weight_attr`](BoxSchema::weight_attr)"),
            "{sentence}"
        );
        assert!(
            sentence.contains("`GetSizeAttr()`"),
            "ambiguous, so left alone: {sentence}"
        );
        assert!(
            sentence.contains("[`size_attr`](BoxSchema::size_attr)"),
            "qualified, so answered: {sentence}"
        );
    }

    /// Rootness is one question with one answer: a versioned spelling names the
    /// same family, so the rule that classifies it and the filter that skips it
    /// reach the same verdict and it is generated no more than `Typed` is.
    #[test]
    fn versioned_root_not_generated() {
        let text = emitted(VERSIONED_ROOT);
        assert!(text.contains("pub const LIBRARY_NAME"), "the library emits: {text}");
        assert!(!text.contains("pub trait"), "{text}");
        assert!(!text.contains("pub struct"), "{text}");
    }

    /// A library sublayering `layers`, each written beside it, with `root` as
    /// its own layer.
    fn stacked(dir: &Path, layers: &[(&str, &str)], root: &str) -> Library {
        for (name, contents) in layers {
            fs::write(dir.join(name), contents).expect("writes a layer");
        }
        read_source(dir, root).expect("resolves")
    }

    /// The root layer of a library called `testHere`: it sublayers `layers` and
    /// declares `classes`.
    fn sublayering(layers: &[&str], classes: &str) -> String {
        let layers: Vec<String> = layers.iter().map(|layer| format!("        @{layer}@")).collect();
        format!(
            r#"#usda 1.0
(
    subLayers = [
{}
    ]
)

def "GLOBAL" (
    customData = {{
        string libraryName = "testHere"
    }}
)
{{
}}

{classes}
"#,
            layers.join(",\n")
        )
    }

    /// A `Crate` whose documentation says `doc`, for what the prose links to.
    fn with_doc(doc: &str) -> String {
        format!(
            r#"class Crate "Crate" (
    inherits = </Typed>
    doc = "{doc}"
) {{
}}"#
        )
    }

    /// A library whose base belongs to another, which is what reaches for the
    /// configured path to that library's views.
    fn inheriting(dir: &Path) -> Library {
        let base = schema(
            "testElsewhere",
            r#"class "Thing" (
    inherits = </Typed>
) {
}"#,
        );
        stacked(
            dir,
            &[("base.usda", base.as_str())],
            &sublayering(
                &["base.usda"],
                r#"class Crate "Crate" (
    inherits = </Thing>
) {
}"#,
            ),
        )
    }

    /// Where a library's views live is read where a base reaches for it, so a
    /// spelling Rust cannot read is reported against the class that reached,
    /// and told apart from a library that was never placed at all.
    #[test]
    fn library_path_must_read() {
        let dir = tempfile::tempdir().expect("tempdir");
        let model = inheriting(dir.path());
        let externs = Externs::from([("testElsewhere".to_owned(), "not a path!".to_owned())]);

        match emit(&model, &externs, "schema.usda", Views::Generate, &[]) {
            Err(Error::Definition {
                violation: Violation::UnreadableLibraryPath { library, path },
                ..
            }) => {
                assert_eq!(library, "testElsewhere");
                assert_eq!(path, "not a path!");
            }
            other => panic!("{:?}", other.map(|_| "emitted")),
        }
    }

    /// A library that was never placed is a different fault, and the one a
    /// caller can fix by placing it.
    #[test]
    fn library_must_be_placed() {
        let dir = tempfile::tempdir().expect("tempdir");
        let model = inheriting(dir.path());

        match emit(&model, &Externs::new(), "schema.usda", Views::Generate, &[]) {
            Err(Error::Definition {
                violation: Violation::UnknownLibrary { library, .. },
                ..
            }) => assert_eq!(library, "testElsewhere"),
            other => panic!("{:?}", other.map(|_| "emitted")),
        }
    }

    /// The configuration names every library a consumer has, whether or not
    /// this one inherits from it, so one this library never reaches for is
    /// none of its business — however it is spelled.
    #[test]
    fn unreached_library_ignored() {
        let dir = tempfile::tempdir().expect("tempdir");
        let model = read_source(dir.path(), KINDS).expect("resolves");
        let externs = Externs::from([("testElsewhere".to_owned(), "not a path!".to_owned())]);

        emit(&model, &externs, "schema.usda", Views::Generate, &[]).expect("emits");
    }

    /// The library `tests/reflect.rs` compiles: it reflects a single-apply
    /// schema another library declares, from a prim type and from an applied
    /// API schema.
    fn reflecting_elsewhere() -> Library {
        let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reflect");
        configure()
            .search_path(&dir)
            .read(&dir.join("schema.usda"), &[])
            .map(|(library, _)| library)
            .expect("the reflect fixture resolves")
    }

    /// A schema another library declares is reflected through the path its
    /// views were placed at: its accessors are emitted here, naming their
    /// properties by this library's constants, and its view is named where it
    /// lives.
    #[test]
    fn reflected_foreign_emitted() {
        let model = reflecting_elsewhere();
        let externs = Externs::from([("testElsewhere".to_owned(), "crate::elsewhere".to_owned())]);

        let rust = emit(&model, &externs, "schema.usda", Views::Generate, &[]).expect("emits");
        assert!(
            rust.contains("fn thing_api(&self) -> crate::elsewhere::ThingAPI"),
            "{rust}"
        );
        assert!(
            rust.contains("crate::elsewhere::ThingAPI::from_prim_unchecked"),
            "{rust}"
        );
        assert!(rust.contains("fn weight_attr(&self)"), "{rust}");
        assert!(rust.contains("fn create_owner_rel(&self)"), "{rust}");
        assert!(rust.contains("tokens::WEIGHT"), "{rust}");
    }

    /// A reflected schema of a library that was never placed is the fault a
    /// caller fixes by placing it, and the schema is named.
    #[test]
    fn reflected_library_unplaced() {
        let model = reflecting_elsewhere();

        match emit(&model, &Externs::new(), "schema.usda", Views::Generate, &[]) {
            Err(Error::Definition {
                violation: Violation::UnknownLibrary { library, class },
                ..
            }) => {
                assert_eq!(library, "testElsewhere");
                assert_eq!(class.as_str(), "ThingAPI");
            }
            other => panic!("{:?}", other.map(|_| "emitted")),
        }
    }

    /// Two reflected schemas declaring one property: the class takes the
    /// first's accessor and leaves the second's out, as upstream does.
    #[test]
    fn reflected_first_wins() {
        let dir = tempfile::tempdir().expect("tempdir");
        let model = read_source(
            dir.path(),
            &schema(
                "testFirst",
                &format!(
                    r#"{TAG_API}

class "LabelAPI" (
    inherits = </APISchemaBase>
    customData = {{ token apiSchemaType = "singleApply" }}
) {{
    string label = ""
    int dup = 0
}}

class "Thing" (
    inherits = </Typed>
    prepend apiSchemas = ["TagAPI", "LabelAPI"]
    customData = {{ token[] reflectedAPISchemas = ["TagAPI", "LabelAPI"] }}
) {{
}}"#
                ),
            ),
        )
        .expect("resolves");

        let rust = emit(&model, &Externs::new(), "schema.usda", Views::Generate, &[]).expect("emits");
        let start = rust
            .find("pub trait ThingSchema")
            .expect("the reflecting class's trait");
        let body = &rust[start..];
        let body = &body[..body.find("\n}\n").expect("the trait ends")];
        assert_eq!(body.matches("fn dup_attr(").count(), 1, "{body}");
        assert!(body.contains("fn tag_attr("), "{body}");
        assert!(body.contains("fn label_attr("), "{body}");
    }

    /// A reflected accessor landing on a name the class already offers is a
    /// collision between the property that has it and the schema reflected.
    #[test]
    fn reflected_own_collides() {
        let dir = tempfile::tempdir().expect("tempdir");
        let model = read_source(
            dir.path(),
            &schema(
                "testCollide",
                &format!(
                    r#"{TAG_API}

class "Thing" (
    inherits = </Typed>
    prepend apiSchemas = ["TagAPI"]
    customData = {{ token[] reflectedAPISchemas = ["TagAPI"] }}
) {{
    string tag = "own"
}}"#
                ),
            ),
        )
        .expect("resolves");

        match emit(&model, &Externs::new(), "schema.usda", Views::Generate, &[]) {
            Err(Error::Definition {
                violation: Violation::MethodCollision { method, first, second },
                ..
            }) => {
                assert_eq!(method, "tag_attr");
                assert_eq!(first.as_str(), "tag");
                assert_eq!(second.as_str(), "TagAPI");
            }
            other => panic!("{:?}", other.map(|_| "emitted")),
        }
    }

    /// A base reflecting `TagAPI`, and a derived class declaring `derived`.
    fn reflecting_base(derived: &str) -> String {
        schema(
            "testAncestor",
            &format!(
                r#"{TAG_API}

class "Base" (
    inherits = </Typed>
    prepend apiSchemas = ["TagAPI"]
    customData = {{ token[] reflectedAPISchemas = ["TagAPI"] }}
) {{
}}

{derived}"#
            ),
        )
    }

    /// The body of the trait `name` in `rust`.
    fn trait_body<'a>(rust: &'a str, name: &str) -> &'a str {
        let start = rust.find(&format!("pub trait {name}")).expect("the trait");
        let body = &rust[start..];
        &body[..body.find("\n}\n").expect("the trait ends")]
    }

    /// A schema an ancestor already reflects arrives through the ancestor's
    /// trait, so a descendant listing it again reflects nothing twice.
    #[test]
    fn reflected_by_ancestor() {
        let dir = tempfile::tempdir().expect("tempdir");
        let model = read_source(
            dir.path(),
            &reflecting_base(
                r#"class "Derived" (
    inherits = </Base>
    customData = { token[] reflectedAPISchemas = ["TagAPI"] }
) {
}"#,
            ),
        )
        .expect("resolves");

        let rust = emit(&model, &Externs::new(), "schema.usda", Views::Generate, &[]).expect("emits");
        let base = trait_body(&rust, "BaseSchema");
        assert!(base.contains("fn tag_attr(") && base.contains("fn tag_api("), "{base}");
        let derived = trait_body(&rust, "DerivedSchema");
        assert!(
            !derived.contains("fn tag_attr(") && !derived.contains("fn tag_api("),
            "{derived}"
        );
    }

    /// A property a descendant declares under a name an ancestor's reflected
    /// accessor already takes is a collision, as one with an inherited property
    /// is.
    #[test]
    fn reflected_by_ancestor_collides() {
        let dir = tempfile::tempdir().expect("tempdir");
        let model = read_source(
            dir.path(),
            &reflecting_base(
                r#"class "Derived" (
    inherits = </Base>
) {
    string tag = "own"
}"#,
            ),
        )
        .expect("resolves");

        match emit(&model, &Externs::new(), "schema.usda", Views::Generate, &[]) {
            Err(Error::Definition {
                violation: Violation::MethodCollision { method, first, second },
                ..
            }) => {
                assert_eq!(method, "tag_attr");
                assert_eq!(first.as_str(), "tag");
                assert_eq!(second.as_str(), "Base");
            }
            other => panic!("{:?}", other.map(|_| "emitted")),
        }
    }

    /// A schema listed twice is reflected once.
    #[test]
    fn reflected_listed_twice() {
        let dir = tempfile::tempdir().expect("tempdir");
        let model = read_source(
            dir.path(),
            &schema(
                "testTwice",
                &format!(
                    r#"{TAG_API}

class "Thing" (
    inherits = </Typed>
    prepend apiSchemas = ["TagAPI"]
    customData = {{ token[] reflectedAPISchemas = ["TagAPI", "TagAPI"] }}
) {{
}}"#
                ),
            ),
        )
        .expect("resolves");

        let rust = emit(&model, &Externs::new(), "schema.usda", Views::Generate, &[]).expect("emits");
        let thing = trait_body(&rust, "ThingSchema");
        assert_eq!(thing.matches("fn tag_api(").count(), 1, "{thing}");
        assert_eq!(thing.matches("fn tag_attr(").count(), 1, "{thing}");
    }

    /// A library here sublayering `testElsewhere`, whose `Base` reflects
    /// `TagAPI` and declares a `label` of its own, with `classes` declared here.
    fn below_foreign_base(dir: &Path, classes: &str) -> Library {
        let base = schema(
            "testElsewhere",
            &format!(
                r#"{TAG_API}

class "Base" (
    inherits = </Typed>
    prepend apiSchemas = ["TagAPI"]
    customData = {{ token[] reflectedAPISchemas = ["TagAPI"] }}
) {{
    string label = ""
}}"#
            ),
        );
        stacked(
            dir,
            &[("base.usda", base.as_str())],
            &sublayering(&["base.usda"], classes),
        )
    }

    /// Where `testElsewhere`'s views are placed.
    fn elsewhere_placed() -> Externs {
        Externs::from([("testElsewhere".to_owned(), "crate::elsewhere".to_owned())])
    }

    /// The collision `emit` reports for `model`, as `(method, first, second)`.
    fn collision(model: &Library, externs: &Externs) -> (String, String, String) {
        match emit(model, externs, "schema.usda", Views::Generate, &[]) {
            Err(Error::Definition {
                violation: Violation::MethodCollision { method, first, second },
                ..
            }) => (method, first.to_string(), second.to_string()),
            other => panic!("{:?}", other.map(|_| "emitted")),
        }
    }

    /// An ancestor another library declares is read the same way: what it
    /// reflects arrives through its trait, so a descendant here listing the same
    /// schema reflects nothing of it.
    #[test]
    fn reflected_by_foreign_ancestor() {
        let dir = tempfile::tempdir().expect("tempdir");
        let model = below_foreign_base(
            dir.path(),
            r#"class "Derived" (
    inherits = </Base>
    customData = { token[] reflectedAPISchemas = ["TagAPI"] }
) {
}"#,
        );

        let rust = emit(&model, &elsewhere_placed(), "schema.usda", Views::Generate, &[]).expect("emits");
        let derived = trait_body(&rust, "DerivedSchema");
        assert!(
            derived.starts_with("pub trait DerivedSchema: crate::elsewhere::BaseSchema"),
            "{derived}"
        );
        assert!(
            !derived.contains("fn tag_attr(") && !derived.contains("fn tag_api("),
            "{derived}"
        );
    }

    /// What an ancestor of another library reflects takes its method names as
    /// surely as one of this library's does, so a property here offering the
    /// same accessor is reported as a collision when the library is built.
    #[test]
    fn reflected_by_foreign_ancestor_collides() {
        let dir = tempfile::tempdir().expect("tempdir");
        let model = below_foreign_base(
            dir.path(),
            r#"class "Derived" (
    inherits = </Base>
) {
    string tag = "own"
}"#,
        );

        let inherited: Vec<&str> = model.inherited.iter().map(|class| class.identifier.as_str()).collect();
        assert_eq!(
            inherited,
            vec!["Base", "TagAPI"],
            "the ancestor and what it reflects are held"
        );
        let (method, first, second) = collision(&model, &elsewhere_placed());
        assert_eq!(
            (method.as_str(), first.as_str(), second.as_str()),
            ("tag_attr", "tag", "Base")
        );
    }

    /// A schema a descendant reflects is held to the names its foreign
    /// ancestor's reflected schema already takes.
    #[test]
    fn foreign_reflections_collide() {
        let dir = tempfile::tempdir().expect("tempdir");
        let model = below_foreign_base(
            dir.path(),
            r#"class "LabelAPI" (
    inherits = </APISchemaBase>
    customData = { token apiSchemaType = "singleApply" }
) {
    string tag = ""
}

class "Derived" (
    inherits = </Base>
    prepend apiSchemas = ["LabelAPI"]
    customData = { token[] reflectedAPISchemas = ["LabelAPI"] }
) {
}"#,
        );

        let (method, first, second) = collision(&model, &elsewhere_placed());
        assert_eq!(
            (method.as_str(), first.as_str(), second.as_str()),
            ("tag_attr", "Base", "LabelAPI")
        );
    }

    /// A foreign grandparent's reflections reach a class through its parent
    /// here, so they are checked there too.
    #[test]
    fn foreign_grandparent_collides() {
        let dir = tempfile::tempdir().expect("tempdir");
        let model = below_foreign_base(
            dir.path(),
            r#"class "Middle" (
    inherits = </Base>
) {
}

class "Derived" (
    inherits = </Middle>
) {
    string tag = "own"
}"#,
        );

        let (method, first, second) = collision(&model, &elsewhere_placed());
        assert_eq!(
            (method.as_str(), first.as_str(), second.as_str()),
            ("tag_attr", "tag", "Base")
        );
    }

    /// Prose on a class names an accessor its foreign ancestor declares, and
    /// links to it through the module that ancestor's views were placed at.
    #[test]
    fn foreign_ancestor_accessor_linked() {
        let dir = tempfile::tempdir().expect("tempdir");
        let model = below_foreign_base(
            dir.path(),
            r#"class "Derived" (
    doc = "See GetLabelAttr()."
    inherits = </Base>
) {
}"#,
        );

        let rust = emit(&model, &elsewhere_placed(), "schema.usda", Views::Generate, &[]).expect("emits");
        assert!(
            rust.contains("[`label_attr`](crate::elsewhere::BaseSchema::label_attr)"),
            "{rust}"
        );
    }

    /// A library of the roots and one typed class, `BigThing`, for another
    /// library's prose to name.
    fn elsewhere() -> String {
        schema(
            "testElsewhere",
            r#"class "BigThing" (
    inherits = </Typed>
) {
}"#,
        )
    }

    /// A class another library declares is linked under both spellings
    /// upstream writes it, through the path that library's views were placed
    /// at.
    #[test]
    fn foreign_class_linked() {
        let dir = tempfile::tempdir().expect("tempdir");
        let elsewhere = elsewhere();
        let model = stacked(
            dir.path(),
            &[("base.usda", elsewhere.as_str())],
            &sublayering(
                &["base.usda"],
                &with_doc("Like a TestElsewhereBigThing, or a BigThing."),
            ),
        );
        let externs = Externs::from([("testElsewhere".to_owned(), "crate::elsewhere".to_owned())]);

        let rust = emit(&model, &externs, "schema.usda", Views::Generate, &[]).expect("emits");
        assert!(rust.contains("[`BigThing`](crate::elsewhere::BigThing)"), "{rust}");
        assert!(
            !rust.contains("TestElsewhereBigThing"),
            "the qualified spelling is linked: {rust}"
        );
        assert!(!rust.contains("a `BigThing`"), "the bare spelling is linked: {rust}");
    }

    /// A class of a library that was never placed is left as it was written: a
    /// link is not worth failing a build over.
    #[test]
    fn unplaced_foreign_unlinked() {
        let dir = tempfile::tempdir().expect("tempdir");
        let elsewhere = elsewhere();
        let model = stacked(
            dir.path(),
            &[("base.usda", elsewhere.as_str())],
            &sublayering(&["base.usda"], &with_doc("Like a TestElsewhereBigThing.")),
        );

        let rust = emit(&model, &Externs::new(), "schema.usda", Views::Generate, &[]).expect("emits");
        assert!(rust.contains("Like a `TestElsewhereBigThing`."), "{rust}");
        assert!(!rust.contains("crate::elsewhere"), "{rust}");
    }

    /// A bare class name two other libraries share names neither; the
    /// qualified spellings still each name theirs.
    #[test]
    fn foreign_name_ambiguous() {
        let dir = tempfile::tempdir().expect("tempdir");
        let alpha = schema(
            "testAlpha",
            r#"class "Alpha" (
    inherits = </Typed>
    customData = { string className = "SharedThing" }
) {
}"#,
        );
        let beta = schema(
            "testBeta",
            r#"class "Beta" (
    inherits = </Typed>
    customData = { string className = "SharedThing" }
) {
}"#,
        );
        let model = stacked(
            dir.path(),
            &[("alpha.usda", alpha.as_str()), ("beta.usda", beta.as_str())],
            &sublayering(
                &["alpha.usda", "beta.usda"],
                &with_doc("TestAlphaSharedThing and TestBetaSharedThing are each a SharedThing."),
            ),
        );
        let externs = Externs::from([
            ("testAlpha".to_owned(), "crate::alpha".to_owned()),
            ("testBeta".to_owned(), "crate::beta".to_owned()),
        ]);

        let rust = emit(&model, &externs, "schema.usda", Views::Generate, &[]).expect("emits");
        assert!(rust.contains("[`SharedThing`](crate::alpha::SharedThing)"), "{rust}");
        assert!(rust.contains("[`SharedThing`](crate::beta::SharedThing)"), "{rust}");
        assert!(rust.contains("a `SharedThing`."), "{rust}");
    }

    /// A class of this library keeps its bare name against a class of another
    /// library called the same; the other is still reached by its qualified
    /// spelling.
    #[test]
    fn foreign_name_yields_to_own() {
        let dir = tempfile::tempdir().expect("tempdir");
        let elsewhere = schema(
            "testElsewhere",
            r#"class "Elsewhere" (
    inherits = </Typed>
    customData = { string className = "BigThing" }
) {
}"#,
        );
        let model = stacked(
            dir.path(),
            &[("base.usda", elsewhere.as_str())],
            &sublayering(
                &["base.usda"],
                &format!(
                    r#"class "BigThing" (
    inherits = </Typed>
) {{
}}

{}"#,
                    with_doc("Is a BigThing. Not a TestElsewhereBigThing.")
                ),
            ),
        );
        let externs = Externs::from([("testElsewhere".to_owned(), "crate::elsewhere".to_owned())]);

        let rust = emit(&model, &externs, "schema.usda", Views::Generate, &[]).expect("emits");
        assert!(
            rust.contains("Is a [`BigThing`]. Not a [`BigThing`](crate::elsewhere::BigThing)."),
            "{rust}"
        );
    }

    /// A library declaring `libraryPrefix` is paired under that spelling, which
    /// is how upstream's prose names its classes, and not under the name it
    /// would otherwise take.
    #[test]
    fn library_prefix_kept() {
        let dir = tempfile::tempdir().expect("tempdir");
        let model = read_source(
            dir.path(),
            r#"#usda 1.0

def "GLOBAL" (
    customData = {
        string libraryName = "testHere"
        string libraryPrefix = "Pfx"
    }
)
{
}

class "Typed" {}

class Crate "Crate" (
    inherits = </Typed>
    doc = "A PfxCrate, not a TestHereCrate."
) {
}
"#,
        )
        .expect("resolves");

        let rust = emit(&model, &Externs::new(), "schema.usda", Views::Generate, &[]).expect("emits");
        assert!(rust.contains("A [`Crate`], not a `TestHereCrate`."), "{rust}");
    }

    /// The generated file takes three names of its own, and a class that asks
    /// for one is refused where it asks rather than by the consumer's compiler.
    #[test]
    fn class_takes_a_file_name() {
        let dir = tempfile::tempdir().expect("tempdir");
        let library = read_source(
            dir.path(),
            r#"#usda 1.0

def "GLOBAL" (
    customData = {
        string libraryName = "testReserved"
    }
)
{
}

class "Typed" {}

class "Held" (
    inherits = </Typed>
    customData = {
        string className = "tokens"
    }
) {
}
"#,
        )
        .expect("the library itself is well formed");

        match emit(&library, &Externs::new(), "schema.usda", Views::Generate, &[]) {
            Err(Error::Definition {
                violation: Violation::RustNameCollision { name, .. },
                ..
            }) => assert_eq!(name, "tokens"),
            other => panic!("{:?}", other.map(|_| "emitted")),
        }
    }

    /// A legacy type spelling a stage resolves but no constant names is one no
    /// creator could declare, so it is refused rather than declared as a token.
    #[test]
    fn type_without_a_constant() {
        let dir = tempfile::tempdir().expect("tempdir");
        let library = read_source(
            dir.path(),
            r#"#usda 1.0

def "GLOBAL" (
    customData = {
        string libraryName = "testTypes"
    }
)
{
}

class "Typed" {}

class "Held" (
    inherits = </Typed>
) {
    Transform placement
}
"#,
        )
        .expect("the type is one a stage resolves");

        match emit(&library, &Externs::new(), "schema.usda", Views::Generate, &[]) {
            Err(Error::Definition {
                violation: Violation::UnnameableType { property, .. },
                ..
            }) => assert_eq!(property.as_str(), "placement"),
            other => panic!("{:?}", other.map(|_| "emitted")),
        }
    }

    /// A redeclaration reaches the ancestor's accessor, so a hand-written
    /// reader asked for beside it would never be called.
    #[test]
    fn custom_get_on_a_redeclaration() {
        let dir = tempfile::tempdir().expect("tempdir");
        let library = read_source(
            dir.path(),
            r#"#usda 1.0

def "GLOBAL" (
    customData = {
        string libraryName = "testShadowed"
    }
)
{
}

class "Typed" {}

class "Held" (
    inherits = </Typed>
) {
    double size = 1
}

class "Deeper" (
    inherits = </Held>
) {
    double size = 2 (
        customData = {
            string apiGetImplementation = "custom"
        }
    )
}
"#,
        )
        .expect("the library itself is well formed");

        match emit(&library, &Externs::new(), "schema.usda", Views::Generate, &[]) {
            Err(Error::Definition {
                violation: Violation::CustomGetWithoutAccessor { property },
                ..
            }) => assert_eq!(property.as_str(), "size"),
            other => panic!("{:?}", other.map(|_| "emitted")),
        }
    }
}