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
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
//! Layer DAG: the loaded layers and their sublayer structure.
//!
//! [`LayerGraph`] owns every [`sdf::Layer`] a stage depends on and the sublayer
//! edges between them, keyed by the stable [`LayerId`]. It is the Rust
//! analog of C++ `PcpLayerStack` for the layer-ownership half of composition;
//! the composition index itself lives in [`IndexCache`](super::index_cache::IndexCache).
//!
//! Holding layers here (rather than inside the cache) lets a [`Stage`] borrow
//! the layer data and the composition index independently. Composition reads
//! the graph through a shared `&LayerGraph` parameter, so every per-prim build
//! stays a pure function of `(graph, context, cached indices)`.
//!
//! A composed sublayer stack (the depth-first pre-order walk of a root's sublayer
//! edges, with offsets composed) is interned in the
//! [`LayerStackRegistry`](super::layer_stack::LayerStackRegistry) of the
//! [`layer_stack`](super::layer_stack) module and addressed by a [`LayerStackId`];
//! only composition roots get an instance, so a sublayer-only layer participates
//! through its root's members rather than its own stack. The edges are always
//! derived from each layer's `subLayers` metadata by
//! [`recompute_sublayers`](LayerGraph::recompute_sublayers): both an ordinary
//! `subLayers` authoring edit and the public
//! [`Stage::insert_layer`](crate::usd::Stage::insert_layer) /
//! [`remove_layer`](crate::usd::Stage::remove_layer) route through it, so
//! editing `subLayers` updates the edges and the metadata stays the single
//! source of truth — no DFS on every query, and no edge that fails to persist on
//! save.
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::hash::Hash;
use std::mem;
use std::path;
use crate::ar::ResolvedPath;
use crate::sdf::expr;
use crate::sdf::schema::FieldKey;
use crate::sdf::{self, LayerOffset, Path, RelocateList, Value};
use super::compose_site::{evaluate_expression, EvaluatedExpression};
use super::layer_stack::{ExprVarId, LayerStackId, LayerStackRegistry, StackVarsDelta, VarsSource};
use super::mapping::MapFunction;
use super::prim_index::Demand;
use super::relocates::{analyze_relocate_occurrences, chain_through_relocates, validate_layer_relocates};
use super::{effective_time_codes_per_second, Error, ExpressionContext};
/// A cheap, `Copy` handle identifying a layer within a `LayerGraph`.
///
/// Graph-assigned (interned) as layers are added, not derived from content, so
/// it is unique by construction — no hashing and no collision. It is opaque:
/// resolve it back to an identifier with
/// [`Stage::layer_identifier`](crate::usd::Stage::layer_identifier). Authoring
/// callers address layers by identifier string instead; this handle is what
/// composition introspection (the [`PrimIndex`](super::PrimIndex) nodes) hands
/// back.
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct LayerId(u32);
impl LayerId {
/// A sentinel never assigned to a real layer, for degenerate fallbacks (an
/// empty layer stack's synthetic root, an unresolvable edit target).
pub(crate) const INVALID: LayerId = LayerId(u32::MAX);
/// Wraps a raw graph-assigned index. Only [`LayerGraph`] mints ids in
/// production; tests use it to build synthetic handles.
pub(crate) const fn from_raw(raw: u32) -> Self {
Self(raw)
}
}
/// Stable identity of a stage's root layer stack, by composition input.
///
/// The Rust analog of C++ `PcpLayerStackIdentifier`, which keys a
/// `PcpLayerStack` by `(rootLayer, sessionLayer, pathResolverContext)`. Two
/// stages opened from the same root and session under a resolver with the same
/// [`identity`](crate::ar::Resolver::identity) are the same composition input,
/// so their identifiers compare equal. Used to tag a stage-bound
/// [`EditTarget`](crate::usd::EditTarget) so one built against a stage's
/// composition is rejected by an unrelated stage.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LayerStackIdentifier {
/// Canonical identifier of the root layer.
pub root_layer: String,
/// Canonical identifier of the strongest session layer, if any.
pub session_layer: Option<String>,
/// The resolver's [`identity`](crate::ar::Resolver::identity) token — the
/// configuration the stack's asset paths resolve under.
pub resolver: String,
}
/// A composed layer stack by value — the transferable counterpart of the
/// graph-local [`LayerStackId`], the value form of C++
/// `PcpLayerStackIdentifier` with its recursive
/// `expressionVariablesOverrideSource`. An arc-based edit target carries one so
/// the stack resolves by content on whichever equal-input stage installs it,
/// where the numeric handles differ. Total over every stack, the root included,
/// so capture and resolve sites need no root special case. Captured by
/// [`stack_identity`](LayerGraph::stack_identity) and resolved by
/// [`resolve_stack_identity`](LayerGraph::resolve_stack_identity).
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum StackIdentity {
/// The stage root layer stack.
Root,
/// A reference/payload target stack: the target root layer's canonical
/// identifier plus its variable source chain — each element the canonical
/// identifier of a source stack's target root, ordered outermost (seeded by
/// the stage root stack) first, with an empty chain meaning the root
/// source.
Target {
/// Canonical identifier of the target root layer.
root: String,
/// Canonical identifiers of the variable source chain's target roots,
/// outermost first.
source_chain: Vec<String>,
},
}
/// A layer's resolved sublayer edges in declared order: each child paired with
/// the effective layer offset for that hop (the authored `subLayerOffset` with
/// the time-codes-per-second retiming folded in, per spec 10.3.1.1 / 12.3.2).
type SublayerEdges = Vec<(LayerId, LayerOffset)>;
/// A single layer in the [`LayerGraph`].
pub(crate) struct LayerNode {
/// The loaded layer (identifier + backing data + authoring surface).
pub layer: sdf::Layer,
/// This layer's context-free [`SublayerEdges`]: its `subLayers` resolved against
/// the empty expression-variable set, so literal sublayers resolve and `${VAR}`
/// sublayers drop out. Shared by every stack with no expression sublayer, where
/// the members are context-independent; a stack with an expression sublayer
/// re-resolves its subtree against the stack's variables in
/// [`compose_stack_edges`](LayerGraph::compose_stack_edges) instead, so these are
/// not duplicated per stack instance.
pub children: SublayerEdges,
/// Whether this layer authors at least one expression-valued (`${VAR}`)
/// `subLayers` entry — a purely local property of its own `subLayers`, not its
/// composed subtree. Recomputed by
/// [`build_sublayer_edges`](LayerGraph::build_sublayer_edges), it lets
/// [`has_expr_sublayer`](LayerGraph::has_expr_sublayer) decide whether a stack's
/// members depend on the expression-variable context by reading a bool per
/// member rather than re-decoding `subLayers`.
pub has_expr_sublayer: bool,
/// The structurally valid authored `layerRelocates` pairs `(source, target)`
/// in this layer's own namespace. Stack queries apply duplicate-source and
/// conflict rules for the ambient layer stack. Empty when the layer authors
/// none.
pub relocates: RelocateList,
}
impl LayerNode {
/// A node wrapping `layer`, with no edges and no relocates. The sublayer
/// edges, expression-sublayer flag, and relocates are filled in by
/// [`LayerGraph::recompute_sublayers`].
fn new(layer: sdf::Layer) -> Self {
Self {
layer,
children: Vec::new(),
has_expr_sublayer: false,
relocates: Vec::new(),
}
}
}
/// The loaded layers and their sublayer DAG.
///
/// Corresponds to a simplified C++ `PcpLayerStack`: it owns the layers but not
/// the composed prim indices. Composition queries reach a layer by its
/// [`LayerId`] in O(1).
pub(crate) struct LayerGraph {
/// Every layer, keyed by id.
nodes: HashMap<LayerId, LayerNode>,
/// Exact `identifier → id` index, so a layer is resolved by its canonical
/// identifier (the public authoring surface) in O(1), and a re-added
/// identifier collapses onto its existing id.
by_identifier: HashMap<String, LayerId>,
/// Next id to mint. Monotonic for the life of the graph, so a removed id is
/// never reused for a different layer within a session.
next_id: u32,
/// All layer ids in collection order. Iteration order is deterministic, so
/// identifier listing and sublayer-stack composition are stable. The
/// first [`session_layer_count`](Self::session_layer_count) entries are the
/// session layers collected at open, in strength order; the session root is
/// `order[0]`. Root-stack membership derives from a sublayer walk rooted
/// there, not from this prefix, so a session sublayer loaded at runtime
/// composes without joining it.
order: Vec<LayerId>,
/// Number of open-time session layers at the front of [`order`](Self::order).
session_layer_count: usize,
/// The root layer's id (the first non-session layer), if any.
root: Option<LayerId>,
/// Canonical identifiers of the muted layers — the source of truth for muting
/// (C++ `Pcp_MutedLayers`'s sorted id set), so a layer can be muted before it
/// is loaded. A path is reduced to this canonical form by
/// [`canonical_muted_id`](Self::canonical_muted_id) (the resolver, anchored
/// against the root layer), so every spelling of one layer collapses to a
/// single entry and a not-yet-loaded reference/payload target matches the
/// identifier it will be interned under. Excludes the root layer's identifier,
/// which cannot be muted. The root layer can be muted neither here nor in
/// [`muted`](Self::muted).
muted_identifiers: HashSet<String>,
/// The interned ids of the [`muted_identifiers`](Self::muted_identifiers) that
/// name a loaded layer, re-materialized on every stack rebuild and excluded
/// when materializing the stacks (C++ `PcpLayerStack::_BuildLayerStack`). A
/// muted layer and its whole sublayer subtree are pruned from every stack while
/// staying interned, so unmute is a rebuild. Re-materializing on each rebuild
/// lets a layer muted before it was loaded take effect the moment it is
/// interned. Empty by default, leaving composition unchanged.
muted: HashSet<LayerId>,
/// Whether any node keeps structurally valid authored relocates. The indexer
/// reads this to gate its relocate passes without rescanning.
has_relocates: bool,
/// Sublayer-cycle diagnostics reachable from the root layer, replaced wholesale
/// by [`build_sublayer_edges`](Self::build_sublayer_edges) on every edge
/// rebuild so a fixed cycle stops being reported and a recompute never
/// duplicates one.
cycle_errors: Vec<Error>,
/// Validated-relocate diagnostics, replaced wholesale by
/// [`recompute_relocates`](Self::recompute_relocates) on every relocate
/// rebuild. Independent of [`cycle_errors`](Self::cycle_errors): a
/// relocate-only edit refreshes these alone.
relocate_errors: Vec<Error>,
/// Loads layers: the resolver that anchors relative asset paths (its
/// [`identity`](Resolver::identity) is the resolver component of the stack's
/// [`layer_stack_id`](Self::layer_stack_id)) and the format registry.
/// Composition opens a reference/payload target on demand through it.
registry: sdf::LayerRegistry,
/// Anchored asset paths whose on-demand open failed, each mapped to what
/// went wrong ([`LoadFailure`]). Consulted at the reference/payload demand
/// point so a target that cannot be opened is reported
/// [`MalformedLayer`](Error::MalformedLayer) once (with the arc's site
/// context and the failure's reason) rather than re-demanded every pass —
/// without it the demanding prim's index would never cache — and at
/// sublayer-demand derivation
/// ([`file_stack_discoveries`](Self::file_stack_discoveries)), which
/// regenerates a failed entry's per-referrer diagnostic instead of a
/// demand. Written only at the stage's load barrier through `&mut self`;
/// read during composition, and cleared when an edit changes the layers so
/// a now-readable asset is retried.
failed_loads: HashMap<String, LoadFailure>,
/// Every composed layer stack against this graph — the stage root stack, plus
/// each reference/payload target's stack under whatever variable sources have
/// reached it (see [`LayerStackRegistry`]). The graph composes a stack's members
/// (it owns the layers) through [`build_stack_members`](Self::build_stack_members)
/// and hands them to the registry, which owns the storage and interning. A
/// [`LayerStackId`] is an index into it.
stacks: LayerStackRegistry,
/// The sublayer-resolution subsystem: what the `subLayers` walks derive and
/// carry beyond the composed edges themselves (see [`SublayerState`]).
sublayers: SublayerState,
}
/// The [`LayerGraph`]'s sublayer-resolution subsystem: everything the
/// `subLayers` walks derive beyond the composed edges themselves — the shared
/// path-resolution memo, the context-free misses, the pending load demands,
/// and the per-stack diagnostics. One invariant ties the mutable pieces
/// together: a stack's re-resolution supersedes its earlier discoveries
/// ([`replace_stack`](Self::replace_stack)), so demands and diagnostics always
/// reflect each stack's latest rebuild.
#[derive(Default)]
struct SublayerState {
/// Whether any node authors an expression-valued (`${VAR}`) `subLayers` entry.
/// A false value lets [`LayerGraph::has_expr_sublayer`] short-circuit to
/// `false` for the overwhelmingly common stage with no expression sublayers,
/// so `LayerGraph::build_stack_members` never scans a stack for them.
/// Recomputed with the per-node flags by
/// `LayerGraph::recompute_expr_sublayer_flags`.
any_expr: bool,
/// Memoized sublayer-path resolution, `parent layer → (authored sub-path →
/// resolved identifier)`. `LayerGraph::resolve_edges` anchors each relative
/// `subLayers` entry against its parent through the resolver — a filesystem
/// canonicalize — and re-runs the whole walk on every
/// `LayerGraph::build_sublayer_edges`, i.e. every `subLayers` edit. The
/// `(parent, sub-path) → identifier` mapping is a pure function of the
/// asset paths, so it is computed once and reused; the identifier is then
/// looked up live with [`LayerGraph::id_of`], so the cache survives a layer
/// being removed and re-added, and a target that interns on a later rebuild
/// is picked up without re-resolving the path.
resolution: HashMap<LayerId, HashMap<String, String>>,
/// Sublayer entries that resolved to no loaded layer under the empty
/// context, keyed by the authoring parent — the table a stack on the
/// context-free `collect_plain` fast path consults to record load demands
/// without re-decoding `subLayers` (its edges are exactly the context-free
/// ones). Rebuilt wholesale by [`set_plain_misses`](Self::set_plain_misses)
/// per edge build; a stack with an expression sublayer records its
/// unresolved entries directly from its contextual re-resolution instead.
// TODO(perf): a permanently missing literal keeps this table non-empty, so
// every plain-stack rebuild re-scans its members to regenerate the
// diagnostic; a per-parent presence flag on `LayerNode` would shortcut
// stacks with no unresolved entries.
unresolved_plain: HashMap<LayerId, Vec<String>>,
/// The [`SublayerDemand`]s the last stack recompose or mint discovered,
/// awaiting the stage's load barrier
/// ([`LayerGraph::take_sublayer_demands`]). A plain `Vec` mutated through
/// `&mut self`, like the cache's pending arc demands; each stack's entries
/// reflect its latest rebuild ([`replace_stack`](Self::replace_stack)).
pending_demands: Vec<SublayerDemand>,
/// Per-stack sublayer diagnostics: `${VAR}` expression failures
/// ([`Error::InvalidExpression`] with the sublayer context) and the
/// per-referrer load failures of unresolved entries
/// ([`Error::UnresolvedSublayer`] / [`Error::MalformedSublayer`]). Each
/// stack's bucket is replaced on its contextual re-resolution — load
/// failures re-derived from `LayerGraph::failed_loads` — so a fixed
/// expression or a removed entry stops being reported; the load barrier
/// appends a freshly discovered failure between rebuilds
/// ([`record_error`](Self::record_error)). Keyed by stack in mint order, so
/// the [`diagnostics`](Self::diagnostics) listing is deterministic.
errors: BTreeMap<LayerStackId, Vec<Error>>,
}
impl SublayerState {
/// Replaces `stack`'s discoveries — its pending demands and its error
/// bucket — with a fresh re-resolution's. The supersession invariant: a
/// stale demand or diagnostic could name an entry a mute or edit just
/// removed, so both always reflect the stack's latest rebuild.
fn replace_stack(&mut self, stack: LayerStackId, demands: Vec<SublayerDemand>, errors: Vec<Error>) {
self.pending_demands.retain(|demand| demand.stack != stack);
self.pending_demands.extend(demands);
if errors.is_empty() {
self.errors.remove(&stack);
} else {
self.errors.insert(stack, errors);
}
}
/// Appends a diagnostic to `stack`'s bucket — the load barrier's channel
/// for a failure discovered between rebuilds; the stack's next
/// re-resolution re-derives or drops it
/// ([`replace_stack`](Self::replace_stack)). An identical already-recorded
/// diagnostic is not repeated.
fn record_error(&mut self, stack: LayerStackId, error: Error) {
let bucket = self.errors.entry(stack).or_default();
if !bucket.contains(&error) {
bucket.push(error);
}
}
/// Drains the pending demands for the stage's load barrier.
fn take_demands(&mut self) -> Vec<SublayerDemand> {
mem::take(&mut self.pending_demands)
}
/// Replaces the per-parent table of context-free unresolved entries from
/// one edge build's misses.
fn set_plain_misses(&mut self, misses: Vec<(LayerId, String)>) {
self.unresolved_plain.clear();
for (parent, evaluated) in misses {
self.unresolved_plain.entry(parent).or_default().push(evaluated);
}
}
/// Every per-stack diagnostic, in stack mint order.
fn diagnostics(&self) -> impl Iterator<Item = &Error> {
self.errors.values().flatten()
}
}
/// What a [`mute_layer`](LayerGraph::mute_layer) or
/// [`unmute_layer`](LayerGraph::unmute_layer) actually changed, returned only
/// when the muted set changed.
pub(crate) struct MuteChange {
/// The canonical identifier whose muted state toggled — the one a mute
/// inserted or an unmute removed. The stage notifies it, not the spelling the
/// caller passed, so a listener mirroring the muted set stays in sync (C++
/// reports the canonical id it toggled).
pub(crate) changed: String,
/// Layers whose cached prim indices the change can invalidate (see
/// [`mute_fanout`](LayerGraph::mute_fanout)).
pub(crate) affected: HashSet<LayerId>,
}
/// The layer stack a reference/payload arc to an external target should compose
/// against, the result of [`LayerGraph::external_stack_id`]. Centralizes the
/// stack-selection decision so the indexer and the load barrier do not each
/// re-encode it.
pub(crate) enum ExternalStack {
/// The stack is composed and ready; compose the arc against this handle.
Ready(LayerStackId),
/// No instance exists yet for this `(target, source)`; the arc must record a
/// [`Demand`](super::Demand) so the load barrier mints it (and opens any
/// `${VAR}` sublayers the context resolves), after which the query re-runs.
Demand,
}
/// A composed stack's unresolved `subLayers` entry — `${VAR}`-selected or
/// literal — naming a layer not yet in the graph. Recorded while a stack's
/// members are composed (a [`rebuild_sublayer_stacks`](LayerGraph::rebuild_sublayer_stacks)
/// pass or a mint) and drained by the stage's load barrier
/// ([`take_sublayer_demands`](LayerGraph::take_sublayer_demands)), which opens
/// the layer under the demanding stack's composed expression variables and
/// recomposes — the sublayer analog of a reference/payload [`Demand`].
#[derive(Debug, Clone)]
pub(crate) struct SublayerDemand {
/// The layer whose `subLayers` entry did not resolve: the anchor for the
/// entry's relative path, and the referrer diagnostics name.
pub(crate) parent: LayerId,
/// The stack the entry composes into. Its composed expression variables are
/// the context the demanded layer's own sublayers resolve under, and the
/// barrier dedups open attempts per `(identifier, stack)`.
pub(crate) stack: LayerStackId,
/// The entry's evaluated asset path (the authored path for a literal).
pub(crate) evaluated: String,
}
/// What [`LayerGraph::recompute_sublayers`] found: the layers whose composed
/// state shifted (the cache-eviction scope) and the per-stack composed
/// expression-variable changes the rebuild emitted. Change processing
/// (`pcp::Changes::apply`) consumes both; the mute and load paths use only
/// [`affected`](Self::affected) — a mute's blanket fanout already covers any
/// variable shift, and a load never changes a stack's composed variables (they
/// read only the root layer and seed, both already present).
pub(crate) struct SublayerRecompute {
/// The layers whose composed edges or relocate pairs changed, unioned with
/// the edited set.
pub(crate) affected: HashSet<LayerId>,
/// The stacks whose composed expression variables (or their source)
/// changed, in dependency order.
pub(crate) vars_deltas: Vec<StackVarsDelta>,
}
/// Why a prior on-demand open of an asset failed, memoized in
/// [`failed_loads`](LayerGraph::failed_loads) so composition stops retrying
/// the asset and every referrer's diagnostic can be re-derived from it. An
/// [`Unreadable`](Self::Unreadable) failure is terminal until an edit clears
/// the memo; an [`Unresolved`](Self::Unresolved) one blocks nothing once the
/// asset resolves again (the file has since appeared).
#[derive(Debug, Clone)]
pub(crate) enum LoadFailure {
/// The asset path did not resolve to a physical location.
Unresolved,
/// It resolved but could not be read or parsed.
Unreadable(String),
}
impl LoadFailure {
/// The per-referrer sublayer diagnostic for this failure: the entry
/// `asset_path`, authored by `introduced_by`, names an asset that did not
/// resolve or could not be read.
pub(crate) fn sublayer_error(&self, asset_path: &str, introduced_by: &str) -> Error {
match self {
LoadFailure::Unresolved => Error::UnresolvedSublayer {
asset_path: asset_path.to_string(),
introduced_by: introduced_by.to_string(),
},
LoadFailure::Unreadable(reason) => Error::MalformedSublayer {
asset_path: asset_path.to_string(),
introduced_by: introduced_by.to_string(),
reason: reason.clone(),
},
}
}
}
/// What a sublayer-edge resolution pass discovers beyond the edges themselves,
/// tagged by the authoring parent so the consumer can drop what a muted branch
/// keeps out of the composed stack. The default sink records demands only —
/// the shape the context-free pass wants, whose empty context legitimately
/// fails every expression and must record neither the failures nor their names
/// as dependencies.
#[derive(Default)]
struct EdgeSink {
/// Unresolved entries as `(parent, evaluated path)`.
demands: Vec<(LayerId, String)>,
/// The buckets only a stack's contextual re-resolution fills, or `None` to
/// skip recording them.
contextual: Option<ContextualSink>,
}
/// The [`EdgeSink`] buckets a stack's contextual re-resolution fills beyond
/// the load demands: `${VAR}` evaluation diagnostics and the variable names
/// those evaluations read — successes and failures alike, an undefined name
/// being a dependency too.
#[derive(Default)]
struct ContextualSink {
/// Expression diagnostics as `(parent, error)`.
errors: Vec<(LayerId, Error)>,
/// Variable names the `${VAR}` evaluations requested, as `(parent, name)`.
used_vars: Vec<(LayerId, String)>,
}
impl EdgeSink {
/// A sink for a stack's contextual re-resolution: demands, diagnostics, and
/// used variable names.
fn contextual() -> Self {
Self {
demands: Vec::new(),
contextual: Some(ContextualSink::default()),
}
}
/// Splits the sink into stack-stamped demands, bare diagnostics, and the
/// deduplicated used-variable names, keeping only entries whose parent
/// composes into `members`.
fn drain(
self,
stack: LayerStackId,
members: &HashSet<LayerId>,
) -> (Vec<SublayerDemand>, Vec<Error>, HashSet<String>) {
let demands = self
.demands
.into_iter()
.filter(|(parent, _)| members.contains(parent))
.map(|(parent, evaluated)| SublayerDemand {
parent,
stack,
evaluated,
})
.collect();
let ContextualSink { errors, used_vars } = self.contextual.unwrap_or_default();
let errors = errors
.into_iter()
.filter(|(parent, _)| members.contains(parent))
.map(|(_, error)| error)
.collect();
let used_vars = used_vars
.into_iter()
.filter(|(parent, _)| members.contains(parent))
.map(|(_, name)| name)
.collect();
(demands, errors, used_vars)
}
}
impl LayerGraph {
/// Builds the graph from collected layers in strength order (session layers
/// first, then the root layer and the rest). The recoverable layer-stack
/// errors it detects (sublayer cycles, invalid relocates) are stored on the
/// graph and read back through [`errors`](Self::errors).
/// An empty graph that opens layers through `registry`. Layers join via
/// [`ensure_layer`](Self::ensure_layer); [`finalize`](Self::finalize) wires
/// the sublayer DAG once they are all added. The stage builds a graph this way
/// so it can attach a change sink to each layer as it joins;
/// [`from_layers`](Self::from_layers) is the all-at-once convenience.
pub(crate) fn new(registry: sdf::LayerRegistry) -> Self {
Self {
nodes: HashMap::new(),
by_identifier: HashMap::new(),
next_id: 0,
order: Vec::new(),
session_layer_count: 0,
root: None,
muted_identifiers: HashSet::new(),
muted: HashSet::new(),
has_relocates: false,
cycle_errors: Vec::new(),
relocate_errors: Vec::new(),
registry,
failed_loads: HashMap::new(),
stacks: LayerStackRegistry::default(),
sublayers: SublayerState::default(),
}
}
/// Set the session/root layers and wire the sublayer DAG from each layer's
/// authored `subLayers` metadata (resolving relocates), after the layers have
/// been added. `root` is the stage root layer's id and `session_layer_count`
/// the number of distinct session layers at the front of the collection. The
/// post-add half of construction, shared by [`from_layers`](Self::from_layers)
/// and the stage builder, which adds layers one at a time.
///
/// `session_count` counts only the distinct session-region layers that
/// survive into [`order`](Self::order), so [`session_layers`](Self::session_layers)
/// (which slices the prefix) never over-reads when the caller passed duplicate
/// identifiers (the same dependency reached through both the session and root
/// collections). `root` is captured at the original root slot rather than
/// derived from `order`, so a root identifier that already appeared in the
/// session collection still points at the right layer.
pub(crate) fn finalize(&mut self, session_layer_count: usize, root: Option<LayerId>) {
self.session_layer_count = session_layer_count;
self.root = root;
// A full pass returns no scoped set; finalize re-resolves every stack.
// The first composition's vars deltas are discarded too — nothing is
// cached yet, so there is nothing to invalidate against them.
let _ = self.build_sublayer_edges(None);
self.mint_eager_target_stacks();
self.recompute_relocates();
}
/// Adds `layer` as a node, minting a fresh [`LayerId`] and recording it in
/// [`by_identifier`](Self::by_identifier) and [`order`](Self::order).
/// Returns `(id, fresh)`: an identifier already present is left untouched
/// (its existing node, children, and relocates survive) and reported as not
/// fresh, so a re-added layer collapses onto its existing id.
fn intern(&mut self, mut layer: sdf::Layer) -> (LayerId, bool) {
if let Some(&id) = self.by_identifier.get(layer.identifier()) {
return (id, false);
}
let id = LayerId::from_raw(self.next_id);
self.next_id += 1;
self.by_identifier.insert(layer.identifier().to_string(), id);
// A layer's content is composed fresh as it joins the graph, so any
// change record left by prior write-through edits must not survive to
// be drained by a later transaction the stage runs on it.
layer.discard_changes();
self.nodes.insert(id, LayerNode::new(layer));
self.order.push(id);
(id, true)
}
/// Resolves every layer's `subLayers` into [`LayerNode::children`] — the
/// context-free edges — folding the per-hop time-codes-per-second retiming into
/// each edge offset. Replaces [`cycle_errors`](Self::cycle_errors) with the
/// sublayer-cycle errors reachable from the root layer (C++
/// `PcpErrorSublayerCycle`).
///
/// A layer stack's expression variables come from its root layer, not its
/// sublayers (C++ `PcpExpressionVariables`), so `children` carry no
/// expression-variable context: each layer's `subLayers` resolve independently
/// against the empty variable set, a literal sublayer resolving and an
/// expression (`${VAR}`) sublayer dropping out. Expression sublayers are
/// resolved per-stack against the stack's variables in
/// [`compose_stack_edges`](Self::compose_stack_edges); the shared context-free
/// `children` feed only the stacks that have none.
///
/// Returns the affected layer set for a scoped edit (the layers whose composed
/// edges changed, unioned with `edited`) so the caller can scope cache eviction
/// to the same stacks the re-resolution touched — `None` for a full pass —
/// together with the [`StackVarsDelta`]s the stack rebuild emitted.
fn build_sublayer_edges(
&mut self,
edited: Option<&HashSet<LayerId>>,
) -> (Option<HashSet<LayerId>>, Vec<StackVarsDelta>) {
// Refresh the expression-sublayer flags first, so the stack rebuild below
// reads them through `has_expr_sublayer` for its `collect_plain` fast-path
// gate.
self.recompute_expr_sublayer_flags();
// Edges are resolved into a side buffer so the immutable `resolve_edges`
// borrow does not clash with the per-node mutation that applies them.
let mut all_edges: Vec<(LayerId, SublayerEdges)> = Vec::with_capacity(self.nodes.len());
// Take the resolution cache out so `resolve_edges` (which borrows `self`
// immutably) can fill it; it carries forward across rebuilds, so a
// `subLayers` edit only resolves paths it has not seen before.
let mut resolution = mem::take(&mut self.sublayers.resolution);
// Each layer's context-free edges depend only on its own `subLayers`
// resolved against the empty variable set, so one per-layer pass builds them
// all. The demand-only sink collects the entries that resolved to no loaded
// layer; they become the per-parent table plain stacks consult for load
// demands ([`SublayerState::unresolved_plain`]).
let empty = HashMap::new();
let mut plain_sink = EdgeSink::default();
for &id in &self.order {
let edges = self.resolve_edges(id, &empty, &mut resolution, Some(&mut plain_sink));
all_edges.push((id, edges));
}
self.sublayers.resolution = resolution;
self.sublayers.set_plain_misses(plain_sink.demands);
// Apply the composed edges. A full pass (`None`, at finalize or after a load
// that can extend a stack with a newly opened member) re-resolves every
// stack, so the edges are assigned outright. For an edit, the layers whose
// composed edges actually changed — folded together with the authored layers
// (`edited`) — scope the stack re-resolution to the affected instances: the
// edge diff catches a layer whose own `subLayers` resolution changed, while
// `edited` catches an authored `${VAR}` sublayer or `expressionVariables` edit
// that shifts a stack's members without changing its plain edges.
let affected = match edited {
None => {
for (id, edges) in all_edges {
self.nodes.get_mut(&id).expect("edge source exists").children = edges;
}
None
}
Some(edited) => {
let mut changed: HashSet<LayerId> = HashSet::new();
for (id, edges) in all_edges {
let node = self.nodes.get_mut(&id).expect("edge source exists");
if node.children != edges {
node.children = edges;
changed.insert(id);
}
}
changed.extend(edited);
Some(changed)
}
};
let vars_deltas = self.rebuild_sublayer_stacks(affected.as_ref());
self.recompute_cycle_errors();
(affected, vars_deltas)
}
/// Resolves `id`'s `subLayers` into `(child, effective offset)` edges,
/// evaluating each expression (`${VAR}`) path against `context` — the stack's
/// single expression-variable set, or the empty set for the shared context-free
/// [`LayerNode::children`]. Reads only `id`'s own `subLayers`/`subLayerOffsets`;
/// `id`'s own `expressionVariables` do not contribute — only the stack root's do
/// (C++ `PcpExpressionVariables`), and the caller has already folded them into
/// `context`. `sink`, when given, receives what the resolution drops: entries
/// that resolved to no loaded layer (load-demand candidates), and — when it
/// carries the contextual buckets — `${VAR}` evaluation diagnostics and the
/// variable names those evaluations read.
fn resolve_edges(
&self,
id: LayerId,
context: &HashMap<String, Value>,
resolution: &mut HashMap<LayerId, HashMap<String, String>>,
mut sink: Option<&mut EdgeSink>,
) -> SublayerEdges {
let root_path = Path::abs_root();
let node = &self.nodes[&id];
let Ok(Value::StringVec(sub_paths)) = node
.layer
.data()
.get_field(&root_path, FieldKey::SubLayers.as_str())
.map(|v| v.into_owned())
else {
return Vec::new();
};
let offsets: Vec<LayerOffset> = node
.layer
.data()
.get_field(&root_path, FieldKey::SubLayerOffsets.as_str())
.ok()
.and_then(|v| match v.into_owned() {
Value::LayerOffsetVec(v) => Some(v),
_ => None,
})
.unwrap_or_default();
let parent_tcps = effective_time_codes_per_second(&node.layer);
let mut edges = Vec::with_capacity(sub_paths.len());
for (i, sub_path) in sub_paths.into_iter().enumerate() {
let sub_path = if expr::is_expression(&sub_path) {
// Evaluate through the shared expression seam, recording — when
// the sink carries the contextual buckets — a failure as an
// `InvalidExpression` diagnostic with the sublayer context (C++
// `_BuildLayerStack`) and the variable names the evaluation
// read. A successful expression-language `None` selects no
// sublayer and stays silent; either outcome resolves to no edge.
let mut expr_errors = Vec::new();
let mut expr_used = HashSet::new();
let record = sink.as_deref_mut().is_some_and(|s| s.contextual.is_some());
let outcome = evaluate_expression(
&sub_path,
context,
ExpressionContext::Sublayer,
&node.layer,
&root_path,
record.then_some(&mut expr_errors),
record.then_some(&mut expr_used),
);
if let Some(contextual) = sink.as_deref_mut().and_then(|s| s.contextual.as_mut()) {
contextual
.errors
.extend(expr_errors.into_iter().map(|error| (id, error)));
contextual
.used_vars
.extend(expr_used.into_iter().map(|name| (id, name)));
}
match outcome {
EvaluatedExpression::Value(resolved) => resolved,
EvaluatedExpression::None | EvaluatedExpression::Failed => continue,
}
} else {
sub_path
};
let Some(sub_id) = self.resolve_sublayer(id, &sub_path, resolution) else {
// No loaded layer at the entry's anchored (or bare) identifier:
// record a load-demand candidate for the stacks whose members
// include `id`, so the stage's load barrier can open it. An
// empty entry names nothing to open and stays skipped.
if !sub_path.is_empty() {
if let Some(sink) = sink.as_deref_mut() {
sink.demands.push((id, sub_path));
}
}
continue;
};
let ratio = parent_tcps / effective_time_codes_per_second(&self.nodes[&sub_id].layer);
let effective = offsets
.get(i)
.copied()
.unwrap_or_default()
.sanitized()
.concatenate(&LayerOffset::scale_only(ratio));
edges.push((sub_id, effective));
}
edges
}
/// Resolves an authored `subLayers` entry `sub_path` against its parent layer
/// `parent` to the interned sublayer (the memoizing form of
/// [`find_relative`](Self::find_relative) for the per-rebuild
/// [`resolve_edges`](Self::resolve_edges) walk). The anchored identifier — the
/// asset USD resolves the relative entry to — is tried first; only when no
/// layer is interned there does it fall back to the bare authored string, so a
/// filesystem-backed parent never resolves to an unrelated layer interned
/// under the bare string, while an in-memory layer keyed under that literal
/// name (no filesystem anchor) still resolves.
///
/// The anchored identifier is a pure function of the asset paths, so it is
/// memoized in `cache` whether or not it currently names an interned layer:
/// the resolver's filesystem canonicalize then runs once per `(parent,
/// sub_path)`, while the live [`id_of`](Self::id_of) below still tracks
/// interning, so a target that interns on a later rebuild is picked up without
/// re-resolving the path (see [`SublayerState::resolution`]).
fn resolve_sublayer(
&self,
parent: LayerId,
sub_path: &str,
cache: &mut HashMap<LayerId, HashMap<String, String>>,
) -> Option<LayerId> {
let sub_path = without_dot_segments(sub_path);
if let Some(anchored) = cache.get(&parent).and_then(|paths| paths.get(sub_path.as_ref())) {
return self.anchored_or_bare(anchored, &sub_path);
}
let anchored = self
.registry
.create_identifier_anchored(&sub_path, self.real_path(parent));
let sub_id = self.anchored_or_bare(&anchored, &sub_path);
cache.entry(parent).or_default().insert(sub_path.into_owned(), anchored);
sub_id
}
/// Replaces [`cycle_errors`](Self::cycle_errors) with the sublayer cycles
/// reachable from the root layer through non-muted edges. Run after an edge
/// rebuild and after a mute change, since muting a layer breaks any cycle
/// running through it.
fn recompute_cycle_errors(&mut self) {
let mut errors = Vec::new();
// Detect over the same edges the root stack's members are built from,
// one scan per region root — the session root's subtree and the root
// layer's: a region with an expression sublayer resolves against the
// stack's single variable set — the root instance's stored composed
// variables, which `rebuild_sublayer_stacks` refreshed just before this
// runs — so a `${VAR}` sublayer pointing back at an ancestor is caught;
// otherwise the context-free `children` are the region's edges.
//
// TODO(perf): a stage with an expression sublayer recomputes the stack
// edges here after `rebuild_sublayer_stacks` already resolved them for
// the members; threading the edge map through both would remove the
// duplication.
let region_roots: Vec<LayerId> = self
.session_layers()
.first()
.copied()
.into_iter()
.chain(self.root)
.collect();
for root in region_roots {
let mut ancestors: HashSet<LayerId> = HashSet::new();
if self.has_expr_sublayer(root) {
let mut resolution = mem::take(&mut self.sublayers.resolution);
let stack_vars = self.stacks.expression_variables(LayerStackId::ROOT);
let edges = self.compose_stack_edges(root, stack_vars, &mut resolution, None);
self.sublayers.resolution = resolution;
self.detect_cycles(
root,
|id| edges.get(&id).map_or(&[][..], |e| e.as_slice()),
&mut ancestors,
&mut errors,
);
} else {
let nodes = &self.nodes;
self.detect_cycles(
root,
|id| nodes.get(&id).map_or(&[][..], |n| n.children.as_slice()),
&mut ancestors,
&mut errors,
);
}
}
// A sublayer reached twice off-path (a diamond) — or from both region
// roots — can report the same cycle twice; report each physical
// `(root_layer, seen_layer)` pair once.
let mut seen = HashSet::new();
errors.retain(|error| match error {
Error::SublayerCycle { root_layer, seen_layer } => seen.insert((root_layer.clone(), seen_layer.clone())),
_ => true,
});
self.cycle_errors = errors;
}
/// Refreshes the registry's composed stacks from the current edges. Run after
/// any edge mutation so [`layer_stack`](Self::layer_stack) and its callers read
/// up-to-date members, keeping every [`LayerStackId`] stable so a handle held by
/// a surviving prim index stays valid.
///
/// The stage root stack (registry instance 0) and every already-interned target
/// stack — plain and contextual — are re-resolved in place. A reference/payload
/// target a `subLayers` edit cannot have minted yet is left for the demand path
/// ([`intern_external`](Self::intern_external)). Work stays proportional to the
/// composed stacks rather than the sum over every layer (O(n²) for a deep
/// chain): a sublayer-only layer participates through its root's stack, never its
/// own.
///
/// Returns one [`StackVarsDelta`] per stack whose composed expression
/// variables (or their source) changed, in ascending stack order — dependency
/// order, so a consumer processing them in sequence sees a source's delta
/// before the deltas it cascaded into (the C++ step-5 propagation to stacks
/// whose override source resolves here).
fn rebuild_sublayer_stacks(&mut self, affected: Option<&HashSet<LayerId>>) -> Vec<StackVarsDelta> {
// Re-resolve the muted identifiers to ids first, so a layer muted before
// it was loaded takes effect the moment a later edit interns it and
// rebuilds the stacks.
self.resolve_muted_ids();
// One delta per stack whose composed expression variables (or their
// source) changed this pass — the return value, and the membership the
// targets loop consults to cascade: a stack seeds from its key source's
// referent, so a change there must rebuild it even when the edit touched
// none of its own layers. A source referent always precedes the stacks
// keyed by it, so the single ascending-index pass below reads every seed
// after its referent was refreshed.
let mut vars_deltas: Vec<StackVarsDelta> = Vec::new();
// The stage root stack (session layers at identity offset minus a muted
// session subtree, then the root layer and its sublayers) is rebuilt on a
// full pass, or when an edited layer is one of its members — an edit
// elsewhere leaves it unchanged. A not-yet-built root (finalize) always
// rebuilds.
let rebuild_root = match affected {
None => true,
Some(affected) => self
.stacks
.member_set(LayerStackId::ROOT)
.is_none_or(|members| !members.is_disjoint(affected)),
};
if rebuild_root {
// Both regions of the stage root stack — the session root's sublayer
// subtree and the root layer's — expand against the stack's single
// composed expression-variable context (C++ `PcpExpressionVariables`):
// the root layer's own variables overlaid by the session root's own,
// the session winning, a muted session root contributing none. The
// root layer itself is never muted (the Stage API rejects it). Each
// region is a member walk from its region root, so a runtime
// `subLayers` edit or `${VAR}` re-selection re-resolves session
// membership exactly like root membership, and an unresolved entry
// in either region files a load demand through the sink.
let session_vars = self.session_expression_variables();
let stack_vars = match self.root {
Some(root) => self.composed_stack_vars(root, &session_vars),
None => session_vars,
};
let mut sink = EdgeSink::contextual();
let mut resolution = mem::take(&mut self.sublayers.resolution);
let mut root_members: Vec<(LayerId, LayerOffset)> = Vec::new();
if let Some(&session_root) = self.session_layers().first() {
root_members.extend(self.stack_members_uncached(
session_root,
&stack_vars,
&mut resolution,
Some(&mut sink),
));
}
if let Some(root) = self.root {
root_members.extend(self.stack_members_uncached(root, &stack_vars, &mut resolution, Some(&mut sink)));
}
self.sublayers.resolution = resolution;
if let Some(delta) = self.stacks.set_root(root_members, stack_vars) {
vars_deltas.push(delta);
}
self.file_stack_discoveries(LayerStackId::ROOT, sink);
}
// Re-resolve each already-interned target stack whose composition an
// edited layer can reach; a full pass (`None`) re-resolves them all. A
// target rebuilds when an edited layer is its target root (checked
// explicitly because a muted root's member set is empty — disjoint from
// everything — while its layer data still feeds the stack's composed
// variables), a member, or when its seed shifted: its key source's
// referent changed this pass. The seed is read live from that referent,
// already refreshed by this pass's ascending order.
// TODO(perf): this materializes every target instance per rebuild (the
// registry borrow must end before `build_stack_members` takes `&mut
// self`); an index-walk accessor on the registry would drop the
// allocation.
for (id, root, source) in self.stacks.targets().collect::<Vec<_>>() {
let rebuild = match affected {
None => true,
Some(affected) => {
affected.contains(&root)
|| self
.stacks
.member_set(id)
.is_some_and(|members| !members.is_disjoint(affected))
|| vars_deltas.iter().any(|delta| delta.stack == source.referent())
}
};
if !rebuild {
continue;
}
let seed_vars = self.stacks.expression_variables(source.referent()).clone();
let mut sink = EdgeSink::contextual();
let (members, expr_vars) = self.build_stack_members(root, &seed_vars, Some(&mut sink));
if let Some(delta) = self.stacks.set_composed(id, members, expr_vars) {
vars_deltas.push(delta);
}
self.file_stack_discoveries(id, sink);
}
vars_deltas
}
/// Classifies one stack composition's [`EdgeSink`] discoveries and files
/// them into the sublayer subsystem
/// ([`SublayerState::replace_stack`], which supersedes the stack's earlier
/// demands and diagnostics). Each unresolved entry becomes one of three
/// things: nothing when its parent is anonymous (nothing anchors the
/// entry, so there is no asset to open) or its target muted (membership
/// pruning would drop the opened layer right back out — the sublayer
/// analog of the indexer's muted-arc-target check; an unmute rebuilds the
/// stack, which re-derives the entry), a regenerated per-referrer
/// diagnostic when its identifier already failed to open (the barrier
/// would refuse it; an edit clears the failure and the next rebuild
/// demands again), or a demand. A resolve failure holds only while the
/// asset stays unresolvable: once the resolver finds it again, the entry
/// demands rather than reporting — the sublayer analog of the arc demand
/// gate's retry.
fn file_stack_discoveries(&mut self, stack: LayerStackId, sink: EdgeSink) {
let members = self.stacks.member_set(stack).expect("a filed stack is minted");
let (demands, mut errors, used_vars) = sink.drain(stack, members);
// The names this composition's `${VAR}` entries read replace the stack's
// recorded sublayer dependencies, superseding a fixed or removed entry's.
self.stacks.set_sublayer_var_deps(stack, used_vars);
let muted = self.has_muted_layers();
let mut pending = Vec::new();
// Canonical identifiers already reported for a parent this pass, so a
// second authored spelling of one entry reports once, like open-time
// collection.
let mut seen: HashSet<(LayerId, String)> = HashSet::new();
for demand in demands {
// An anonymous parent has no location to resolve the entry
// against; the entry stays a graph-only lookup, satisfied when a
// matching in-memory layer joins.
if self.nodes[&demand.parent].layer.is_anonymous() {
continue;
}
if muted
&& self
.muted_asset_id(&demand.evaluated, self.anchor_location(Some(demand.parent)).as_ref())
.is_some()
{
continue;
}
if !self.failed_loads.is_empty() {
// The entry's anchored identifier is in the resolution cache —
// `resolve_sublayer` filed it before reporting the entry
// unresolved. A miss falls through to a demand, whose barrier
// attempt records the same diagnostic.
let normalized = without_dot_segments(&demand.evaluated);
let anchored = self
.sublayers
.resolution
.get(&demand.parent)
.and_then(|paths| paths.get(normalized.as_ref()));
if let Some(anchored) = anchored {
let retry = matches!(self.failed_loads.get(anchored), Some(LoadFailure::Unresolved))
&& self.registry.resolve(anchored).is_some();
if retry {
self.failed_loads.remove(anchored.as_str());
} else if let Some(failure) = self.failed_loads.get(anchored) {
if seen.insert((demand.parent, anchored.clone())) {
let error = failure.sublayer_error(&demand.evaluated, self.identifier(demand.parent));
if !errors.contains(&error) {
errors.push(error);
}
}
continue;
}
}
}
pending.push(demand);
}
self.sublayers.replace_stack(stack, pending, errors);
}
/// Appends a sublayer diagnostic to `stack`'s bucket
/// ([`SublayerState::record_error`]) — the load barrier's channel for a
/// failure discovered between rebuilds.
pub(crate) fn record_sublayer_error(&mut self, stack: LayerStackId, error: Error) {
self.sublayers.record_error(stack, error);
}
/// Drains the pending [`SublayerDemand`]s the last recompose or mint
/// discovered. The stage's load barrier resolves them
/// (`Stage::resolve_sublayer_demands`), opening each demanded layer under
/// its stack's composed variables and recomposing.
pub(crate) fn take_sublayer_demands(&mut self) -> Vec<SublayerDemand> {
self.sublayers.take_demands()
}
/// The sublayer load-failure diagnostics re-derived as fresh
/// [`SublayerDemand`]s, for the stage's load barrier after an edit clears
/// the failure memo ([`clear_failed_loads`](Self::clear_failed_loads)): a
/// bucket's unresolved or malformed sublayer entry carries exactly its
/// demand's ingredients, so a repaired asset reloads even when the edit
/// itself rebuilds no stack. A retry that fails re-records the identical
/// diagnostic, so requeueing is idempotent.
pub(crate) fn requeue_failed_sublayers(&self) -> Vec<SublayerDemand> {
let mut demands = Vec::new();
for (&stack, bucket) in &self.sublayers.errors {
for error in bucket {
let (asset_path, introduced_by) = match error {
Error::UnresolvedSublayer {
asset_path,
introduced_by,
}
| Error::MalformedSublayer {
asset_path,
introduced_by,
..
} => (asset_path, introduced_by),
_ => continue,
};
let Some(parent) = self.id_of(introduced_by) else {
continue;
};
demands.push(SublayerDemand {
parent,
stack,
evaluated: asset_path.clone(),
});
}
}
demands
}
/// Mints a root-sourced stack instance for every sublayer-DAG root that lacks
/// one — a reference/payload target interned eagerly by `from_layers` rather
/// than through the demand path. The stacks are keyed `{root, Root}` and
/// seeded by the root stack's composed variables: a stack whose variable
/// source is the root composes under the root stack's set (C++
/// `PcpLayerStackIdentifier` with no explicit override source), so a
/// var-authoring stage root reaches into every such target. Run once at
/// [`finalize`](Self::finalize): a production target loads after finalize and
/// is minted by [`intern_external`](Self::intern_external) under its own
/// context, so it never reaches here, and an edit-time recompose never
/// re-mints a never-queried instance for a contextual-only target.
fn mint_eager_target_stacks(&mut self) {
let sublayered: HashSet<LayerId> = self
.order
.iter()
.flat_map(|&id| self.nodes[&id].children.iter().map(|&(child, _)| child))
.collect();
let dag_roots: Vec<LayerId> = self
.order
.iter()
.copied()
.filter(|&id| !sublayered.contains(&id) && Some(id) != self.root)
.collect();
for root in dag_roots {
self.intern_target_stack(root, VarsSource::Root);
}
}
/// Depth-first cycle scan recording [`Error::SublayerCycle`] for any edge
/// that re-enters a layer already on the path from the root. Runs on an
/// explicit work stack so a deep chain does not overflow the native stack; an
/// `Exit` frame pops the layer back out of the `ancestors` path after its
/// subtree. `children_of` supplies a layer's resolved edges — the shared
/// context-free [`LayerNode::children`], or a stack's expression-resolved edges
/// — and a sublayer diamond re-scans off-path rather than looking like a cycle.
fn detect_cycles<'e>(
&self,
root: LayerId,
children_of: impl Fn(LayerId) -> &'e [(LayerId, LayerOffset)],
ancestors: &mut HashSet<LayerId>,
errors: &mut Vec<Error>,
) {
enum Step {
Enter(LayerId),
Exit(LayerId),
}
let mut work = vec![Step::Enter(root)];
while let Some(step) = work.pop() {
let id = match step {
Step::Exit(id) => {
ancestors.remove(&id);
continue;
}
Step::Enter(id) => id,
};
ancestors.insert(id);
work.push(Step::Exit(id));
// Iterate forward to record cycle errors in declared order, gathering
// the non-cycle children; they are pushed reversed so they pop in
// declared order.
let mut to_visit = Vec::new();
for &(child, _) in children_of(id) {
// A muted child is pruned from every stack, so a cycle through it
// never composes and is not reported.
if self.is_muted(child) {
continue;
}
if ancestors.contains(&child) {
errors.push(Error::SublayerCycle {
root_layer: self.nodes[&id].layer.identifier().to_string(),
seen_layer: self.nodes[&child].layer.identifier().to_string(),
});
continue;
}
to_visit.push(child);
}
for &child in to_visit.iter().rev() {
work.push(Step::Enter(child));
}
}
}
/// Read-only access to a layer node.
pub(crate) fn get(&self, id: LayerId) -> Option<&LayerNode> {
self.nodes.get(&id)
}
/// Mutable access to a layer node, for routed authoring writes.
pub(crate) fn get_mut(&mut self, id: LayerId) -> Option<&mut LayerNode> {
self.nodes.get_mut(&id)
}
/// Borrow the layers named by `ids` together, in `ids` order, skipping any
/// id with no live layer. Used to open a transaction on each layer of a
/// batched edit so they commit all-or-nothing.
pub(crate) fn layers_mut(&mut self, ids: &[LayerId]) -> Vec<(LayerId, &mut sdf::Layer)> {
let want: HashSet<LayerId> = ids.iter().copied().collect();
let mut by_id: HashMap<LayerId, &mut sdf::Layer> = self
.nodes
.iter_mut()
.filter(|(id, _)| want.contains(id))
.map(|(id, node)| (*id, &mut node.layer))
.collect();
ids.iter()
.filter_map(|id| by_id.remove(id).map(|layer| (*id, layer)))
.collect()
}
/// The layer with the given id. Panics if the id is unknown.
pub(crate) fn layer(&self, id: LayerId) -> &sdf::Layer {
&self.nodes[&id].layer
}
/// The identifier of the layer with the given id. Panics if unknown.
pub(crate) fn identifier(&self, id: LayerId) -> &str {
self.nodes[&id].layer.identifier()
}
/// The resolved physical location of the layer with the given id — the
/// anchor for the relative asset paths it authors (C++
/// `SdfLayer::GetRealPath`). Equals the identifier except for a package,
/// whose real path is its package-relative default layer. Panics if
/// unknown.
pub(crate) fn real_path(&self, id: LayerId) -> &str {
self.nodes[&id].layer.real_path()
}
/// Whether a layer with this id is present.
pub(crate) fn contains(&self, id: LayerId) -> bool {
self.nodes.contains_key(&id)
}
/// The registry that opens reference/payload targets on demand.
pub(crate) fn layer_registry(&self) -> &sdf::LayerRegistry {
&self.registry
}
/// The location that anchors the relative asset paths authored in the layer
/// `anchor`: its resolved [`real_path`](Self::real_path), recorded when the
/// loader opened it. Returns `None` when there is no anchor layer or it is
/// anonymous (no resolvable location, C++ `SdfLayer::GetRealPath` is
/// empty).
pub(crate) fn anchor_location(&self, anchor: Option<LayerId>) -> Option<ResolvedPath> {
let layer = &self.nodes[&anchor?].layer;
(!layer.is_anonymous()).then(|| ResolvedPath::new(layer.real_path()))
}
/// Records that an on-demand open of `asset_path` failed, so composition
/// stops demanding it and reports it — [`MalformedLayer`](Error::MalformedLayer)
/// at a reference/payload arc, a per-referrer sublayer diagnostic at each
/// stack rebuild. Called from the stage's load barriers.
pub(crate) fn mark_load_failed(&mut self, asset_path: &str, failure: LoadFailure) {
self.failed_loads.insert(asset_path.to_string(), failure);
}
/// The layer stack a reference/payload arc to external `root` should compose
/// against, given the arc-carrying stack `context`. Every target stack is
/// keyed by the source of the arc-carrying stack's composed expression
/// variables (C++ `primIndex.cpp` builds the target identifier from
/// `GetExpressionVariables().GetSource()`), so this is a plain
/// `(root, source)` lookup on its interned id. Read-only: the indexer runs
/// against `&LayerGraph` and cannot mint, so a not-yet-built stack returns
/// [`ExternalStack::Demand`] for the load barrier to resolve through
/// [`intern_external`](Self::intern_external).
pub(crate) fn external_stack_id(&self, root: LayerId, context: LayerStackId) -> ExternalStack {
self.resolve_target_stack(root, self.stacks.vars_source(context))
}
/// The `(root, source)` resolve policy shared by the read path
/// ([`external_stack_id`](Self::external_stack_id)) and the mint path
/// ([`intern_target_stack`](Self::intern_target_stack)): collapse to the
/// root stack when the identity is the root stack's own
/// ([`collapses_to_root`](Self::collapses_to_root)), else the interned
/// `(root, source)` instance, else [`ExternalStack::Demand`].
fn resolve_target_stack(&self, root: LayerId, source: VarsSource) -> ExternalStack {
if self.collapses_to_root(root, source) {
return ExternalStack::Ready(LayerStackId::ROOT);
}
match self.stacks.lookup_target(root, source) {
Some(id) => ExternalStack::Ready(id),
None => ExternalStack::Demand,
}
}
/// Whether an arc to `root` under the variable source `source` composes
/// against the stage root stack itself — pure key equality with the root
/// stack's identity (C++ `PcpLayerStackIdentifier` with the root's null
/// override source): the target is the stage root layer, no session layers
/// separate the two, and the variables' source is the root. A carried
/// [`VarsSource::Instance`] — a back-reference through a stack that authored
/// its own variables — instead mints a contextual instance rooted at the
/// stage root layer, keeping the outer variables in force.
fn collapses_to_root(&self, root: LayerId, source: VarsSource) -> bool {
self.session_layer_count == 0 && self.root == Some(root) && source == VarsSource::Root
}
/// Builds and interns the layer stack for a reference/payload arc to `root`
/// demanded under the context of the stack `context` (the `&mut self`
/// counterpart to [`external_stack_id`](Self::external_stack_id)), returning
/// its handle and whether a new instance was created so the load barrier can
/// drive a re-run. Idempotent. Called from the load barrier once the target
/// and the sublayers its context resolves have been interned.
pub(crate) fn intern_external(&mut self, root: LayerId, context: LayerStackId) -> (LayerStackId, bool) {
self.intern_target_stack(root, self.stacks.vars_source(context))
}
/// Whether the load barrier must (re)open `root`'s sublayers for a
/// reference/payload demanded under the context of the stack `context`: the
/// inherited context selects a contextual stack that is not yet built, so its
/// `${VAR}` sublayers — possibly nested below a literal sublayer an earlier
/// context left unopened — need loading. A context-free arc, a target with no
/// `${VAR}` sublayer (a keying-only demand the barrier interns without
/// reloading), or a context already built needs no reopen.
///
/// The stage's own root layer is never reopened: its stack is already loaded,
/// and the layer may be in-memory or carry unsaved edits a disk re-read would
/// discard. A back-reference to it interns from the loaded graph, and any
/// `${VAR}` sublayer its carried context newly selects loads through the
/// mint's [`SublayerDemand`]s instead.
//
// TODO: retire this whole-tree reopen in favor of `SublayerDemand` coverage —
// the demand-driven loader opens a context's unresolved selections
// individually (nested-below-literal ones converge across recompose rounds),
// which should make the reload redundant once that coverage is proven.
pub(crate) fn needs_contextual_open(&self, root: LayerId, context: LayerStackId) -> bool {
self.root != Some(root)
&& !self.stacks.expression_variables(context).is_empty()
&& self.has_expr_sublayer(root)
&& matches!(self.external_stack_id(root, context), ExternalStack::Demand)
}
/// The value identity of the stack `id`, for capture into an arc-based edit
/// target: the root stack as [`StackIdentity::Root`], a target stack as its
/// root's identifier plus its variable source chain's identifiers, walked
/// key source by key source down to the root stack and reversed to
/// outermost-first.
pub(crate) fn stack_identity(&self, id: LayerStackId) -> StackIdentity {
let Some((root, mut source)) = self.stacks.target_key(id) else {
return StackIdentity::Root;
};
let mut chain = Vec::new();
while let VarsSource::Instance(referent) = source {
let (referent_root, next) = self
.stacks
.target_key(referent)
.expect("a canonical source referent is a target stack");
chain.push(referent_root);
source = next;
}
chain.reverse();
StackIdentity::Target {
root: self.identifier(root).to_string(),
source_chain: self.identifiers_of(chain),
}
}
/// Resolves a captured [`StackIdentity`] to a stack handle on this graph,
/// walking the source chain outside-in so the same content derives the same
/// source-keyed identities the capturing graph held — including on a
/// different stage with equal composition inputs, where the numeric handles
/// number differently.
///
/// Read-only, like the arc path: the first chain element whose layer is not
/// loaded or whose stack is not yet composed comes back as `Err` with the
/// [`Demand`] the load barrier must satisfy, and the caller re-runs the
/// walk after each load until it resolves or loading stops progressing.
/// Minting is left to the barrier so a `${VAR}`-selected sublayer the
/// context resolves is opened before the stack is interned (the barrier's
/// contextual-open check), and a walk that ultimately fails interns
/// nothing.
pub(crate) fn resolve_stack_identity(&self, identity: &StackIdentity) -> Result<LayerStackId, Demand> {
let StackIdentity::Target { root, source_chain } = identity else {
return Ok(LayerStackId::ROOT);
};
let mut context = LayerStackId::ROOT;
for identifier in source_chain.iter().chain([root]) {
let stack = self
.id_of(identifier)
.map(|layer| self.external_stack_id(layer, context));
let Some(ExternalStack::Ready(id)) = stack else {
return Err(Demand {
asset_path: identifier.clone(),
context,
});
};
context = id;
}
Ok(context)
}
/// The single mint policy for an external target stack: resolve through the
/// shared policy ([`resolve_target_stack`](Self::resolve_target_stack)) and,
/// on [`ExternalStack::Demand`], compose the members and variables under the
/// source referent's composed set and intern a fresh instance. Distinct
/// sources to the same target intern distinct instances even when their
/// composed maps and members are equal — the source is the identity, so
/// sharing would collapse sites C++ keeps apart.
fn intern_target_stack(&mut self, root: LayerId, source: VarsSource) -> (LayerStackId, bool) {
if let ExternalStack::Ready(id) = self.resolve_target_stack(root, source) {
return (id, false);
}
let seed_vars = self.stacks.expression_variables(source.referent()).clone();
// A mint can itself discover unloaded selections — a `${VAR}` sublayer
// the fresh context resolves to a layer nothing else has opened — so it
// files demands like a rebuild does.
let mut sink = EdgeSink::contextual();
let (members, expr_vars) = self.build_stack_members(root, &seed_vars, Some(&mut sink));
let id = self.stacks.intern_target(root, source, members, expr_vars);
self.file_stack_discoveries(id, sink);
(id, true)
}
/// Whether any layer in `root`'s plain sublayer subtree authors an
/// expression-valued `${VAR}` `subLayers` entry — the only sublayer whose
/// resolution depends on the expression-variable context inherited across a
/// reference/payload arc. The load barrier reads this to decide whether a
/// demanded context must (re)open the target's sublayers
/// ([`needs_contextual_open`](Self::needs_contextual_open)), and
/// [`stack_members_uncached`](Self::stack_members_uncached) to gate a stack
/// onto the context-free `collect_plain` fast path. The whole subtree is
/// scanned so an expression sublayer nested below the target root — under a
/// literal sublayer — is still caught.
///
/// The walk reads the current [`LayerNode::children`] rather than a registry
/// stack's interned members: those members can predate the edit driving a stack
/// rebuild (they are replaced only after every stack is recomposed), so scanning
/// them would miss a freshly added expression branch and wrongly gate the stack
/// onto `collect_plain`. The children (and the per-node flags) are already
/// rebuilt by [`build_sublayer_edges`](Self::build_sublayer_edges) before the
/// rebuild reads this. Muted layers (and any subtree reached only through them)
/// are skipped, matching the composed members: an expression sublayer that
/// mutes out contributes nothing, so a demand for a target that only reaches
/// one skips the reopen. [`SublayerState::any_expr`] short-circuits the
/// common stage with no expression sublayer at all to `O(1)`.
//
// TODO(perf): this runs a fresh subtree walk (allocating a work stack + visited
// set) per empty-seed stack rebuilt in `rebuild_sublayer_stacks` once any layer
// authors an expression sublayer. A transitive per-node "subtree authors one"
// flag computed with the local flags would make it an `O(1)` field read.
pub(crate) fn has_expr_sublayer(&self, root: LayerId) -> bool {
if !self.sublayers.any_expr {
return false;
}
let mut work = vec![root];
let mut visited = HashSet::new();
while let Some(id) = work.pop() {
if self.is_muted(id) || !visited.insert(id) {
continue;
}
let Some(node) = self.nodes.get(&id) else { continue };
if node.has_expr_sublayer {
return true;
}
work.extend(node.children.iter().map(|&(child, _)| child));
}
false
}
/// Recomputes the exact [`LayerNode::has_expr_sublayer`] flags and their
/// graph-level union [`SublayerState::any_expr`] from each
/// layer's own `subLayers`. Run on every edge rebuild so an edit that adds or
/// removes the last expression `subLayers` entry is reflected exactly.
//
// TODO(perf): this re-decodes each layer's `subLayers`, which `resolve_edges`
// already decodes (and already runs `is_expression` over) in the same
// `build_sublayer_edges` pass. Returning the flag from `resolve_edges` and
// folding it in as `children` are applied would drop this second decode.
fn recompute_expr_sublayer_flags(&mut self) {
let root_path = Path::abs_root();
let mut any = false;
for node in self.nodes.values_mut() {
let has = matches!(
node.layer.data().get_field(&root_path, FieldKey::SubLayers.as_str()),
Ok(subs) if matches!(&*subs, Value::StringVec(paths) if paths.iter().any(|p| expr::is_expression(p)))
);
node.has_expr_sublayer = has;
any |= has;
}
self.sublayers.any_expr = any;
}
/// The cached composer for a rebuild: composes the stack's expression
/// variables ([`composed_stack_vars`](Self::composed_stack_vars)), then
/// expands members against them via the [`stack_members_uncached`] policy
/// with the graph's shared sublayer-resolution cache threaded through, so a
/// `subLayers` edit only re-canonicalizes paths it has not seen before.
/// Returns both so the caller stores them on the stack instance together.
/// Read-only queries call [`stack_members_uncached`] directly with a scratch
/// cache ([`sublayer_stack`]).
///
/// [`stack_members_uncached`]: Self::stack_members_uncached
/// [`sublayer_stack`]: Self::sublayer_stack
fn build_stack_members(
&mut self,
root: LayerId,
seed_vars: &HashMap<String, Value>,
sink: Option<&mut EdgeSink>,
) -> (Vec<(LayerId, LayerOffset)>, HashMap<String, Value>) {
let stack_vars = self.composed_stack_vars(root, seed_vars);
let mut resolution = mem::take(&mut self.sublayers.resolution);
let members = self.stack_members_uncached(root, &stack_vars, &mut resolution, sink);
self.sublayers.resolution = resolution;
(members, stack_vars)
}
/// The composed expression variables of a stack rooted at `root` under
/// `seed_vars`: the root layer's own `expressionVariables` overlaid by the
/// seed, the seed winning (C++ `PcpExpressionVariables`). The loader
/// validated the `expressionVariables` read at open time; this
/// composition-time read of the same already-loaded layer cannot abort, so
/// an unreadable field degrades to no variables.
fn composed_stack_vars(&self, root: LayerId, seed_vars: &HashMap<String, Value>) -> HashMap<String, Value> {
expr::stack_expression_variables(self.nodes[&root].layer.data(), seed_vars).unwrap_or_default()
}
/// The single member-expansion policy for every "stack rooted at `root` under
/// the composed variables `stack_vars`" query, cached
/// ([`build_stack_members`](Self::build_stack_members)) or on demand
/// ([`sublayer_stack`](Self::sublayer_stack)): resolves `root`'s subtree and
/// composes offsets, pruning muted layers, sharing [`collect_sublayers`].
///
/// A stack with no expression sublayer ([`has_expr_sublayer`](Self::has_expr_sublayer)
/// false) walks the shared context-free [`LayerNode::children`], resolved once
/// per `subLayers` edit. A stack with one re-resolves its subtree against
/// `stack_vars` ([`compose_stack_edges`](Self::compose_stack_edges)) so every
/// `${VAR}` sublayer resolves the same way throughout the stack (C++
/// `PcpExpressionVariables`). `resolution` memoizes sublayer path
/// canonicalization — the graph's cache on a rebuild, a scratch map on a read
/// query.
fn stack_members_uncached(
&self,
root: LayerId,
stack_vars: &HashMap<String, Value>,
resolution: &mut HashMap<LayerId, HashMap<String, String>>,
sink: Option<&mut EdgeSink>,
) -> Vec<(LayerId, LayerOffset)> {
if !self.has_expr_sublayer(root) {
let members = self.collect_plain(root);
// A plain stack's edges are the context-free ones, so its
// unresolved entries are exactly the recorded per-parent table;
// scanning the members costs nothing on the common fully-resolved
// stage, where the table is empty.
if let Some(sink) = sink.filter(|_| !self.sublayers.unresolved_plain.is_empty()) {
for &(member, _) in &members {
if let Some(entries) = self.sublayers.unresolved_plain.get(&member) {
sink.demands
.extend(entries.iter().map(|evaluated| (member, evaluated.clone())));
}
}
}
return members;
}
let edges = self.compose_stack_edges(root, stack_vars, resolution, sink);
let muted = &self.muted;
let mut members = Vec::new();
let mut ancestors = HashSet::new();
collect_sublayers(
root,
LayerOffset::IDENTITY,
&mut members,
&mut ancestors,
|id| muted.contains(&id),
|id| edges.get(&id).map_or(&[][..], |e| e.as_slice()),
);
members
}
/// Resolves the sublayer edges of the stack rooted at `root` against
/// `stack_vars`, the stack's single composed expression-variable set, into a
/// per-`LayerId` edge map. Every `${VAR}` sublayer in the stack resolves
/// against that one set (C++ `PcpExpressionVariables`); a sublayer's own
/// `expressionVariables` contribute nothing. Unlike the shared context-free
/// [`LayerNode::children`], these edges carry the stack's variables.
/// `resolution` memoizes sublayer path canonicalization.
fn compose_stack_edges(
&self,
root: LayerId,
stack_vars: &HashMap<String, Value>,
resolution: &mut HashMap<LayerId, HashMap<String, String>>,
mut sink: Option<&mut EdgeSink>,
) -> HashMap<LayerId, SublayerEdges> {
let mut edges: HashMap<LayerId, SublayerEdges> = HashMap::new();
let mut visited: HashSet<LayerId> = HashSet::new();
let mut work = vec![root];
while let Some(id) = work.pop() {
if !visited.insert(id) {
continue;
}
let resolved = self.resolve_edges(id, stack_vars, resolution, sink.as_deref_mut());
for &(child, _) in resolved.iter().rev() {
work.push(child);
}
edges.insert(id, resolved);
}
edges
}
/// The session layer's own `expressionVariables` — the overrides the root stage
/// stack composes over the stage root layer's own (C++ `PcpExpressionVariables`
/// reads the root and session layers, not their sublayers). Seeds the root
/// layer's `${VAR}` sublayer resolution (see
/// [`rebuild_sublayer_stacks`](Self::rebuild_sublayer_stacks)). Empty when the
/// session root authors none, the common case that keeps the root on the
/// sessionless path.
///
/// The session root is the first session layer; a muted session root contributes
/// nothing, matching the members the root stack drops. The session root is
/// `order[0]`, the top of the session region, so muting drops it exactly when it
/// is itself muted.
fn session_expression_variables(&self) -> HashMap<String, Value> {
match self.session_layers().first() {
Some(&session_root) if !self.is_muted(session_root) => {
expr::read_expression_variables(self.nodes[&session_root].layer.data())
.map(|dict| dict.into_owned())
.unwrap_or_default()
}
_ => HashMap::new(),
}
}
/// The stage root stack's expression variables read regardless of muting: the
/// stage root layer's own overlaid by the session root's own (session wins). The
/// structural walk [`expression_ancestry_edges`](Self::expression_ancestry_edges)
/// resolves the root stage stack's `${VAR}` sublayers against this one set (both
/// regions of a single stack, C++ `PcpExpressionVariables`), so muting a layer
/// leaves the walk's edges unchanged: the ancestor set is identical before a mute
/// and after the matching unmute. The composition context a muted session root
/// drops out of is [`stack_expression_variables`](Self::stack_expression_variables).
fn root_stack_structural_vars(&self) -> HashMap<String, Value> {
let session = match self.session_layers().first() {
Some(&session_root) => expr::read_expression_variables(self.nodes[&session_root].layer.data())
.map(|dict| dict.into_owned())
.unwrap_or_default(),
None => HashMap::new(),
};
match self.root {
Some(root) => {
expr::stack_expression_variables(self.nodes[&root].layer.data(), &session).unwrap_or_default()
}
None => session,
}
}
/// The composed expression variables of the layer stack `id` (C++
/// `PcpExpressionVariables`, stored on the stack like C++
/// `PcpLayerStack::GetExpressionVariables`): its root layer's own
/// `expressionVariables` overlaid by the inherited overrides — the arc's seed
/// for a target, the session root's own for the stage root stack. This is the
/// single set the stack's `${VAR}` sublayer paths, reference/payload asset
/// paths, and value-time asset attributes all resolve against; a sublayer of
/// the root contributes nothing. The same value the stack's members were
/// resolved with ([`build_stack_members`](Self::build_stack_members)), so
/// membership and asset-path resolution never diverge. Panics on an unminted
/// handle — composition only reads stacks the graph has built.
pub(crate) fn stack_expression_variables(&self, id: LayerStackId) -> &HashMap<String, Value> {
self.stacks.expression_variables(id)
}
/// The context-free members of the stack rooted at `root`, composing offsets and
/// pruning muted layers over the shared [`LayerNode::children`]. The fast path
/// [`stack_members_uncached`](Self::stack_members_uncached) takes when the stack
/// has no expression sublayer ([`has_expr_sublayer`](Self::has_expr_sublayer)).
fn collect_plain(&self, root: LayerId) -> Vec<(LayerId, LayerOffset)> {
let muted = &self.muted;
let nodes = &self.nodes;
let mut members = Vec::new();
let mut ancestors = HashSet::new();
collect_sublayers(
root,
LayerOffset::IDENTITY,
&mut members,
&mut ancestors,
|id| muted.contains(&id),
|id| nodes.get(&id).map_or(&[][..], |n| n.children.as_slice()),
);
members
}
/// Whether a prior on-demand open of `asset_path` failed.
pub(crate) fn load_failed(&self, asset_path: &str) -> bool {
self.failed_loads.contains_key(asset_path)
}
/// What a prior on-demand open of `asset_path` recorded as its failure, or
/// `None` if it never failed.
pub(crate) fn load_failure(&self, asset_path: &str) -> Option<&LoadFailure> {
self.failed_loads.get(asset_path)
}
/// Forgets every recorded load failure so a now-readable asset is demanded
/// again, returning whether any were recorded. Called when an edit changes
/// the layers.
pub(crate) fn clear_failed_loads(&mut self) -> bool {
if self.failed_loads.is_empty() {
return false;
}
self.failed_loads.clear();
true
}
/// Whether any layer keeps structurally valid authored relocates.
pub(crate) fn has_relocates(&self) -> bool {
self.has_relocates
}
/// Number of layers in the graph.
pub(crate) fn len(&self) -> usize {
self.nodes.len()
}
/// Whether the graph has no layers.
#[allow(dead_code)]
pub(crate) fn is_empty(&self) -> bool {
self.nodes.is_empty()
}
/// Number of session layers.
pub(crate) fn session_layer_count(&self) -> usize {
self.session_layer_count
}
/// The open-time session-layer ids in strength order; the session root is
/// first. The session region's composed membership is a sublayer walk from
/// that root (see `rebuild_sublayer_stacks`), so a session sublayer loaded
/// at runtime is a root-stack member without appearing here.
pub(crate) fn session_layers(&self) -> &[LayerId] {
&self.order[..self.session_layer_count]
}
/// The root layer's id (the first non-session layer), if any.
pub(crate) fn root_id(&self) -> Option<LayerId> {
self.root
}
/// The root layer (the first non-session layer), if any. Per spec 12.2.7,
/// pseudo-root layer metadata resolves from this layer alone.
pub(crate) fn root_layer(&self) -> Option<&sdf::Layer> {
self.root.map(|id| self.layer(id))
}
/// All layer ids in collection order (session layers first).
pub(crate) fn all_ids(&self) -> &[LayerId] {
&self.order
}
/// Layer identifiers in collection order (root-stack first).
pub(crate) fn identifiers(&self) -> Vec<String> {
self.identifiers_of(self.order.iter().copied())
}
/// Maps a sequence of layer ids to their identifiers, in order.
pub(crate) fn identifiers_of(&self, ids: impl IntoIterator<Item = LayerId>) -> Vec<String> {
ids.into_iter().map(|id| self.identifier(id).to_string()).collect()
}
/// The identifiers of the stage's root layer stack (session layers, the root
/// layer, and its sublayers) in strength order. Backs C++
/// `UsdStage::GetLayerStack`.
pub(crate) fn root_layer_stack_identifiers(&self) -> Vec<String> {
self.identifiers_of(self.root_layer_stack().iter().map(|&(id, _)| id))
}
/// The layer ids + effective offsets of the root-sourced sublayer stack rooted
/// at `root_layer` (spec 10.3.1.1) — its sublayer edges resolved under the
/// layer's own `expressionVariables` overlaid by the stage root stack's
/// composed set (a stack with no explicit override source composes under the
/// root's, C++ `PcpExpressionVariables`), the depth-first pre-order walk with
/// offsets composed through nested sublayers. A layer that sublayers itself
/// transitively is a cycle and is skipped; an off-path duplicate is expanded
/// again. Empty for an unknown layer.
///
/// The query goes through the same expansion policy as a rebuilt stack
/// ([`stack_members_uncached`](Self::stack_members_uncached)): it reads the
/// registry's interned `{root_layer, Root}` instance when one exists, and
/// otherwise composes on demand with a scratch resolution cache — so a
/// sublayer diamond whose shared layer resolves `${VAR}` differently per arm
/// expands per ancestry here exactly as it does in the interned members. A
/// variable a layer inherits only from a parent that sublayers it is not in
/// scope — those members appear in the parent's stack, not in the layer's own.
pub(crate) fn sublayer_stack(&self, root_layer: LayerId) -> Cow<'_, [(LayerId, LayerOffset)]> {
if let Some(id) = self.stacks.lookup_target(root_layer, VarsSource::Root) {
return Cow::Borrowed(self.stacks.members(id));
}
if !self.nodes.contains_key(&root_layer) {
return Cow::Borrowed(&[]);
}
// Only a `${VAR}` sublayer reads the stack's variables — the layer's own
// seeded by the root stack's composed set; the plain fast path never
// touches them. A true `has_expr_sublayer` implies an edge build ran,
// which minted the root stack first, so its composed set is present.
let stack_vars = if self.has_expr_sublayer(root_layer) {
let seed = self.stacks.expression_variables(LayerStackId::ROOT);
self.composed_stack_vars(root_layer, seed)
} else {
HashMap::new()
};
let mut resolution = HashMap::new();
Cow::Owned(self.stack_members_uncached(root_layer, &stack_vars, &mut resolution, None))
}
/// The stage's root layer stack (registry instance 0): session layers (identity
/// offset) followed by the root layer and its sublayers with their effective
/// offsets (spec 10.3.1). The set of layers a top-level prim index scans for
/// local opinions.
pub(crate) fn root_layer_stack(&self) -> &[(LayerId, LayerOffset)] {
self.stacks.members(LayerStackId::ROOT)
}
/// The handle for the stage root layer stack, the ambient a top-level prim
/// composes against.
pub(crate) fn root_layer_stack_id(&self) -> LayerStackId {
LayerStackId::ROOT
}
/// Resolves a [`LayerStackId`] back to its members (the `(layer id, effective
/// offset)` pairs in strength order) from the registry. Empty for a stack whose
/// root is unknown or muted.
pub(crate) fn layer_stack(&self, id: LayerStackId) -> &[(LayerId, LayerOffset)] {
self.stacks.members(id)
}
/// The strongest (representative) layer of the stack `id` — its
/// [`layer_stack`](Self::layer_stack)'s first member — or [`LayerId::INVALID`]
/// when the stack is empty (an unknown or muted root).
pub(crate) fn layer_stack_root(&self, id: LayerStackId) -> LayerId {
self.stacks
.members(id)
.first()
.map(|&(li, _)| li)
.unwrap_or(LayerId::INVALID)
}
/// The layer ids of the stage's root layer stack, as a set (C++ "local"
/// layers, spec 12.3.4.5). Opinions from these outrank value-clip data.
pub(crate) fn local_layers(&self) -> HashSet<LayerId> {
self.stacks.member_set(LayerStackId::ROOT).cloned().unwrap_or_default()
}
/// Rebuilds the sublayer edges and relocate data from the current layer
/// data, refreshing both [`cycle_errors`](Self::cycle_errors) and
/// [`relocate_errors`](Self::relocate_errors). Called after a
/// `subLayers`/`subLayerOffsets` edit, where the graph's edges may be stale.
///
/// `edited` names the layers whose root metadata the edit authored; together
/// with the edges the rebuild finds changed, it scopes the stack re-resolution
/// to the instances the change can affect. Pass `None` for a load, where a
/// newly opened layer can join a stack the changed-edge set cannot name, so
/// every stack is re-resolved.
///
/// Returns the affected layer set the caller drops cached indices against — the
/// layers whose composed edges shifted (unioned with `edited`) plus those whose
/// relocate pairs changed, so eviction covers exactly the stacks the rebuild
/// re-resolved; empty when `edited` is `None` apart from the relocate set (a
/// full pass scopes nothing) — together with the [`StackVarsDelta`]s the stack
/// rebuild emitted, which only an `expressionVariables` edit's change
/// processing consumes.
pub(crate) fn recompute_sublayers(&mut self, edited: Option<&HashSet<LayerId>>) -> SublayerRecompute {
let (affected, vars_deltas) = self.build_sublayer_edges(edited);
let mut affected = affected.unwrap_or_default();
affected.extend(self.recompute_relocates());
SublayerRecompute { affected, vars_deltas }
}
/// The variable names whose value differs between the interned
/// expression-variable contexts `old` and `new` — how change processing
/// resolves a [`StackVarsDelta`]'s before/after pair into the C++
/// changed-name predicate
/// (`PcpChanges::_DidChangeLayerStackExpressionVariables`).
pub(crate) fn changed_var_names(&self, old: ExprVarId, new: ExprVarId) -> HashSet<String> {
self.stacks.changed_var_names(old, new)
}
/// The variable names the stack's `${VAR}` `subLayers` entries read when its
/// members were last composed. A variable edit hitting one of these can swap
/// the stack's membership, so change processing treats it as significant for
/// every prim using the stack (C++ `GetExpressionVariableDependencies`).
pub(crate) fn stack_sublayer_var_deps(&self, id: LayerStackId) -> &HashSet<String> {
self.stacks.sublayer_var_deps(id)
}
/// Re-derives every node's structurally valid relocate pairs from its
/// current layer data, replacing [`relocate_errors`](Self::relocate_errors)
/// with the recoverable relocate diagnostics (C++
/// `PcpErrorInvalidAuthoredRelocates` and conflict diagnostics). Run once at
/// construction and again whenever a `subLayers`/`layerRelocates` edit
/// lands.
///
/// Returns the layers whose cached relocate pairs changed, so a mute toggle
/// can fan out to the prims reading them (see
/// [`recompose_for_mute_with_fanout`](Self::recompose_for_mute_with_fanout))
/// without a separate before/after snapshot. Validation reads only authored
/// layer data, so each layer's new pairs are moved out of `relocates` into
/// the node cache.
pub(crate) fn recompute_relocates(&mut self) -> HashSet<LayerId> {
let (mut relocates, errors) = validate_layer_relocates(self);
self.has_relocates = false;
let mut changed = HashSet::new();
for &id in &self.order {
let pairs = relocates.remove(&id).unwrap_or_default();
self.has_relocates |= !pairs.is_empty();
let node = self.nodes.get_mut(&id).expect("layer node exists");
if node.relocates != pairs {
changed.insert(id);
}
node.relocates = pairs;
}
self.relocate_errors = errors;
changed
}
/// The current layer-graph diagnostics — sublayer cycles
/// ([`cycle_errors`](Self::cycle_errors)), relocate errors
/// ([`relocate_errors`](Self::relocate_errors)), then per-stack sublayer
/// errors ([`SublayerState::errors`]). Always reflects the
/// present graph state: a fixed cycle, relocate, expression, or removed
/// entry stops appearing and a recompute never duplicates one, since each
/// bucket is replaced on rebuild.
pub(crate) fn errors(&self) -> Vec<Error> {
let mut errors: Vec<Error> = self.cycle_errors.iter().chain(&self.relocate_errors).cloned().collect();
// A parent composing into several stacks derives the same per-referrer
// diagnostic into each stack's bucket; report each distinct diagnostic
// once.
for error in self.sublayers.diagnostics() {
if !errors.contains(error) {
errors.push(error.clone());
}
}
errors
}
/// The ordered layer-id stacks, one per sublayer stack (one rooted at each
/// layer) plus the stage root stack. Used to scope relocate conflicts and
/// duplicate-source strength to a single layer stack (C++
/// `Pcp_ComputeRelocationsForLayerStack`).
pub(crate) fn relocate_conflict_scopes(&self) -> Vec<Vec<LayerId>> {
let mut scopes: Vec<Vec<LayerId>> = self
.order
.iter()
.map(|&id| self.sublayer_stack(id).iter().map(|&(layer, _)| layer).collect())
.collect();
scopes.push(self.root_layer_stack().iter().map(|&(id, _)| id).collect());
scopes
}
/// The relocation source for `target` if a layer in `ambient` relocates a
/// prim onto it (C++ `GetIncrementalRelocatesTargetToSource`). The strongest
/// layer wins a collision; a deletion relocate has no target and is skipped.
pub(crate) fn relocation_source(&self, ambient: LayerStackId, target: &Path) -> Option<Path> {
self.incremental_relocate_entries(ambient)
.into_iter()
.find_map(|(source, relocate_target, _)| {
(!relocate_target.is_empty() && relocate_target == *target).then_some(source)
})
}
/// The relocation [`MapFunction`] applying at `path` in the layer stack
/// `ambient` (C++ `PcpLayerStack::GetExpressionForRelocatesAtPath`): every
/// relocate whose source lies at or below `path`, chained, plus the `(/, /)`
/// identity catch-all. `None` when no relocate affects `path`. `exclude_source`
/// drops the relocate whose source is exactly that path.
pub(crate) fn relocates_expression_at(
&self,
ambient: LayerStackId,
path: &Path,
exclude_source: Option<&Path>,
) -> Option<MapFunction> {
let mut pairs: Vec<(Path, Path)> = self
.combined_relocates(ambient)
.into_iter()
.filter(|(source, target)| !target.is_empty() && source.has_prefix(path) && Some(source) != exclude_source)
.collect();
if pairs.is_empty() {
return None;
}
pairs.push((Path::abs_root(), Path::abs_root()));
Some(MapFunction::new(pairs))
}
/// The stack-effective relocates of `ambient`, strongest layer first, after
/// duplicate-source and conflict dropping (C++ `GetIncrementalRelocates*`).
/// Not chained.
fn incremental_relocate_entries(&self, ambient: LayerStackId) -> Vec<(Path, Path, LayerId)> {
let mut entries: Vec<(Path, Path, LayerId)> = Vec::new();
for &(layer, _) in self.layer_stack(ambient).iter() {
let Some(node) = self.nodes.get(&layer) else {
continue;
};
for (source, target) in &node.relocates {
entries.push((source.clone(), target.clone(), layer));
}
}
let pairs: RelocateList = entries
.iter()
.map(|(source, target, _)| (source.clone(), target.clone()))
.collect();
let status = analyze_relocate_occurrences(&pairs);
entries
.into_iter()
.zip(status)
.filter_map(|(entry, status)| status.is_active().then_some(entry))
.collect()
}
/// Chains the per-layer authored relocates of `ambient` into a single
/// source→target map (C++ `GetRelocatesSourceToTarget`): a target that is
/// itself a relocation source follows on to the final target, and a relocate
/// authored *under* another's target contributes a combined
/// pre-relocation-source → final-target pair so a single map application
/// reaches the final location through nested relocates.
pub(crate) fn combined_relocates(&self, ambient: LayerStackId) -> RelocateList {
let mut pairs: RelocateList = self
.incremental_relocate_entries(ambient)
.into_iter()
.map(|(source, target, _)| (source, target))
.collect();
let snapshot = pairs.clone();
for (source, target) in pairs.iter_mut() {
if target.is_empty() {
continue;
}
*target = chain_through_relocates(target, &snapshot, Some(source));
}
// Nested relocates: a relocate `s2 → t2` whose source `s2` lies under
// another's target `t1` (from `s1 → t1`) means content moved to `t1` is
// moved on. Express that as a pair from the pre-relocation source
// (`s1` + the suffix of `s2` below `t1`) straight to `t2`, so one map
// application covers the whole chain. Iterated to a fixpoint over chains
// of any depth; bounded by the relocate count.
// TODO(perf): this is O(relocates⁴) with the linear `.any` membership
// scans (a `HashSet<Path>` of seen sources would cut it); relocate counts
// are tiny in practice, and the per-ambient cache TODO at
// `IndexCache::compose_property_paths` would amortize it away.
for _ in 0..pairs.len() {
let mut added: Vec<(Path, Path)> = Vec::new();
for (s1, t1) in &pairs {
if t1.is_empty() {
continue;
}
for (s2, t2) in &pairs {
if s2 == s1 {
continue;
}
let Some(combined) = s2.replace_prefix(t1, s1) else {
continue;
};
// `combined == s2` is already excluded by the `pairs`
// membership check (`s2` is in `pairs`).
if !pairs.iter().any(|(s, _)| *s == combined) && !added.iter().any(|(s, _)| *s == combined) {
added.push((combined, t2.clone()));
}
}
}
if added.is_empty() {
break;
}
pairs.extend(added);
}
pairs
}
/// Whether a layer in `ambient` authors a relocate whose SOURCE is `source`
/// (the salted-earth prohibition test). Includes deletion relocates.
pub(crate) fn is_relocation_source(&self, ambient: LayerStackId, source: &Path) -> bool {
self.relocation_source_layer(ambient, source).is_some()
}
/// Identifier of the strongest layer in `ambient` that authors a relocate
/// whose SOURCE is `source`, or `None`.
pub(crate) fn relocation_source_layer(&self, ambient: LayerStackId, source: &Path) -> Option<&str> {
self.incremental_relocate_entries(ambient)
.into_iter()
.find_map(|(relocate_source, _, layer)| {
(relocate_source == *source).then(|| self.layer(layer).identifier())
})
}
/// Ensures `layer` is present as a graph node, returning `(id, fresh)` where
/// `fresh` is `true` when the layer newly joined the graph. An already-loaded
/// layer (matched by identifier) is left untouched (its existing children and
/// relocates survive, since the same layer may be sublayered from several
/// places) and reported as not fresh; an absent one joins with a freshly
/// minted id. Callers key one-time per-layer setup (e.g. attaching a change
/// aggregator) off `fresh` so a re-added identifier is not set up twice.
///
/// The node must exist before a `subLayers` edit naming its asset path is
/// rebuilt, so that [`build_sublayer_edges`](Self::build_sublayer_edges)'s
/// [`find_relative`](Self::find_relative) resolves the path to it.
pub(crate) fn ensure_layer(&mut self, layer: sdf::Layer) -> (LayerId, bool) {
self.intern(layer)
}
/// The id of the layer interned under exactly `identifier` (the canonical,
/// resolver-produced form), or `None`. An authored relative path must be
/// anchored to its canonical identifier first (see
/// [`find_relative`](Self::find_relative)); this is the exact registry lookup
/// the anchored path then resolves through, and the authoring surface keys a
/// layer this way.
pub(crate) fn id_of(&self, identifier: &str) -> Option<LayerId> {
self.by_identifier.get(identifier).copied()
}
/// The layer interned under the resolver-anchored identifier `anchored`, or —
/// when nothing is interned there — under the bare authored `normalized` path.
/// Anchoring wins so a relative path against a filesystem-backed layer never
/// resolves to an unrelated layer interned under the bare string, while an
/// in-memory layer keyed under that literal name (no filesystem anchor) still
/// resolves. The shared lookup behind [`find_relative`](Self::find_relative)
/// and [`resolve_sublayer`](Self::resolve_sublayer).
fn anchored_or_bare(&self, anchored: &str, normalized: &str) -> Option<LayerId> {
self.id_of(anchored).or_else(|| self.id_of(normalized))
}
/// Resolves `asset_path` as authored in `anchor`, anchoring it through the
/// resolver to a canonical identifier, then looking that up exactly (C++
/// `SdfLayer::FindRelativeToLayer`). The resolver owns anchoring and
/// canonicalization, so a `..` path or a symlinked leaf resolves to the same
/// canonical identifier the load path (`LayerRegistry::open_sublayers`)
/// interned the layer under — the lookup is an exact registry hit that agrees
/// with the load path by construction.
///
/// The anchored identifier — the asset USD resolves a relative path to — is
/// tried first. Only when no layer is interned there does it fall back to the
/// bare authored string, which lets an in-memory layer keyed under that
/// literal name (with no filesystem location to anchor against) resolve.
/// Anchoring first means a relative path against a filesystem-backed layer
/// never resolves to an unrelated layer that merely happens to be interned
/// under the bare string.
pub(crate) fn find_relative(&self, asset_path: &str, anchor: LayerId) -> Option<LayerId> {
self.resolve_relative(asset_path, anchor).ok()
}
/// The resolution behind [`find_relative`](Self::find_relative), keeping
/// the miss: returns the interned layer, or `Err` with the anchored
/// canonical identifier the asset would intern under — the form the
/// on-demand loader opens a sublayer demand at, and the key load failures
/// and open attempts are recorded by.
pub(crate) fn resolve_relative(&self, asset_path: &str, anchor: LayerId) -> Result<LayerId, String> {
let asset_path = without_dot_segments(asset_path);
let anchored = self
.registry
.create_identifier_anchored(&asset_path, self.real_path(anchor));
self.anchored_or_bare(&anchored, &asset_path).ok_or(anchored)
}
/// [`resolve_relative`](Self::resolve_relative) for a demanded sublayer
/// entry, replacing the entry's memoized anchoring
/// ([`SublayerState::resolution`]) with the fresh one: anchoring
/// canonicalizes through the filesystem, so an asset that appeared since
/// the memo was filed can shift the entry's canonical form, and the memo
/// must follow for the next rebuild to resolve the entry the same way the
/// barrier just did.
pub(crate) fn refresh_demanded_sublayer(&mut self, parent: LayerId, sub_path: &str) -> Result<LayerId, String> {
let normalized = without_dot_segments(sub_path);
let anchored = self
.registry
.create_identifier_anchored(&normalized, self.real_path(parent));
self.sublayers
.resolution
.entry(parent)
.or_default()
.insert(normalized.clone().into_owned(), anchored.clone());
self.anchored_or_bare(&anchored, &normalized).ok_or(anchored)
}
/// Mutes the layer with the given identifier so it contributes no opinions to
/// composition (C++ `PcpCache::RequestLayerMuting`), recomposing the
/// muting-dependent graph state. Returns what changed (see [`MuteChange`]), or
/// `None` when nothing did: the identifier was already muted, or it resolves to
/// the root layer, which cannot be muted ("would lead to empty layer stacks").
///
/// The layer need not be loaded; the canonical identifier is stored and takes
/// effect the moment a later edit interns a matching layer (see
/// [`rebuild_sublayer_stacks`](Self::rebuild_sublayer_stacks), which
/// re-materializes the interned muted ids).
pub(crate) fn mute_layer(&mut self, identifier: String) -> Option<MuteChange> {
let canonical = self.canonical_muted_id(&identifier, self.anchor_location(self.root).as_ref());
if self.is_root_identifier(&canonical) || !self.muted_identifiers.insert(canonical.clone()) {
return None;
}
let affected = self.recompose_for_mute_with_fanout(&canonical);
Some(MuteChange {
changed: canonical,
affected,
})
}
/// Unmutes the layer with the given identifier, restoring its opinions and
/// recomposing. Returns what changed (see [`MuteChange`]), or `None` when the
/// identifier was not muted. The identifier is canonicalized the same way
/// muting canonicalized it, so any spelling of one layer unmutes it.
pub(crate) fn unmute_layer(&mut self, identifier: &str) -> Option<MuteChange> {
let canonical = self.canonical_muted_id(identifier, self.anchor_location(self.root).as_ref());
if !self.muted_identifiers.remove(&canonical) {
return None;
}
let affected = self.recompose_for_mute_with_fanout(&canonical);
Some(MuteChange {
changed: canonical,
affected,
})
}
/// Recomposes the muting-dependent graph state for a just-changed muted set
/// and returns the layers whose cached prim indices the toggle of the layer
/// with canonical identifier `canonical` can invalidate: the structural
/// [`mute_fanout`](Self::mute_fanout) plus any layer whose cached relocate
/// pairs the recompose changed.
///
/// Relocate extraction omits muted layers and refreshes diagnostics in the
/// graph. Any layer whose cached relocate pairs change is added to the
/// fanout so dependent prims rebuild against the current stack state.
fn recompose_for_mute_with_fanout(&mut self, canonical: &str) -> HashSet<LayerId> {
let mut affected = self.mute_fanout(canonical);
affected.extend(self.recompose_for_mute());
affected
}
/// The interned layers a (un)mute of the layer with canonical identifier
/// `canonical` can invalidate: the layer itself and every layer whose
/// `subLayers` subtree contains it. Empty when no loaded layer has that
/// identifier — muting a not-yet-loaded layer changes no composed index.
///
/// A composed prim index is affected by toggling the layer exactly when one
/// of its nodes resolves against a layer stack containing it, and a sublayer
/// stack contains a layer iff its root layer does, so the set's members are
/// the stack roots whose nodes a dependent index would list. Both the
/// identifier lookup and the subtree edges are independent of the muted set,
/// so the set is identical whether computed before muting or after unmuting.
///
/// The stage root layer stack is the one stack that is not a single sublayer
/// subtree: it glues the session layers (and their subtrees) onto the root
/// layer's subtree. A toggle anywhere in it can change every prim that
/// composes locally against it, and such a prim always retains the root layer
/// in its composition (the root layer is never muted), so when a session
/// layer is in the set the root layer is added as the anchor a dependent
/// index is found through.
fn mute_fanout(&self, canonical: &str) -> HashSet<LayerId> {
let Some(id) = self.id_of(canonical) else {
return HashSet::new();
};
let mut affected = self.ancestors_including(id);
if let Some(root) = self.root {
if self.session_layers().iter().any(|s| affected.contains(s)) {
affected.insert(root);
}
}
affected
}
/// Every layer whose `subLayers` subtree contains `target`, including
/// `target` itself. Derived from the sublayer edges, which `subLayers`
/// metadata is the single source of truth for and which muting never alters,
/// so the result does not depend on the current muted set. A `${VAR}` sublayer
/// is absent from the context-free [`LayerNode::children`], so the edges only a
/// stack's variables resolve are supplied by
/// [`expression_ancestry_edges`](Self::expression_ancestry_edges).
fn ancestors_including(&self, target: LayerId) -> HashSet<LayerId> {
let mut found = HashSet::from([target]);
let expr_edges = self.expression_ancestry_edges();
// The sublayer DAG holds one node per loaded layer, so growing the set to
// a fixpoint — add any layer with a child already in it, until it stops
// growing — is cheaper than materializing a reverse-edge index.
let mut growing = true;
while growing {
growing = false;
for (&id, node) in &self.nodes {
if found.contains(&id) {
continue;
}
let reaches = node.children.iter().any(|&(child, _)| found.contains(&child))
|| expr_edges
.get(&id)
.is_some_and(|children| children.iter().any(|c| found.contains(c)));
if reaches {
found.insert(id);
growing = true;
}
}
}
found
}
/// The sublayer edges only a stack's expression variables resolve, keyed by the
/// parent layer — the supplement the context-free [`LayerNode::children`] omit, so
/// [`ancestors_including`](Self::ancestors_including) still finds a stack root whose
/// `${VAR}` sublayer selects the target. Each stack's subtree is resolved against
/// its own variables (the root stack's structural variables for the stage root
/// stack's root and session regions, a seed for a target), read regardless of
/// muting so the ancestor set is identical before a mute and after the matching
/// unmute.
fn expression_ancestry_edges(&self) -> HashMap<LayerId, Vec<LayerId>> {
let mut edges: HashMap<LayerId, Vec<LayerId>> = HashMap::new();
if !self.sublayers.any_expr {
return edges;
}
// The roots of every stack whose subtree can hold an expression edge: the
// stage root stack — both its root region and its session region, each
// resolved against the structural root-stack variables so a session
// sublayer sees the stage root's variables too — and every interned
// target stack, resolved against its stored composed set (the same set
// its `${VAR}` sublayer edges resolved against on the last rebuild).
let structural = self.root_stack_structural_vars();
let mut specs: Vec<(LayerId, &HashMap<String, Value>)> = Vec::new();
if let Some(root) = self.root {
specs.push((root, &structural));
}
if let Some(&session_root) = self.session_layers().first() {
specs.push((session_root, &structural));
}
specs.extend(
self.stacks
.targets()
.map(|(id, root, _)| (root, self.stacks.expression_variables(id))),
);
let mut resolution = HashMap::new();
for (root, vars) in specs {
if !self.has_expr_sublayer(root) {
continue;
}
for (parent, resolved) in self.compose_stack_edges(root, vars, &mut resolution, None) {
edges
.entry(parent)
.or_default()
.extend(resolved.into_iter().map(|(child, _)| child));
}
}
edges
}
/// Seeds the muted set from `identifiers` (open-time muting), then recomposes
/// once — cheaper than a `mute_layer` per identifier, which would recompose on
/// each. Canonicalizes each against the root layer and drops any that names the
/// root (which cannot be muted); identical canonical ids collapse in the set,
/// so [`muted_layers`](Self::muted_layers) lists each muted layer once.
pub(crate) fn set_muted_identifiers(&mut self, identifiers: impl IntoIterator<Item = String>) {
let root_anchor = self.anchor_location(self.root);
for identifier in identifiers {
let canonical = self.canonical_muted_id(&identifier, root_anchor.as_ref());
if !self.is_root_identifier(&canonical) {
self.muted_identifiers.insert(canonical);
}
}
self.recompose_for_mute();
}
/// Whether the layer named by this identifier is muted, matching by canonical
/// identifier anchored against the root layer (C++ `PcpCache::IsLayerMuted`),
/// so any spelling of one layer reads alike.
pub(crate) fn is_layer_muted(&self, identifier: &str) -> bool {
if self.muted_identifiers.is_empty() {
return false;
}
let canonical = self.canonical_muted_id(identifier, self.anchor_location(self.root).as_ref());
self.muted_identifiers.contains(&canonical)
}
/// Whether any layer identifier is muted at all. A cheap gate so the per-arc
/// mute check skips its anchoring work on the common unmuted stage.
pub(crate) fn has_muted_layers(&self) -> bool {
!self.muted_identifiers.is_empty()
}
/// The muted-set identifier matched by the reference/payload target
/// `asset_path`, anchored against `anchor` (the layer that authored the arc),
/// or `None` when it names no muted layer. Matched by the canonical identifier
/// the target would be interned under (C++ `Pcp_MutedLayers::IsLayerMuted`,
/// anchored against the containing layer; see
/// [`Indexer::arc_target_muted`](super::prim_indexer)). Unlike
/// [`is_muted`](Self::is_muted), this matches before the layer is interned, so
/// the on-demand loader can recognize a muted target and skip opening it, and
/// the returned identifier is the muted-set entry an unmute toggles, so a
/// not-yet-loaded target can record it as its unmute-fanout trace.
pub(crate) fn muted_asset_id(&self, asset_path: &str, anchor: Option<&ResolvedPath>) -> Option<String> {
if self.muted_identifiers.is_empty() {
return None;
}
let canonical = self.canonical_muted_id(asset_path, anchor);
self.muted_identifiers.contains(&canonical).then_some(canonical)
}
/// The layers of every composed stack — the effectively-present set the stage
/// filters muted collection diagnostics against (see
/// [`sublayer_error_contributes`](Self::sublayer_error_contributes)). Read from
/// the composed stacks (muting has pruned their muted subtrees), so it is a pure
/// function of the muted set and the graph, independent of which prim indices
/// are cached — a diagnostic's visibility does not change as the cache warms.
pub(crate) fn effective_layers(&self) -> HashSet<LayerId> {
self.stacks.member_layers()
}
/// Whether a collection diagnostic still contributes to composition once muting
/// is applied, so the stage keeps it (the loader reports every load failure raw,
/// unaware of muting). A non-sublayer error always survives. A missing or
/// unreadable sublayer survives only when its referencing layer is `effective`
/// (a member of some composed stack) and the sublayer it names is not itself
/// muted; otherwise muting prunes it and the raw diagnostic is spurious. The
/// `effective` set is a pure function of the muted set and the graph, so the
/// decision is deterministic across queries and independent of load order.
pub(crate) fn sublayer_error_contributes(&self, error: &Error, effective: &HashSet<LayerId>) -> bool {
let (asset_path, introduced_by) = match error {
Error::UnresolvedSublayer {
asset_path,
introduced_by,
}
| Error::MalformedSublayer {
asset_path,
introduced_by,
..
} => (asset_path, introduced_by),
_ => return true,
};
let Some(referrer) = self.id_of(introduced_by) else {
return true;
};
effective.contains(&referrer)
&& self
.muted_asset_id(asset_path, self.anchor_location(Some(referrer)).as_ref())
.is_none()
}
/// The muted layer identifiers, sorted for a deterministic result.
pub(crate) fn muted_layers(&self) -> Vec<String> {
let mut ids: Vec<String> = self.muted_identifiers.iter().cloned().collect();
ids.sort();
ids
}
/// Whether the layer with this id is muted, i.e. excluded from every stack.
/// A muted layer contributes nothing to composition — not its opinions, its
/// stage metadata, or its diagnostics.
pub(crate) fn is_muted(&self, id: LayerId) -> bool {
self.muted.contains(&id)
}
/// Refreshes every muting-dependent piece of graph state after the muted set
/// changes: the sublayer stacks (rebuilding re-resolves the muted ids), the
/// sublayer-cycle diagnostics (a cycle through a muted layer no longer
/// composes), and the relocates, whose validation and conflict scopes both
/// drop muted layers. Returns the layers whose cached relocate pairs changed
/// (from [`recompute_relocates`](Self::recompute_relocates)).
fn recompose_for_mute(&mut self) -> HashSet<LayerId> {
// A mute toggles the muted set rather than the sublayer edges, so the
// edge-diff scoping `build_sublayer_edges` uses does not apply; re-resolve
// every instance (an unmuted layer rejoins stacks whose members no longer
// list it, which a member-set scope would miss). `rebuild_sublayer_stacks`
// refreshes the muted set and recomputes the root's session-seeded members,
// so muting a session layer that supplies a root `${VAR}` sublayer's variable
// re-resolves that sublayer out of (or into, among interned layers) the root
// stack. The vars deltas a mute can emit (a muted session root drops its
// variables) are discarded: the mute fanout's affected set already drops
// every index reading a stack whose members shifted, which covers any
// stack whose variables the toggle changed.
let _ = self.rebuild_sublayer_stacks(None);
self.recompute_cycle_errors();
self.recompute_relocates()
}
/// Re-materializes [`muted`](Self::muted) — the interned ids of the muted
/// canonical identifiers — at the start of every stack rebuild, so it reflects
/// the currently-loaded layers (a layer muted before it was loaded takes effect
/// the moment a later edit interns it). The root is never present: its
/// identifier is rejected before any entry is inserted (see
/// [`is_root_identifier`](Self::is_root_identifier)).
fn resolve_muted_ids(&mut self) {
// TODO: reclaim a muted layer's memory. C++ drops its references; here
// the node stays interned so unmute is a rebuild and nothing is freed.
// The common unmuted stage rebuilds stacks often, so leave `muted` (already
// empty) untouched rather than reallocating it each time.
if self.muted_identifiers.is_empty() {
self.muted.clear();
return;
}
self.muted = self.muted_identifiers.iter().filter_map(|id| self.id_of(id)).collect();
}
/// Whether `canonical` is the root layer's identifier, which cannot be muted
/// ("would lead to empty layer stacks"). The single authority for rejecting a
/// request to mute the root, regardless of the spelling the caller supplied.
fn is_root_identifier(&self, canonical: &str) -> bool {
self.root.is_some_and(|root| self.identifier(root) == canonical)
}
/// The canonical identifier a muted-layer path resolves to (C++
/// `Pcp_MutedLayers::_GetCanonicalLayerId`). A path is reduced to the
/// identifier its layer is interned under (see [`intern`](Self::intern)): with
/// no filesystem `anchor` — an in-memory or anonymous root — a relative path
/// has nothing to resolve against and an added layer keeps its bare
/// identifier, so the path passes through. Every other path is canonicalized
/// through the registry against `anchor`, the form a filesystem asset is
/// interned under; an anonymous identifier passes through there too (the
/// registry keeps an `anon:` id as its own canonical form).
///
/// `anchor` is the layer the path is anchored against: the root layer for the
/// mute/unmute/query API, the arc's authoring layer for a reference/payload
/// target. Keying the muted set on this makes two spellings of one layer
/// collapse to a single entry and lets a not-yet-loaded target match the
/// identifier it will be interned under. The result is a pure function of
/// `(path, anchor)`, independent of which layers are currently loaded — so the
/// same physical layer never keys under different strings by load order.
fn canonical_muted_id(&self, path: &str, anchor: Option<&ResolvedPath>) -> String {
if anchor.is_none() {
return path.to_string();
}
self.registry.create_identifier(path, anchor)
}
}
/// Depth-first pre-order walk of a sublayer subtree, composing each hop's offset
/// and pruning muted layers, the shared traversal behind every composed stack.
/// `children_of` supplies a layer's resolved sublayer edges — the shared
/// context-free [`LayerNode::children`], or a stack's expression-resolved edges —
/// so both build paths stay locked together. Runs on an explicit work stack so a
/// deep chain does not overflow the native stack; an `Exit` frame pops the layer
/// back out of the `ancestors` path after its subtree. A layer that sublayers
/// itself transitively is a cycle and is skipped; an off-path duplicate (a sublayer
/// diamond) is expanded again.
fn collect_sublayers<'a>(
root: LayerId,
effective: LayerOffset,
members: &mut Vec<(LayerId, LayerOffset)>,
ancestors: &mut HashSet<LayerId>,
is_muted: impl Fn(LayerId) -> bool,
children_of: impl Fn(LayerId) -> &'a [(LayerId, LayerOffset)],
) {
enum Step {
Enter(LayerId, LayerOffset),
Exit(LayerId),
}
let mut work = vec![Step::Enter(root, effective)];
while let Some(step) = work.pop() {
let (id, effective) = match step {
Step::Exit(id) => {
ancestors.remove(&id);
continue;
}
Step::Enter(id, effective) => (id, effective),
};
// A muted layer contributes nothing: skip it and its whole subtree.
if is_muted(id) {
continue;
}
members.push((id, effective));
ancestors.insert(id);
work.push(Step::Exit(id));
for &(child, edge_offset) in children_of(id).iter().rev() {
if !ancestors.contains(&child) {
work.push(Step::Enter(child, effective.concatenate(&edge_offset)));
}
}
}
}
/// `asset_path` with its `.` (current-directory) segments dropped, rendered with
/// `/` separators: `./a` and `a/./b` become `a` and `a/b`. Segments are split on
/// any separator the platform accepts — `/` everywhere, and `\` on Windows — so
/// this matches the `std::path::Components` normalization the resolver applies
/// when it anchors a relative path (`LayerRegistry::create_identifier` via
/// `TfNormPath`). A dot-relative spelling therefore reduces to the same bare key
/// the anchored identifier drops its `.` to — `./sub.usda` on any platform, or
/// `.\sub.usda` on Windows — and the bare fallback in `anchored_or_bare` finds an
/// in-memory layer interned under `sub.usda`. A path with no `.` segment is
/// returned unchanged.
fn without_dot_segments(asset_path: &str) -> Cow<'_, str> {
if !asset_path.split(path::is_separator).any(|segment| segment == ".") {
return Cow::Borrowed(asset_path);
}
let kept: Vec<&str> = asset_path
.split(path::is_separator)
.filter(|segment| *segment != ".")
.collect();
Cow::Owned(kept.join("/"))
}
#[cfg(test)]
impl LayerGraph {
/// Mints the layer stack each demand resolves against, once its target
/// layer is interned: `id_of` the demanded asset, then
/// [`intern_external`](Self::intern_external) under the demand's context.
/// The demand drain the test harnesses run in place of the stage's load
/// barrier (whose own mint loop additionally re-checks contextual opens for
/// targets that joined mid-pass); their fixtures load every layer up front,
/// so a demand only ever needs interning. Returns whether any new instance
/// was created, so the caller re-runs the composition pass that recorded
/// the demands.
pub(crate) fn intern_demanded(&mut self, demands: &[Demand]) -> bool {
let mut newly_interned = false;
for demand in demands {
if let Some(root) = self.id_of(demand.asset_path.as_str()) {
newly_interned |= self.intern_external(root, demand.context).1;
}
}
newly_interned
}
}
#[cfg(test)]
mod tests {
use std::io;
use std::path::Path as FsPath;
use super::*;
use crate::ar;
/// Author through a layer's `edit` API and commit, for building test fixtures.
fn edit_layer(layer: &mut sdf::Layer, f: impl FnOnce(&mut sdf::LayerEdit<'_>)) {
layer
.edit(|e| {
f(e);
Ok(())
})
.expect("authored");
}
impl LayerGraph {
/// Build a graph from `layers` in one step: intern each, then
/// [`finalize`](Self::finalize). The first `session_layer_count` layers
/// are the session layers; the next is the root. A test convenience — the
/// stage builds its graph through [`new`](Self::new) +
/// [`ensure_layer`](Self::ensure_layer) so it can attach a change sink to
/// each layer as it joins.
pub(crate) fn from_layers(
layers: Vec<sdf::Layer>,
session_layer_count: usize,
registry: sdf::LayerRegistry,
) -> Self {
let mut graph = Self::new(registry);
let mut root = None;
let mut session_count = 0;
for (i, layer) in layers.into_iter().enumerate() {
let (id, fresh) = graph.intern(layer);
if i == session_layer_count {
root = Some(id);
}
if fresh && i < session_layer_count {
session_count += 1;
}
}
graph.finalize(session_count, root);
graph
}
/// The id of a loaded layer whose identifier ends with the path component
/// `leaf` (its file name), or `None`. A test convenience for locating a
/// layer in a stack built from on-disk assets, where the identifier is the
/// full resolved path rather than the authored leaf; production code keys
/// layers by canonical identifier ([`id_of`](Self::id_of)) or anchors an
/// authored path first ([`find_relative`](Self::find_relative)).
pub(crate) fn find_by_leaf(&self, leaf: &str) -> Option<LayerId> {
self.order
.iter()
.copied()
.find(|&id| FsPath::new(self.identifier(id)).ends_with(leaf))
}
}
/// A `root → sub → leaf` sublayer chain, each layer named verbatim so the
/// authored `subLayers` entries resolve by exact identifier match.
fn chain_graph() -> LayerGraph {
let mut root = sdf::Layer::new_in_memory("root.usda");
edit_layer(&mut root, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["sub.usda"]);
});
let mut sub = sdf::Layer::new_in_memory("sub.usda");
edit_layer(&mut sub, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["leaf.usda"]);
});
let leaf = sdf::Layer::new_in_memory("leaf.usda");
LayerGraph::from_layers(vec![root, sub, leaf], 0, sdf::LayerRegistry::default())
}
/// Muting a sublayer drops it and its whole subtree from `sublayer_stack`,
/// `root_layer_stack`, and `local_layers`; unmuting restores them.
#[test]
fn muted_excludes_subtree() {
let mut graph = chain_graph();
let root = graph.root_id().unwrap();
let sub = graph.id_of("sub.usda").unwrap();
let leaf = graph.id_of("leaf.usda").unwrap();
let ids: Vec<LayerId> = graph.sublayer_stack(root).iter().map(|&(id, _)| id).collect();
assert_eq!(ids, vec![root, sub, leaf]);
assert_eq!(graph.root_layer_stack().len(), 3);
assert!(graph.mute_layer("sub.usda".to_string()).is_some());
let ids: Vec<LayerId> = graph.sublayer_stack(root).iter().map(|&(id, _)| id).collect();
assert_eq!(ids, vec![root], "the muted sublayer and its subtree are pruned");
assert_eq!(graph.root_layer_stack().len(), 1);
assert_eq!(graph.local_layers(), HashSet::from([root]));
assert!(graph.unmute_layer("sub.usda").is_some());
let ids: Vec<LayerId> = graph.sublayer_stack(root).iter().map(|&(id, _)| id).collect();
assert_eq!(ids, vec![root, sub, leaf], "unmuting restores the subtree");
assert_eq!(graph.local_layers(), HashSet::from([root, sub, leaf]));
}
/// Muting the root layer is rejected: `mute_layer` reports no change and the
/// root stack is unchanged.
#[test]
fn muted_root_ignored() {
let mut graph = chain_graph();
assert!(
graph.mute_layer("root.usda".to_string()).is_none(),
"the root layer cannot be muted"
);
assert!(!graph.is_layer_muted("root.usda"));
assert_eq!(graph.root_layer_stack().len(), 3);
}
/// Muting a layer in a sublayer cycle clears the cycle diagnostic, since the
/// muted branch no longer composes; unmuting brings it back.
#[test]
fn muted_cycle_clears_error() {
let mut root = sdf::Layer::new_in_memory("root.usda");
edit_layer(&mut root, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["a.usda"]);
});
let mut a = sdf::Layer::new_in_memory("a.usda");
edit_layer(&mut a, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["b.usda"]);
});
let mut b = sdf::Layer::new_in_memory("b.usda");
edit_layer(&mut b, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["a.usda"]);
});
let mut graph = LayerGraph::from_layers(vec![root, a, b], 0, sdf::LayerRegistry::default());
assert!(!graph.errors().is_empty(), "the a → b → a sublayer cycle is reported");
assert!(graph.mute_layer("b.usda".to_string()).is_some());
assert!(
graph.errors().is_empty(),
"muting a layer in the cycle clears the diagnostic"
);
assert!(graph.unmute_layer("b.usda").is_some());
assert!(!graph.errors().is_empty(), "unmuting restores the cycle diagnostic");
}
/// Authors an `expressionVariables` dictionary on a layer's pseudo-root.
fn set_expr_var(layer: &mut sdf::Layer, name: &str, value: &str) {
edit_layer(layer, |e| {
let dict = HashMap::from([(name.to_string(), Value::String(value.to_string()))]);
e.pseudo_root_mut()
.unwrap()
.set(FieldKey::ExpressionVariables.as_str(), Value::Dictionary(dict));
});
}
/// A variable authored on a **sublayer** is ignored: a layer stack's expression
/// variables come from its root layer, not its sublayers (C++
/// `PcpExpressionVariables`). `a` sublayers the root and authors `V`, but `b`'s
/// `${V}` sublayer resolves against the stack root's variables (none here), so it
/// does not resolve and `leaf` never enters the stack.
#[test]
fn sublayer_var_ignored() {
let mut root = sdf::Layer::new_in_memory("root.usda");
edit_layer(&mut root, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["a.usda"]);
});
let mut a = sdf::Layer::new_in_memory("a.usda");
set_expr_var(&mut a, "V", "leaf");
edit_layer(&mut a, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["b.usda"]);
});
let mut b = sdf::Layer::new_in_memory("b.usda");
edit_layer(&mut b, |e| {
e.pseudo_root_mut().unwrap().set_sublayers([r#"`"${V}.usda"`"#]);
});
let leaf = sdf::Layer::new_in_memory("leaf.usda");
let graph = LayerGraph::from_layers(vec![root, a, b, leaf], 0, sdf::LayerRegistry::default());
let root = graph.root_id().unwrap();
let leaf = graph.id_of("leaf.usda").unwrap();
let ids: Vec<LayerId> = graph.sublayer_stack(root).iter().map(|&(id, _)| id).collect();
assert!(
!ids.contains(&leaf),
"`a` is a sublayer, so its `V` is ignored and `b`'s ${{V}} does not resolve: {ids:?}",
);
}
/// A `${VAR}` root sublayer resolved by a session variable back onto the root
/// is a cycle, and it is reported: the session-seeded root edges feed cycle
/// detection, not just member collection, so the diagnostic surfaces rather
/// than the edge being silently pruned.
#[test]
fn session_var_sublayer_cycle() {
let mut session = sdf::Layer::new_in_memory("session.usda");
set_expr_var(&mut session, "WHICH", "root");
let mut root = sdf::Layer::new_in_memory("root.usda");
edit_layer(&mut root, |e| {
e.pseudo_root_mut().unwrap().set_sublayers([r#"`"${WHICH}.usda"`"#]);
});
let graph = LayerGraph::from_layers(vec![session, root], 1, sdf::LayerRegistry::default());
assert!(
graph.errors().iter().any(|e| matches!(e, Error::SublayerCycle { .. })),
"the session-resolved self-sublayer is reported as a cycle: {:?}",
graph.errors()
);
}
/// A failing `${VAR}` sublayer expression — a bare reference to an
/// undefined variable errors, where a quoted string substitutes the name in
/// place — records one `InvalidExpression` diagnostic with the sublayer
/// context from the stack's contextual re-resolution (C++
/// `_BuildLayerStack`); the context-free edge pass stays silent. Authoring
/// the variable clears it on the next rebuild.
#[test]
fn sublayer_expr_error_reported() {
let mut root = sdf::Layer::new_in_memory("root.usda");
edit_layer(&mut root, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["`${WHICH}`"]);
});
let sub = sdf::Layer::new_in_memory("sub.usda");
let mut graph = LayerGraph::from_layers(vec![root, sub], 0, sdf::LayerRegistry::default());
let errors = graph.errors();
let expression_errors = errors
.iter()
.filter(|e| {
matches!(
e,
Error::InvalidExpression {
context: ExpressionContext::Sublayer,
..
}
)
})
.count();
assert_eq!(
expression_errors, 1,
"one failing evaluation, one diagnostic: {errors:?}"
);
let root_id = graph.root_id().unwrap();
set_expr_var(&mut graph.nodes.get_mut(&root_id).unwrap().layer, "WHICH", "sub.usda");
graph.recompute_sublayers(Some(&HashSet::from([root_id])));
assert!(
graph.errors().is_empty(),
"authoring WHICH resolves the expression and clears the diagnostic"
);
let sub_id = graph.id_of("sub.usda").unwrap();
assert!(
graph.root_layer_stack().iter().any(|&(id, _)| id == sub_id),
"the resolved selection joins the root stack"
);
}
/// A degenerate empty `subLayers` entry names nothing to open: it resolves
/// to no edge and records no load demand.
#[test]
fn empty_entry_no_demand() {
let mut root = sdf::Layer::new_in_memory("root.usda");
edit_layer(&mut root, |e| {
e.pseudo_root_mut().unwrap().set_sublayers([""]);
});
let mut graph = LayerGraph::from_layers(vec![root], 0, sdf::LayerRegistry::default());
assert!(graph.take_sublayer_demands().is_empty());
}
/// An anonymous parent anchors nothing, so its unresolved entries are
/// graph-only lookups: no load demand is recorded for them.
#[test]
fn anon_parent_no_demand() {
let mut root = sdf::Layer::new_anonymous("root.usda");
edit_layer(&mut root, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["ghost.usda"]);
});
let mut graph = LayerGraph::from_layers(vec![root], 0, sdf::LayerRegistry::default());
assert!(graph.take_sublayer_demands().is_empty());
}
/// Muting a session layer that supplies a root `${VAR}` sublayer's variable
/// re-resolves the root edges: the sublayer it selected drops, rather than the
/// muted layer continuing to resolve it.
#[test]
fn mute_session_drops_sublayer() {
let mut session = sdf::Layer::new_in_memory("session.usda");
set_expr_var(&mut session, "WHICH", "a");
let mut root = sdf::Layer::new_in_memory("root.usda");
edit_layer(&mut root, |e| {
e.pseudo_root_mut().unwrap().set_sublayers([r#"`"${WHICH}.usda"`"#]);
});
let a = sdf::Layer::new_in_memory("a.usda");
let mut graph = LayerGraph::from_layers(vec![session, root, a], 1, sdf::LayerRegistry::default());
let a_id = graph.id_of("a.usda").unwrap();
let in_root = |g: &LayerGraph| g.root_layer_stack().iter().any(|&(id, _)| id == a_id);
assert!(
in_root(&graph),
"the session's WHICH=a resolves the root sublayer to a.usda"
);
graph.mute_layer("session.usda".to_string());
assert!(
!in_root(&graph),
"muting the session layer drops the variable, so the root sublayer no longer resolves"
);
}
/// A variable authored on a session **sublayer** is ignored; only the session
/// root layer's own reaches the root stack (C++ `PcpExpressionVariables` reads
/// the session layer, not its sublayers). The mirror — the session root itself
/// authoring the variable — does apply.
#[test]
fn session_sublayer_var_ignored() {
let sublayer_authored = |on_root: bool| -> bool {
let mut session = sdf::Layer::new_in_memory("session.usda");
if on_root {
set_expr_var(&mut session, "V", "leaf");
}
edit_layer(&mut session, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["session_sub.usda"]);
});
let mut session_sub = sdf::Layer::new_in_memory("session_sub.usda");
if !on_root {
set_expr_var(&mut session_sub, "V", "leaf");
}
let mut root = sdf::Layer::new_in_memory("root.usda");
edit_layer(&mut root, |e| {
e.pseudo_root_mut().unwrap().set_sublayers([r#"`"${V}.usda"`"#]);
});
let leaf = sdf::Layer::new_in_memory("leaf.usda");
let graph =
LayerGraph::from_layers(vec![session, session_sub, root, leaf], 2, sdf::LayerRegistry::default());
let leaf_id = graph.id_of("leaf.usda").unwrap();
graph.root_layer_stack().iter().any(|&(id, _)| id == leaf_id)
};
assert!(
!sublayer_authored(false),
"a session sublayer's V is ignored, so the root's `${{V}}` does not resolve",
);
assert!(
sublayer_authored(true),
"the session root's own V applies, so the root's `${{V}}` resolves",
);
}
/// A stack uses its **root** layer's own variables. `a` authors `V` and
/// sublayers `b`; a stack rooted at `a` resolves `b`'s `${V}` sublayer to `leaf`
/// (`a` is that stack's root). A stack rooted at `b` does not: `b` authors no
/// variables, and `a` — which merely sublayers `b` — contributes none (C++
/// `PcpExpressionVariables`). The result is independent of `b` being interned
/// before `a`.
#[test]
fn stack_root_var_applies() {
let root = sdf::Layer::new_in_memory("root.usda");
let mut a = sdf::Layer::new_in_memory("a.usda");
set_expr_var(&mut a, "V", "leaf");
edit_layer(&mut a, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["b.usda"]);
});
let mut b = sdf::Layer::new_in_memory("b.usda");
edit_layer(&mut b, |e| {
e.pseudo_root_mut().unwrap().set_sublayers([r#"`"${V}.usda"`"#]);
});
let leaf = sdf::Layer::new_in_memory("leaf.usda");
// `root` sublayers none of them, so `a`/`b`/`leaf` are an orphan subtree;
// `b` precedes `a` in collection order.
let graph = LayerGraph::from_layers(vec![root, b, a, leaf], 0, sdf::LayerRegistry::default());
let a_id = graph.id_of("a.usda").unwrap();
let b_id = graph.id_of("b.usda").unwrap();
let leaf_id = graph.id_of("leaf.usda").unwrap();
let a_stack: Vec<LayerId> = graph.sublayer_stack(a_id).iter().map(|&(id, _)| id).collect();
assert!(
a_stack.contains(&leaf_id),
"`a`'s stack threads `a`'s `V` into `b`, so `b`'s ${{V}} resolves to `leaf`: {a_stack:?}",
);
let b_stack: Vec<LayerId> = graph.sublayer_stack(b_id).iter().map(|&(id, _)| id).collect();
assert!(
!b_stack.contains(&leaf_id),
"`b`'s own stack has no inherited context, so its ${{V}} stays unresolved: {b_stack:?}",
);
}
/// A deep single-sublayer chain composes without overflowing the native
/// stack: the edge walk, the cycle scan, and the stack collection all run on
/// explicit stacks. Each layer sublayers the next; the root's composed
/// sublayer stack contains the whole chain. Only the root's stack is
/// precomputed (the chain has one sublayer-DAG root), so this is O(n).
#[test]
fn deep_sublayer_chain_no_overflow() {
const DEPTH: usize = 50_000;
let mut layers = Vec::with_capacity(DEPTH);
for i in 0..DEPTH {
let mut layer = sdf::Layer::new_in_memory(format!("layer{i}.usda"));
if i + 1 < DEPTH {
edit_layer(&mut layer, |e| {
e.pseudo_root_mut()
.unwrap()
.set_sublayers([format!("layer{}.usda", i + 1)]);
});
}
layers.push(layer);
}
let graph = LayerGraph::from_layers(layers, 0, sdf::LayerRegistry::default());
let root_id = graph.root_id().unwrap();
assert_eq!(graph.sublayer_stack(root_id).len(), DEPTH, "the whole chain composes");
}
/// `sublayer_stack` composes a non-precomputed layer's stack on demand: a
/// layer that is sublayered (so not a sublayer-DAG root, not precomputed)
/// still reports its own stack when queried — the case of a layer that is both
/// sublayered and used as a reference/payload target.
#[test]
fn sublayer_stack_computed_on_demand() {
let mut root = sdf::Layer::new_in_memory("root.usda");
edit_layer(&mut root, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["a.usda"]);
});
let mut a = sdf::Layer::new_in_memory("a.usda");
edit_layer(&mut a, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["b.usda"]);
});
let b = sdf::Layer::new_in_memory("b.usda");
let graph = LayerGraph::from_layers(vec![root, a, b], 0, sdf::LayerRegistry::default());
let a_id = graph.id_of("a.usda").unwrap();
let b_id = graph.id_of("b.usda").unwrap();
// `a` is sublayered by root, so it is not a precomputed DAG root.
let ids: Vec<LayerId> = graph.sublayer_stack(a_id).iter().map(|&(id, _)| id).collect();
assert_eq!(ids, vec![a_id, b_id], "a's stack composes on demand");
}
/// A `${VAR}` sublayer on a reference/payload target resolves against the
/// expression variables inherited across the arc, held on the target's
/// source-keyed stack instance. The root-sourced
/// [`sublayer_stack`](LayerGraph::sublayer_stack) (no variables anywhere in
/// the root stack) cannot resolve it; the instance interned for an arc from a
/// var-authoring source can.
#[test]
fn contextual_var_sublayer() {
let root = sdf::Layer::new_in_memory("root.usda");
let mut src = sdf::Layer::new_in_memory("src.usda");
set_expr_var(&mut src, "V", "over");
let mut target = sdf::Layer::new_in_memory("target.usda");
edit_layer(&mut target, |e| {
e.pseudo_root_mut().unwrap().set_sublayers([r#"`"${V}.usda"`"#]);
});
let over = sdf::Layer::new_in_memory("over.usda");
let mut graph = LayerGraph::from_layers(vec![root, src, target, over], 0, sdf::LayerRegistry::default());
let src = graph.id_of("src.usda").unwrap();
let target = graph.id_of("target.usda").unwrap();
let over = graph.id_of("over.usda").unwrap();
let ids: Vec<LayerId> = graph.sublayer_stack(target).iter().map(|&(id, _)| id).collect();
assert!(!ids.contains(&over), "the root-sourced stack cannot resolve `${{V}}`");
let src_stack = graph.intern_external(src, LayerStackId::ROOT).0;
let id = graph.intern_external(target, src_stack).0;
let ids: Vec<LayerId> = graph.layer_stack(id).iter().map(|&(id, _)| id).collect();
assert!(
ids.contains(&over),
"the contextual instance resolves the `${{V}}` sublayer edge"
);
}
/// The same `${VAR}`-sublayer target reached from two sources authoring
/// different variables resolves its sublayer independently: each source gets
/// its own stack instance with its own resolved member.
#[test]
fn contextual_var_sublayer_per_context() {
let root = sdf::Layer::new_in_memory("root.usda");
let mut sa = sdf::Layer::new_in_memory("sa.usda");
set_expr_var(&mut sa, "V", "a");
let mut sb = sdf::Layer::new_in_memory("sb.usda");
set_expr_var(&mut sb, "V", "b");
let mut target = sdf::Layer::new_in_memory("target.usda");
edit_layer(&mut target, |e| {
e.pseudo_root_mut().unwrap().set_sublayers([r#"`"${V}.usda"`"#]);
});
let a = sdf::Layer::new_in_memory("a.usda");
let b = sdf::Layer::new_in_memory("b.usda");
let mut graph = LayerGraph::from_layers(vec![root, sa, sb, target, a, b], 0, sdf::LayerRegistry::default());
let sa = graph.id_of("sa.usda").unwrap();
let sb = graph.id_of("sb.usda").unwrap();
let target = graph.id_of("target.usda").unwrap();
let a = graph.id_of("a.usda").unwrap();
let b = graph.id_of("b.usda").unwrap();
let sa_stack = graph.intern_external(sa, LayerStackId::ROOT).0;
let sb_stack = graph.intern_external(sb, LayerStackId::ROOT).0;
let ia = graph.intern_external(target, sa_stack).0;
let ib = graph.intern_external(target, sb_stack).0;
assert_ne!(ia, ib, "different sources get distinct instances");
let members = |id| {
graph
.layer_stack(id)
.iter()
.map(|&(layer, _)| layer)
.collect::<Vec<_>>()
};
assert!(
members(ia).contains(&a) && !members(ia).contains(&b),
"V=a resolves a.usda"
);
assert!(
members(ib).contains(&b) && !members(ib).contains(&a),
"V=b resolves b.usda"
);
}
/// Every target stack is keyed by its variable source, even when the carried
/// variables cannot change its members — here the target's only expression
/// sublayer is muted. The two sources intern distinct instances with equal
/// members, and each instance carries its own composed expression variables
/// (the context an asset attribute inside the target evaluates against).
#[test]
fn muted_expr_sublayer_per_context() {
let root = sdf::Layer::new_in_memory("root.usda");
let mut sa = sdf::Layer::new_in_memory("sa.usda");
set_expr_var(&mut sa, "V", "a");
let mut sb = sdf::Layer::new_in_memory("sb.usda");
set_expr_var(&mut sb, "V", "b");
let mut target = sdf::Layer::new_in_memory("target.usda");
edit_layer(&mut target, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["muted_expr.usda"]);
});
let mut muted_expr = sdf::Layer::new_in_memory("muted_expr.usda");
edit_layer(&mut muted_expr, |e| {
e.pseudo_root_mut().unwrap().set_sublayers([r#"`"${V}.usda"`"#]);
});
let mut graph =
LayerGraph::from_layers(vec![root, sa, sb, target, muted_expr], 0, sdf::LayerRegistry::default());
graph.mute_layer("muted_expr.usda".to_string());
let sa = graph.id_of("sa.usda").unwrap();
let sb = graph.id_of("sb.usda").unwrap();
let target = graph.id_of("target.usda").unwrap();
let sa_stack = graph.intern_external(sa, LayerStackId::ROOT).0;
let sb_stack = graph.intern_external(sb, LayerStackId::ROOT).0;
let ia = graph.intern_external(target, sa_stack).0;
let ib = graph.intern_external(target, sb_stack).0;
assert_ne!(ia, ib, "each source gets its own instance");
assert_eq!(
graph.layer_stack(ia),
graph.layer_stack(ib),
"the muted expression sublayer leaves both sources' members equal"
);
assert_eq!(
graph.stack_expression_variables(ia),
&HashMap::from([("V".to_string(), Value::String("a".to_string()))]),
"the instance carries its source's variables"
);
assert_eq!(
graph.stack_expression_variables(ib),
&HashMap::from([("V".to_string(), Value::String("b".to_string()))]),
"the instance carries its source's variables"
);
}
/// The stored composed set is the target root's own variables overlaid by the
/// seed (seed winning), and an `expressionVariables` edit on the target root
/// refreshes it through the scoped rebuild.
#[test]
fn stored_composed_refreshed() {
let root = sdf::Layer::new_in_memory("root.usda");
let mut src = sdf::Layer::new_in_memory("src.usda");
set_expr_var(&mut src, "W", "x");
let mut target = sdf::Layer::new_in_memory("target.usda");
set_expr_var(&mut target, "V", "a");
let mut graph = LayerGraph::from_layers(vec![root, src, target], 0, sdf::LayerRegistry::default());
let src = graph.id_of("src.usda").unwrap();
let target = graph.id_of("target.usda").unwrap();
let src_stack = graph.intern_external(src, LayerStackId::ROOT).0;
let id = graph.intern_external(target, src_stack).0;
assert_eq!(
graph.stack_expression_variables(id),
&HashMap::from([
("V".to_string(), Value::String("a".to_string())),
("W".to_string(), Value::String("x".to_string())),
]),
"the stored set is the target's own V overlaid by the source's W"
);
set_expr_var(&mut graph.nodes.get_mut(&target).unwrap().layer, "V", "b");
graph.recompute_sublayers(Some(&HashSet::from([target])));
assert_eq!(
graph.stack_expression_variables(id),
&HashMap::from([
("V".to_string(), Value::String("b".to_string())),
("W".to_string(), Value::String("x".to_string())),
]),
"editing the target root's V refreshes the stored set in place"
);
}
/// An `expressionVariables` edit on a muted target root still refreshes the
/// instance's stored composed set: the muted root's member set is empty
/// (disjoint from every edit), so the rebuild filter must match the target
/// root itself, not only the members.
#[test]
fn muted_target_root_edit() {
let root = sdf::Layer::new_in_memory("root.usda");
let mut target = sdf::Layer::new_in_memory("target.usda");
set_expr_var(&mut target, "V", "a");
let mut graph = LayerGraph::from_layers(vec![root, target], 0, sdf::LayerRegistry::default());
graph.mute_layer("target.usda".to_string());
let target = graph.id_of("target.usda").unwrap();
let id = graph.intern_external(target, LayerStackId::ROOT).0;
assert!(graph.layer_stack(id).is_empty(), "the muted root empties the stack");
assert_eq!(
graph.stack_expression_variables(id),
&HashMap::from([("V".to_string(), Value::String("a".to_string()))]),
"the muted root's own variables still compose the stored set"
);
set_expr_var(&mut graph.nodes.get_mut(&target).unwrap().layer, "V", "b");
graph.recompute_sublayers(Some(&HashSet::from([target])));
assert_eq!(
graph.stack_expression_variables(id),
&HashMap::from([("V".to_string(), Value::String("b".to_string()))]),
"the edit reaches the instance even though its member set is empty"
);
}
/// A back-reference to a sessionless stage root collapses to the ROOT
/// instance exactly when the identity keys agree: the arc carries the Root
/// variable source (a non-authoring chain, or an arc from inside the root
/// stack itself). A carried `Instance` source — the arc runs through a
/// var-authoring stack — mints a contextual instance rooted at the stage
/// root layer that keeps the outer variables in force.
#[test]
fn root_backref_identity() {
let mut root = sdf::Layer::new_in_memory("root.usda");
set_expr_var(&mut root, "V", "r");
let mut src = sdf::Layer::new_in_memory("src.usda");
set_expr_var(&mut src, "EXTRA", "e");
let mut graph = LayerGraph::from_layers(vec![root, src], 0, sdf::LayerRegistry::default());
let root = graph.root_id().unwrap();
let src = graph.id_of("src.usda").unwrap();
let id = graph.intern_external(root, LayerStackId::ROOT).0;
assert_eq!(
id,
LayerStackId::ROOT,
"the Root source collapses to ROOT by key equality"
);
let src_stack = graph.intern_external(src, LayerStackId::ROOT).0;
let id = graph.intern_external(root, src_stack).0;
assert_ne!(
id,
LayerStackId::ROOT,
"a back-reference through a var-authoring source stays contextual"
);
assert_eq!(
graph.stack_expression_variables(id),
&HashMap::from([
("V".to_string(), Value::String("r".to_string())),
("EXTRA".to_string(), Value::String("e".to_string())),
]),
"the contextual instance keeps the carried variables over the root's own"
);
}
/// Two source stacks each authoring the same variables into the same target
/// keep distinct target instances: identity keys by the variables' source,
/// not their value (C++ `PcpLayerStackIdentifier` with
/// `expressionVariablesOverrideSource`), and each source changed the
/// dictionary, so each is its own source.
#[test]
fn equal_map_distinct_source() {
let root = sdf::Layer::new_in_memory("root.usda");
let mut s1 = sdf::Layer::new_in_memory("s1.usda");
set_expr_var(&mut s1, "V", "x");
let mut s2 = sdf::Layer::new_in_memory("s2.usda");
set_expr_var(&mut s2, "V", "x");
let target = sdf::Layer::new_in_memory("target.usda");
let mut graph = LayerGraph::from_layers(vec![root, s1, s2, target], 0, sdf::LayerRegistry::default());
let s1 = graph.id_of("s1.usda").unwrap();
let s2 = graph.id_of("s2.usda").unwrap();
let target = graph.id_of("target.usda").unwrap();
let s1_stack = graph.intern_external(s1, LayerStackId::ROOT).0;
let s2_stack = graph.intern_external(s2, LayerStackId::ROOT).0;
assert_ne!(s1_stack, s2_stack, "the sources are distinct stacks");
let (t1, fresh1) = graph.intern_external(target, s1_stack);
let (t2, fresh2) = graph.intern_external(target, s2_stack);
assert!(fresh1 && fresh2, "each authoring source mints its own instance");
assert_ne!(t1, t2, "equal composed maps do not coalesce distinct sources");
assert_eq!(
graph.stack_expression_variables(t1),
graph.stack_expression_variables(t2),
"both instances compose the same variables"
);
}
/// Non-authoring stacks propagate their source: a stack whose own variables
/// change nothing reuses its seed's source (the C++
/// `Pcp_ComposeExpressionVariables` rule), so arcs into the same target
/// through a parallel intermediate and through a chained one all carry the
/// Root source and share the Root-sourced instance.
#[test]
fn source_propagates_noop() {
let root = sdf::Layer::new_in_memory("root.usda");
let m1 = sdf::Layer::new_in_memory("m1.usda");
let m2 = sdf::Layer::new_in_memory("m2.usda");
let target = sdf::Layer::new_in_memory("target.usda");
let mut graph = LayerGraph::from_layers(vec![root, m1, m2, target], 0, sdf::LayerRegistry::default());
let m1 = graph.id_of("m1.usda").unwrap();
let m2 = graph.id_of("m2.usda").unwrap();
let target = graph.id_of("target.usda").unwrap();
let m1_stack = graph.intern_external(m1, LayerStackId::ROOT).0;
let m2_stack = graph.intern_external(m2, m1_stack).0;
assert_ne!(m1_stack, m2_stack, "the intermediates are distinct stacks");
let t1 = graph.intern_external(target, m1_stack).0;
let t2 = graph.intern_external(target, m2_stack).0;
assert_eq!(t1, t2, "the parallel and chained routes key the same instance");
assert_eq!(
t1,
graph.intern_external(target, LayerStackId::ROOT).0,
"the shared instance is the Root-sourced one"
);
}
/// A stack's value identity round-trips: the captured source chain resolves
/// back to the same instance on the same graph, re-deriving each hop from
/// live content rather than trusting the numeric handle; the root stack's
/// identity is total and maps to ROOT.
#[test]
fn stack_identity_roundtrip() {
let root = sdf::Layer::new_in_memory("root.usda");
let mut src = sdf::Layer::new_in_memory("src.usda");
set_expr_var(&mut src, "V", "x");
let target = sdf::Layer::new_in_memory("target.usda");
let mut graph = LayerGraph::from_layers(vec![root, src, target], 0, sdf::LayerRegistry::default());
let src = graph.id_of("src.usda").unwrap();
let target = graph.id_of("target.usda").unwrap();
let src_stack = graph.intern_external(src, LayerStackId::ROOT).0;
let t = graph.intern_external(target, src_stack).0;
let identity = graph.stack_identity(t);
assert_eq!(
identity,
StackIdentity::Target {
root: "target.usda".to_string(),
source_chain: vec!["src.usda".to_string()],
}
);
assert_eq!(graph.resolve_stack_identity(&identity).ok(), Some(t));
let root_identity = graph.stack_identity(LayerStackId::ROOT);
assert_eq!(root_identity, StackIdentity::Root);
assert_eq!(
graph.resolve_stack_identity(&root_identity).ok(),
Some(LayerStackId::ROOT)
);
}
/// An `expressionVariables` edit on a source stack's root refreshes every
/// stack keyed by it in place: the seed is read live from the source
/// instance during the rebuild, so the dependent's stored composed set and
/// members follow the edit while its id — and thus its arc keying — stays
/// stable.
#[test]
fn source_chain_rebuild() {
let root = sdf::Layer::new_in_memory("root.usda");
let mut src = sdf::Layer::new_in_memory("src.usda");
set_expr_var(&mut src, "V", "a");
let mut target = sdf::Layer::new_in_memory("target.usda");
edit_layer(&mut target, |e| {
e.pseudo_root_mut().unwrap().set_sublayers([r#"`"${V}.usda"`"#]);
});
let a = sdf::Layer::new_in_memory("a.usda");
let b = sdf::Layer::new_in_memory("b.usda");
let mut graph = LayerGraph::from_layers(vec![root, src, target, a, b], 0, sdf::LayerRegistry::default());
let src = graph.id_of("src.usda").unwrap();
let target = graph.id_of("target.usda").unwrap();
let a = graph.id_of("a.usda").unwrap();
let b = graph.id_of("b.usda").unwrap();
let src_stack = graph.intern_external(src, LayerStackId::ROOT).0;
let t_stack = graph.intern_external(target, src_stack).0;
let members = |graph: &LayerGraph, id: LayerStackId| -> Vec<LayerId> {
graph.layer_stack(id).iter().map(|&(l, _)| l).collect()
};
assert!(members(&graph, t_stack).contains(&a), "V=a selects a.usda");
set_expr_var(&mut graph.nodes.get_mut(&src).unwrap().layer, "V", "b");
graph.recompute_sublayers(Some(&HashSet::from([src])));
let (resolved, fresh) = graph.intern_external(target, src_stack);
assert!(!fresh, "the edit re-keys nothing; the instance is reused");
assert_eq!(resolved, t_stack, "the arc still resolves the same instance");
assert_eq!(
graph.stack_expression_variables(t_stack),
&HashMap::from([("V".to_string(), Value::String("b".to_string()))]),
"the stored composed set follows the source edit"
);
let m = members(&graph, t_stack);
assert!(
m.contains(&b) && !m.contains(&a),
"the members re-resolve under the new seed: {m:?}"
);
}
/// Removing a source's authored variables flips its variable source back to
/// its seed's, re-keying future arcs: the previously minted contextual
/// target instance is stranded — still interned and rebuilt in place — while
/// new arcs resolve the Root-sourced instance.
#[test]
fn vars_source_flip() {
let root = sdf::Layer::new_in_memory("root.usda");
let mut src = sdf::Layer::new_in_memory("src.usda");
set_expr_var(&mut src, "V", "a");
let mut target = sdf::Layer::new_in_memory("target.usda");
edit_layer(&mut target, |e| {
e.pseudo_root_mut().unwrap().set_sublayers([r#"`"${V}.usda"`"#]);
});
let a = sdf::Layer::new_in_memory("a.usda");
let mut graph = LayerGraph::from_layers(vec![root, src, target, a], 0, sdf::LayerRegistry::default());
let src = graph.id_of("src.usda").unwrap();
let target = graph.id_of("target.usda").unwrap();
let a = graph.id_of("a.usda").unwrap();
let src_stack = graph.intern_external(src, LayerStackId::ROOT).0;
let (old_t, fresh) = graph.intern_external(target, src_stack);
assert!(fresh, "the authoring source mints a contextual instance");
edit_layer(&mut graph.nodes.get_mut(&src).unwrap().layer, |e| {
e.pseudo_root_mut().unwrap().set(
FieldKey::ExpressionVariables.as_str(),
Value::Dictionary(HashMap::new()),
);
});
graph.recompute_sublayers(Some(&HashSet::from([src])));
let new_t = graph.intern_external(target, src_stack).0;
assert_ne!(
new_t, old_t,
"the flipped source re-keys the arc to the Root-sourced instance"
);
assert!(
!graph.layer_stack(old_t).iter().any(|&(l, _)| l == a),
"the stranded instance was still rebuilt: its seed no longer selects a.usda"
);
}
/// A back-reference to the stage root layer does not collapse to ROOT when
/// session layers are present: the identities differ (the ROOT instance
/// carries the session region), so a `{root layer, Root}` instance is minted
/// without the session layers.
#[test]
fn backref_no_session_collapse() {
let session = sdf::Layer::new_in_memory("session.usda");
let root = sdf::Layer::new_in_memory("root.usda");
let mut graph = LayerGraph::from_layers(vec![session, root], 1, sdf::LayerRegistry::default());
let session = graph.id_of("session.usda").unwrap();
let root = graph.root_id().unwrap();
let id = graph.intern_external(root, LayerStackId::ROOT).0;
assert_ne!(id, LayerStackId::ROOT, "session layers keep the identities apart");
let members: Vec<LayerId> = graph.layer_stack(id).iter().map(|&(l, _)| l).collect();
assert!(
members.contains(&root) && !members.contains(&session),
"the back-reference stack is the root region without the session: {members:?}"
);
}
/// A sublayer-DAG root's eagerly minted stack composes under the stage root
/// stack's variables: its identity's variable source is the root (C++: an
/// identifier with no explicit override source), so a var-authoring stage
/// root selects `${V}` sublayers inside plain targets too, and an arc from
/// the root stack shares the eager instance instead of minting a duplicate.
#[test]
fn eager_mint_root_vars() {
let mut root = sdf::Layer::new_in_memory("root.usda");
set_expr_var(&mut root, "V", "leaf");
let mut target = sdf::Layer::new_in_memory("target.usda");
edit_layer(&mut target, |e| {
e.pseudo_root_mut().unwrap().set_sublayers([r#"`"${V}.usda"`"#]);
});
let leaf = sdf::Layer::new_in_memory("leaf.usda");
let mut graph = LayerGraph::from_layers(vec![root, target, leaf], 0, sdf::LayerRegistry::default());
let target = graph.id_of("target.usda").unwrap();
let leaf = graph.id_of("leaf.usda").unwrap();
let ids: Vec<LayerId> = graph.sublayer_stack(target).iter().map(|&(id, _)| id).collect();
assert!(
ids.contains(&leaf),
"the root's V seeds the eager target stack, selecting leaf.usda: {ids:?}"
);
let (id, fresh) = graph.intern_external(target, LayerStackId::ROOT);
assert!(!fresh, "an arc from the root stack resolves the eager instance");
assert_eq!(graph.layer_stack(id), &*graph.sublayer_stack(target));
}
/// A `${VAR}` sublayer selected by a reference target's own variable appears
/// in the expression ancestry edges: the edge resolves against the target
/// stack's composed variables (its root's own overlaid by the seed), so mute
/// fanout can find the target root from the selected sublayer.
#[test]
fn target_own_var_ancestry_edge() {
let root = sdf::Layer::new_in_memory("root.usda");
let mut target = sdf::Layer::new_in_memory("target.usda");
set_expr_var(&mut target, "V", "sub");
edit_layer(&mut target, |e| {
e.pseudo_root_mut().unwrap().set_sublayers([r#"`"${V}.usda"`"#]);
});
let sub = sdf::Layer::new_in_memory("sub.usda");
let graph = LayerGraph::from_layers(vec![root, target, sub], 0, sdf::LayerRegistry::default());
let target = graph.id_of("target.usda").unwrap();
let sub = graph.id_of("sub.usda").unwrap();
let edges = graph.expression_ancestry_edges();
assert!(
edges.get(&target).is_some_and(|children| children.contains(&sub)),
"the target's own V resolves the `${{V}}` ancestry edge: {edges:?}"
);
}
/// The stage's own root layer is never contextually reopened: a
/// context-bearing back-reference to a root with a `${VAR}` sublayer interns
/// from the loaded graph instead of demanding a disk re-read, which would
/// fail for an in-memory root and discard unsaved edits for a dirty one.
#[test]
fn root_never_reopened() {
let mut root = sdf::Layer::new_in_memory("root.usda");
edit_layer(&mut root, |e| {
e.pseudo_root_mut().unwrap().set_sublayers([r#"`"${V}.usda"`"#]);
});
let mut src = sdf::Layer::new_in_memory("src.usda");
set_expr_var(&mut src, "V", "x");
let mut graph = LayerGraph::from_layers(vec![root, src], 0, sdf::LayerRegistry::default());
let root = graph.root_id().unwrap();
let src = graph.id_of("src.usda").unwrap();
let ctx = graph.intern_external(src, LayerStackId::ROOT).0;
assert!(
!graph.needs_contextual_open(root, ctx),
"a context-bearing back-reference to the stage root must not trigger a reopen"
);
}
/// The arms of a sublayer diamond: `x_arm` and `y_arm` each author a conflicting
/// `V` on themselves and sublayer `shared`, whose `${V}` sublayer resolves
/// against the stack root's variables — not these sublayer-authored ones. Add
/// them under a root that sublayers `[x_arm.usda, y_arm.usda]`.
fn diamond_arms() -> Vec<sdf::Layer> {
let mut x_arm = sdf::Layer::new_in_memory("x_arm.usda");
set_expr_var(&mut x_arm, "V", "x_leaf");
edit_layer(&mut x_arm, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["shared.usda"]);
});
let mut y_arm = sdf::Layer::new_in_memory("y_arm.usda");
set_expr_var(&mut y_arm, "V", "y_leaf");
edit_layer(&mut y_arm, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["shared.usda"]);
});
let mut shared = sdf::Layer::new_in_memory("shared.usda");
edit_layer(&mut shared, |e| {
e.pseudo_root_mut().unwrap().set_sublayers([r#"`"${V}.usda"`"#]);
});
let x_leaf = sdf::Layer::new_in_memory("x_leaf.usda");
let y_leaf = sdf::Layer::new_in_memory("y_leaf.usda");
vec![x_arm, y_arm, shared, x_leaf, y_leaf]
}
/// A sublayer diamond whose two arms author conflicting `${V}` values resolves
/// to neither leaf: the arms are sublayers, so their `V` is ignored (a stack's
/// variables come from its root, C++ `PcpExpressionVariables`) and `shared`'s
/// `${V}` has nothing to resolve against. The public `sublayer_stack` query and
/// the composed `root_layer_stack` agree, both going through the one stack-level
/// expansion.
#[test]
fn diamond_sublayer_vars_ignored() {
let mut root = sdf::Layer::new_in_memory("root.usda");
edit_layer(&mut root, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["x_arm.usda", "y_arm.usda"]);
});
let mut layers = vec![root];
layers.extend(diamond_arms());
let graph = LayerGraph::from_layers(layers, 0, sdf::LayerRegistry::default());
let x_leaf = graph.id_of("x_leaf.usda").unwrap();
let y_leaf = graph.id_of("y_leaf.usda").unwrap();
let ids: Vec<LayerId> = graph.root_layer_stack().iter().map(|&(id, _)| id).collect();
assert!(
!ids.contains(&x_leaf) && !ids.contains(&y_leaf),
"the arms' `V` is sublayer-authored, so `${{V}}` resolves to neither leaf: {ids:?}",
);
let root_id = graph.root_id().unwrap();
let queried: Vec<LayerId> = graph.sublayer_stack(root_id).iter().map(|&(id, _)| id).collect();
assert_eq!(queried, ids, "sublayer_stack matches the composed root stack");
}
/// Overrides win over the stack root's own variables, but an unrelated override
/// leaves the root's variable in place (C++ `PcpExpressionVariables`). A
/// reference target authoring `V=a` and a `${V}` sublayer resolves to `b` under
/// a source authoring `V=b`, and back to `a` under a source authoring an
/// unrelated variable.
#[test]
fn override_precedence() {
let root = sdf::Layer::new_in_memory("root.usda");
let mut over = sdf::Layer::new_in_memory("over.usda");
set_expr_var(&mut over, "V", "b");
let mut unrelated = sdf::Layer::new_in_memory("unrelated.usda");
set_expr_var(&mut unrelated, "OTHER", "z");
let mut target = sdf::Layer::new_in_memory("target.usda");
set_expr_var(&mut target, "V", "a");
edit_layer(&mut target, |e| {
e.pseudo_root_mut().unwrap().set_sublayers([r#"`"${V}.usda"`"#]);
});
let a = sdf::Layer::new_in_memory("a.usda");
let b = sdf::Layer::new_in_memory("b.usda");
let mut graph = LayerGraph::from_layers(
vec![root, over, unrelated, target, a, b],
0,
sdf::LayerRegistry::default(),
);
let over = graph.id_of("over.usda").unwrap();
let unrelated = graph.id_of("unrelated.usda").unwrap();
let target = graph.id_of("target.usda").unwrap();
let a_id = graph.id_of("a.usda").unwrap();
let b_id = graph.id_of("b.usda").unwrap();
let members = |graph: &LayerGraph, id: LayerStackId| -> Vec<LayerId> {
graph.layer_stack(id).iter().map(|&(l, _)| l).collect()
};
let over_stack = graph.intern_external(over, LayerStackId::ROOT).0;
let id = graph.intern_external(target, over_stack).0;
let m = members(&graph, id);
assert!(
m.contains(&b_id) && !m.contains(&a_id),
"the source's V=b wins over the root's V=a: {m:?}"
);
let unrelated_stack = graph.intern_external(unrelated, LayerStackId::ROOT).0;
let id = graph.intern_external(target, unrelated_stack).0;
let m = members(&graph, id);
assert!(
m.contains(&a_id) && !m.contains(&b_id),
"an unrelated override keeps the root's V=a: {m:?}"
);
}
/// A `${VAR}` sublayer resolved by a **root**-authored variable back to an
/// ancestor is a cycle, and it is reported once. The root authors `BACK=root`
/// and sublayers `a`, whose `${BACK}` sublayer resolves to `root.usda`, closing a
/// `root → a → root` cycle. Each layer still composes once.
#[test]
fn root_var_sublayer_cycle() {
let mut root = sdf::Layer::new_in_memory("root.usda");
set_expr_var(&mut root, "BACK", "root");
edit_layer(&mut root, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["a.usda"]);
});
let mut a = sdf::Layer::new_in_memory("a.usda");
edit_layer(&mut a, |e| {
e.pseudo_root_mut().unwrap().set_sublayers([r#"`"${BACK}.usda"`"#]);
});
let graph = LayerGraph::from_layers(vec![root, a], 0, sdf::LayerRegistry::default());
let root_id = graph.root_id().unwrap();
let a_id = graph.id_of("a.usda").unwrap();
let cycles = graph
.errors()
.iter()
.filter(|e| matches!(e, Error::SublayerCycle { .. }))
.count();
assert_eq!(cycles, 1, "the root<->a cycle is reported once: {:?}", graph.errors());
let ids: Vec<LayerId> = graph.root_layer_stack().iter().map(|&(id, _)| id).collect();
assert_eq!(
ids.iter().filter(|&&id| id == root_id).count(),
1,
"root composes once: {ids:?}"
);
assert_eq!(
ids.iter().filter(|&&id| id == a_id).count(),
1,
"a composes once: {ids:?}"
);
}
/// Editing the **stack root**'s `expressionVariables` re-resolves its `${V}`
/// sublayer: the root is a member of its stack, so the scoped rebuild recomposes
/// it. (A sublayer's variables would be ignored; only the root's apply.)
#[test]
fn edit_root_var_rebuilds() {
let mut root = sdf::Layer::new_in_memory("root.usda");
set_expr_var(&mut root, "V", "leaf");
edit_layer(&mut root, |e| {
e.pseudo_root_mut().unwrap().set_sublayers([r#"`"${V}.usda"`"#]);
});
let leaf = sdf::Layer::new_in_memory("leaf.usda");
let leaf2 = sdf::Layer::new_in_memory("leaf2.usda");
let mut graph = LayerGraph::from_layers(vec![root, leaf, leaf2], 0, sdf::LayerRegistry::default());
let root_id = graph.root_id().unwrap();
let leaf = graph.id_of("leaf.usda").unwrap();
let leaf2 = graph.id_of("leaf2.usda").unwrap();
let ids: Vec<LayerId> = graph.root_layer_stack().iter().map(|&(id, _)| id).collect();
assert!(
ids.contains(&leaf) && !ids.contains(&leaf2),
"the root's V starts at leaf: {ids:?}"
);
set_expr_var(&mut graph.nodes.get_mut(&root_id).unwrap().layer, "V", "leaf2");
graph.recompute_sublayers(Some(&HashSet::from([root_id])));
let ids: Vec<LayerId> = graph.root_layer_stack().iter().map(|&(id, _)| id).collect();
assert!(
ids.contains(&leaf2) && !ids.contains(&leaf),
"the edit to the root's V re-resolves `${{V}}` to leaf2: {ids:?}",
);
}
/// A plain target stack, rebuilt after an edit adds a branch reaching an
/// expression sublayer, picks it up: `has_expr_sublayer` gates on the current
/// `children`, and the branch's `${V}` resolves against the target root's own
/// variable.
#[test]
fn plain_target_new_branch() {
let root = sdf::Layer::new_in_memory("root.usda");
let mut target = sdf::Layer::new_in_memory("target.usda");
set_expr_var(&mut target, "V", "leaf");
edit_layer(&mut target, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["base.usda"]);
});
let base = sdf::Layer::new_in_memory("base.usda");
let mut expr_mid = sdf::Layer::new_in_memory("expr_mid.usda");
edit_layer(&mut expr_mid, |e| {
e.pseudo_root_mut().unwrap().set_sublayers([r#"`"${V}.usda"`"#]);
});
let leaf = sdf::Layer::new_in_memory("leaf.usda");
let mut graph = LayerGraph::from_layers(
vec![root, target, base, expr_mid, leaf],
0,
sdf::LayerRegistry::default(),
);
let target_id = graph.id_of("target.usda").unwrap();
let base_id = graph.id_of("base.usda").unwrap();
let leaf = graph.id_of("leaf.usda").unwrap();
// `target` is a DAG root, so its plain stack is interned; no expression
// sublayer is reachable yet.
let ids: Vec<LayerId> = graph.sublayer_stack(target_id).iter().map(|&(id, _)| id).collect();
assert!(!ids.contains(&leaf), "no expression branch reachable yet: {ids:?}");
// Add the expression branch under `base` and rebuild with `base` edited: it
// is a member of the interned target stack, so that stack rebuilds.
edit_layer(&mut graph.nodes.get_mut(&base_id).unwrap().layer, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["expr_mid.usda"]);
});
graph.recompute_sublayers(Some(&HashSet::from([base_id])));
let ids: Vec<LayerId> = graph.sublayer_stack(target_id).iter().map(|&(id, _)| id).collect();
assert!(
ids.contains(&leaf),
"the rebuilt target reaches `${{V}}` and resolves it against the target root's V: {ids:?}",
);
}
/// A sublayer interned after the first edge build is picked up on the next
/// rebuild. `resolve_edges` resolves the authored `./leaf.usda` through the
/// memoizing [`resolve_sublayer`](LayerGraph::resolve_sublayer) and looks the
/// resolved identifier up live, so a target missing at first resolves once it
/// is interned — the cache never pins the earlier miss.
#[test]
fn rebuild_resolves_newly_interned_sublayer() {
let mut root = sdf::Layer::new_in_memory("root.usda");
edit_layer(&mut root, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["./leaf.usda"]);
});
let mut graph = LayerGraph::from_layers(vec![root], 0, sdf::LayerRegistry::default());
let root_id = graph.root_id().unwrap();
assert_eq!(
graph.sublayer_stack(root_id).len(),
1,
"the not-yet-interned sublayer contributes no edge"
);
graph.ensure_layer(sdf::Layer::new_in_memory("leaf.usda"));
graph.recompute_sublayers(None);
let leaf = graph.id_of("leaf.usda").unwrap();
let ids: Vec<LayerId> = graph.sublayer_stack(root_id).iter().map(|&(id, _)| id).collect();
assert_eq!(
ids,
vec![root_id, leaf],
"the newly interned sublayer resolves on rebuild"
);
}
/// Relocate conflicts are scoped to the stack being composed. A layer that is
/// weak in one stack can still contribute when referenced as its own stack.
#[test]
fn mute_keeps_relocate_scope() {
let reloc = |id: &str, source: &str, target: &str| {
let mut layer = sdf::Layer::new_in_memory(id);
edit_layer(&mut layer, |e| {
e.set_relocates(vec![(Path::new(source).unwrap(), Path::new(target).unwrap())])
.unwrap();
});
layer
};
let root = sdf::Layer::new_in_memory("root.usda");
let mut combo = sdf::Layer::new_in_memory("combo.usda");
edit_layer(&mut combo, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["s1.usda", "s2.usda"]);
});
// s1 and s2 relocate different sources to the same target, conflicting
// within combo's stack so both are dropped while combo is present.
let s1 = reloc("s1.usda", "/W/A", "/W/C");
let s2 = reloc("s2.usda", "/W/B", "/W/C");
let mut graph = LayerGraph::from_layers(vec![root, combo, s1, s2], 0, sdf::LayerRegistry::default());
let combo_id = graph.id_of("combo.usda").unwrap();
let s1_id = graph.id_of("s1.usda").unwrap();
let s2_id = graph.id_of("s2.usda").unwrap();
// The sub-stack handles are minted on demand at the load barrier in
// production; these direct relocate queries compose nothing, so mint them
// via `intern_external` under the root context. The handles stay valid
// across the mute below (the registry refreshes instances in place).
let combo_stack = graph.intern_external(combo_id, LayerStackId::ROOT).0;
let s1_stack = graph.intern_external(s1_id, LayerStackId::ROOT).0;
let s2_stack = graph.intern_external(s2_id, LayerStackId::ROOT).0;
assert_eq!(
graph.relocation_source(combo_stack, &Path::new("/W/C").unwrap()),
None,
"combo's stack drops the same-target relocates"
);
assert_eq!(
graph.relocation_source(s1_stack, &Path::new("/W/C").unwrap()),
Some(Path::new("/W/A").unwrap()),
"s1's own stack keeps its authored relocate active"
);
let change = graph
.mute_layer("combo.usda".to_string())
.expect("muting combo changed the set");
assert_eq!(
change.affected,
HashSet::from([combo_id]),
"muting combo affects only stacks that include combo"
);
assert_eq!(
graph.relocation_source(s2_stack, &Path::new("/W/C").unwrap()),
Some(Path::new("/W/B").unwrap()),
"s2's own stack keeps its authored relocate active"
);
}
/// An authored relative path anchors against its parent's identifier and
/// resolves to the layer interned under the canonical (absolute) identifier
/// the load path would have produced; an unrelated leaf resolves to `None`.
/// On-disk files are used so the resolver canonicalizes the `./` and bare
/// spellings to the same absolute identifier the sublayer is interned under.
#[test]
fn find_relative_resolves_authored() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("root.usda"), b"#usda 1.0\n").unwrap();
std::fs::write(tmp.path().join("sub.usda"), b"#usda 1.0\n").unwrap();
let canonical = |leaf: &str| {
tmp.path()
.join(leaf)
.canonicalize()
.unwrap()
.to_string_lossy()
.into_owned()
};
let graph = LayerGraph::from_layers(
vec![
sdf::Layer::new(canonical("root.usda"), Box::new(sdf::Data::new())),
sdf::Layer::new(canonical("sub.usda"), Box::new(sdf::Data::new())),
],
0,
sdf::LayerRegistry::default(),
);
let root_id = graph.root_id().unwrap();
let sub_id = graph.id_of(&canonical("sub.usda")).unwrap();
assert_eq!(graph.find_relative("sub.usda", root_id), Some(sub_id));
assert_eq!(graph.find_relative("./sub.usda", root_id), Some(sub_id));
assert_eq!(graph.find_relative("missing.usda", root_id), None);
}
/// When anchoring finds no interned layer, resolution falls back to the bare
/// authored string, so an in-memory graph keyed by literal identifiers still
/// composes. A directory-bearing parent (`/proj/root.usda`) anchors the bare
/// `sub.usda` to `/proj/sub.usda`; with nothing interned there, the fallback
/// matches the child interned under the literal `sub.usda`.
#[test]
fn find_relative_falls_back_to_bare_interned() {
let mut root = sdf::Layer::new_in_memory("/proj/root.usda");
edit_layer(&mut root, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["sub.usda"]);
});
let sub = sdf::Layer::new_in_memory("sub.usda");
let graph = LayerGraph::from_layers(vec![root, sub], 0, sdf::LayerRegistry::default());
let root_id = graph.root_id().unwrap();
let sub_id = graph.id_of("sub.usda").unwrap();
assert_eq!(graph.find_relative("sub.usda", root_id), Some(sub_id));
let ids: Vec<LayerId> = graph.sublayer_stack(root_id).iter().map(|&(id, _)| id).collect();
assert_eq!(
ids,
vec![root_id, sub_id],
"the bare-named sublayer edge forms via the bare-id fallback"
);
}
/// When both the anchored target and an unrelated layer interned under the
/// bare authored string are present, the anchored identifier wins: a relative
/// sublayer resolves to the asset USD anchors it to, not to the colliding
/// bare-named layer. On-disk files give the parent a real location so its
/// relative `sub.usda` canonicalizes to the interned anchored layer.
#[test]
fn find_relative_prefers_anchored_over_bare_collision() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("root.usda"), b"#usda 1.0\n").unwrap();
std::fs::write(tmp.path().join("sub.usda"), b"#usda 1.0\n").unwrap();
let canonical = |leaf: &str| {
tmp.path()
.join(leaf)
.canonicalize()
.unwrap()
.to_string_lossy()
.into_owned()
};
let graph = LayerGraph::from_layers(
vec![
sdf::Layer::new(canonical("root.usda"), Box::new(sdf::Data::new())),
sdf::Layer::new(canonical("sub.usda"), Box::new(sdf::Data::new())),
// An unrelated layer interned under the bare authored string.
sdf::Layer::new("sub.usda", Box::new(sdf::Data::new())),
],
0,
sdf::LayerRegistry::default(),
);
let root_id = graph.root_id().unwrap();
let anchored_id = graph.id_of(&canonical("sub.usda")).unwrap();
assert_eq!(
graph.find_relative("sub.usda", root_id),
Some(anchored_id),
"the relative entry resolves to the anchored on-disk asset, not the colliding bare layer",
);
}
/// A leading `./` is normalized before resolution, so a dot-relative entry
/// resolves to a bare-interned child. Anchoring `./sub.usda` against
/// `/proj/root.usda` yields `/proj/sub.usda`; with nothing interned there, the
/// normalized bare `sub.usda` matches via the fallback.
#[test]
fn find_relative_strips_dot() {
let mut root = sdf::Layer::new_in_memory("/proj/root.usda");
edit_layer(&mut root, |e| {
e.pseudo_root_mut().unwrap().set_sublayers(["./sub.usda"]);
});
let sub = sdf::Layer::new_in_memory("sub.usda");
let graph = LayerGraph::from_layers(vec![root, sub], 0, sdf::LayerRegistry::default());
let root_id = graph.root_id().unwrap();
let sub_id = graph.id_of("sub.usda").unwrap();
assert_eq!(graph.find_relative("./sub.usda", root_id), Some(sub_id));
assert_eq!(
graph.find_relative("././sub.usda", root_id),
Some(sub_id),
"repeated leading `./` is normalized too"
);
let ids: Vec<LayerId> = graph.sublayer_stack(root_id).iter().map(|&(id, _)| id).collect();
assert_eq!(
ids,
vec![root_id, sub_id],
"the dot-relative entry resolves to the bare-interned child"
);
}
/// `.` path segments are dropped, anywhere in an asset path, rendered with
/// `/` separators — matching the resolver's anchored normalization so the
/// exact and anchored lookups agree. On Windows a `\`-spelled `.` segment is
/// recognized too, since `std::path` (and thus the resolver) treats `\` as a
/// separator there.
#[test]
fn dot_segments_normalized() {
assert_eq!(&*without_dot_segments("./sub.usda"), "sub.usda");
assert_eq!(&*without_dot_segments("././sub.usda"), "sub.usda");
assert_eq!(&*without_dot_segments("dir/./sub.usda"), "dir/sub.usda");
assert_eq!(&*without_dot_segments("/abs/./path"), "/abs/path");
assert_eq!(
&*without_dot_segments("sub.usda"),
"sub.usda",
"no `.` segment is unchanged"
);
#[cfg(windows)]
{
assert_eq!(&*without_dot_segments(".\\sub.usda"), "sub.usda");
assert_eq!(&*without_dot_segments("dir\\.\\sub.usda"), "dir/sub.usda");
}
}
/// `find_relative` follows the resolver's canonicalization rather than raw
/// path matching: a resolver that aliases an authored `link.usda` to a fixed
/// canonical leaf resolves the authored name to the layer interned under that
/// different leaf — what a symlinked or repository-aliased sublayer needs.
#[test]
fn find_relative_follows_resolver_canonicalization() {
let registry = sdf::LayerRegistry::new(Box::new(LinkResolver {
inner: ar::DefaultResolver::new(),
}));
let graph = LayerGraph::from_layers(
vec![
sdf::Layer::new("/canonical/root.usda", Box::new(sdf::Data::new())),
sdf::Layer::new("/canonical/real.usda", Box::new(sdf::Data::new())),
],
0,
registry,
);
let root_id = graph.root_id().unwrap();
let real_id = graph.id_of("/canonical/real.usda").unwrap();
assert_eq!(
graph.find_relative("link.usda", root_id),
Some(real_id),
"the authored leaf resolves through the resolver to the canonical layer"
);
}
/// A resolver whose `create_identifier` aliases an authored `link.usda` to a
/// fixed canonical leaf, modeling a symlinked or repository-aliased asset the
/// resolver canonicalizes away. Every other path falls through to the default
/// filesystem behavior.
struct LinkResolver {
inner: ar::DefaultResolver,
}
impl ar::Resolver for LinkResolver {
fn create_identifier(&self, asset_path: &str, anchor: Option<&ResolvedPath>) -> String {
if asset_path.ends_with("link.usda") {
"/canonical/real.usda".to_string()
} else {
self.inner.create_identifier(asset_path, anchor)
}
}
fn resolve(&self, asset_path: &str) -> Option<ResolvedPath> {
self.inner.resolve(asset_path)
}
fn resolve_for_new_asset(&self, asset_path: &str) -> Option<ResolvedPath> {
self.inner.resolve_for_new_asset(asset_path)
}
fn open_asset(&self, resolved_path: &ResolvedPath) -> io::Result<Box<dyn ar::Asset>> {
self.inner.open_asset(resolved_path)
}
}
}