shifty-engine 0.2.6

SHACL validation and SHACL-AF inference execution over the IR
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
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
//! W3C `sh:ValidationReport` generation (component-granular, RDF-driven).
//!
//! Producing a spec-faithful report needs provenance the optimized algebra
//! discards: each result carries `sh:sourceConstraintComponent`,
//! `sh:sourceShape`, and `sh:resultPath`, and the granularity is one result per
//! (focus, value node, component) — `sh:and`/`sh:or`/`sh:not`/`sh:node` report
//! as a *unit* (they do not drill into sub-failures), while `sh:property`
//! delegates to the nested shape. So this validator walks the shapes graph
//! directly, reusing only the leaf evaluation primitives (`succ`,
//! `value_type_holds`). It is separate from the algebra path used for fast
//! conformance.
//!
//! Coverage is a growing subset of SHACL Core (see `docs/BACKLOG.md`).

use crate::frozen::FrozenIndexedDataset;
use crate::path::succ;
use crate::sparql::{FunctionDef, SparqlExecutor};
use crate::validate::{
    UnsupportedPolicy, ValidationGraphMode, ValidationOptions, apply_message_template,
    entry_shape_name_selected, graph_union, is_boolean_true,
};
use crate::value::{compare_terms, value_type_holds};
use oxrdf::{BlankNode, Graph, Literal, NamedNode, NamedNodeRef, NamedOrBlankNode, Term, Triple};
use shifty_algebra::value_type::{Bound, ValueType};
use shifty_algebra::{NodeKindSet, Path, Severity, SparqlConstraint, SparqlQueryKind};
use shifty_parse::graph::{Loaded, term_to_node};
use shifty_parse::lower::canonical_sparql_query;
use shifty_parse::path::parse_path;
use shifty_parse::vocab;
use std::cell::RefCell;
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};

/// One `sh:ValidationResult`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ValidationResult {
    pub focus: Term,
    /// `sh:resultPath` as the original RDF node (predicate IRI for simple paths).
    pub path: Option<Term>,
    pub value: Option<Term>,
    pub component: NamedNode,
    pub source_shape: Term,
    /// `sh:resultSeverity` — the `sh:severity` declared on the source shape,
    /// defaulting to `sh:Violation`.
    pub severity: NamedNode,
    /// `sh:resultMessage` — copied from `sh:message` on the source shape.
    pub messages: Vec<Term>,
}

#[derive(Debug, Clone)]
pub struct ValidationReport {
    pub conforms: bool,
    pub results: Vec<ValidationResult>,
}

/// The observed binding of one `sh:property` shape at one *conforming* focus
/// node — the inverse of a violation: not what failed, but what a passing
/// property shape's `sh:path` actually resolved to.
///
/// `key` identifies the property shape stably: the (deterministically first,
/// when several) value reached by evaluating `key_path` from the property
/// shape's own node over the shapes graph (e.g. a path to a
/// `zea:roleName "outsideAirTemp"`-style annotation) when `key_path` is given
/// and resolves to at least one value, otherwise the property shape's own
/// source node (so callers can still join on it by IRI/blank-node id).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PropertyWitness {
    pub focus: Term,
    /// The node shape (application profile) `focus` conforms to.
    pub shape: Term,
    pub key: Term,
    /// The `sh:path` value nodes, deduped. When the property shape carries a
    /// `sh:qualifiedValueShape`, this is filtered to the values that satisfy
    /// the qualifier (and, under `sh:qualifiedValueShapesDisjoint`, not any
    /// sibling qualifier) — the disambiguated binding rather than every raw
    /// path value.
    pub values: Vec<Term>,
}

/// Validate `data` against the shapes in `shapes`, producing a W3C report.
pub fn validate_report(shapes: &Loaded, data: &Graph) -> ValidationReport {
    validate_report_with_options(shapes, data, &ValidationOptions::default())
}

/// Evaluate a SPARQL expression (a `dash:expression` function-call string such
/// as `ex:fn("A", "B")`) against the `sh:SPARQLFunction`s declared in `shapes`,
/// returning the result term. Drives `dash:FunctionTestCase`s and exposes SHACL
/// functions as a standalone capability. The document's prefixes and base form
/// the query prologue so prefixed function names resolve.
pub fn evaluate_function_expression(shapes: &Loaded, expr: &str) -> Result<Option<Term>, String> {
    let frozen = FrozenIndexedDataset::from_graph(&shapes.graph);
    let mut sparql = SparqlExecutor::from_frozen(frozen, false);
    // Expression evaluation is the function's own dataset-free path; register
    // every function (Ignore) so pure dash:expressions resolve.
    sparql.set_functions(collect_functions(shapes), UnsupportedPolicy::Ignore);
    let mut prologue = String::new();
    if let Some(base) = &shapes.base {
        prologue.push_str(&format!("BASE <{base}>\n"));
    }
    for (prefix, namespace) in &shapes.prefixes {
        prologue.push_str(&format!("PREFIX {prefix}: <{namespace}>\n"));
    }
    sparql.evaluate_expression(&prologue, expr)
}

/// Validate and build a W3C report using an explicit severity policy.
pub fn validate_report_with_options(
    shapes: &Loaded,
    data: &Graph,
    options: &ValidationOptions,
) -> ValidationReport {
    let has_shapes_graph = shapes_reference_shapes_graph(shapes);
    let frozen = if has_shapes_graph {
        FrozenIndexedDataset::from_graphs(data, &shapes.graph)
    } else {
        FrozenIndexedDataset::from_graph(data)
    };
    validate_report_context(shapes, data, frozen, has_shapes_graph, options)
}

/// Validate split data and shapes graphs using the selected graph mode.
pub fn validate_report_graphs(shapes: &Loaded, data: &Graph) -> ValidationReport {
    validate_report_graphs_with_mode_and_options(
        shapes,
        data,
        ValidationGraphMode::default(),
        &ValidationOptions::default(),
    )
}

/// Validate split data and shapes graphs using an explicit graph mode.
pub fn validate_report_graphs_with_mode(
    shapes: &Loaded,
    data: &Graph,
    mode: ValidationGraphMode,
) -> ValidationReport {
    validate_report_graphs_with_mode_and_options(shapes, data, mode, &ValidationOptions::default())
}

/// Validate split graphs with an explicit graph mode and severity policy.
pub fn validate_report_graphs_with_mode_and_options(
    shapes: &Loaded,
    data: &Graph,
    mode: ValidationGraphMode,
    options: &ValidationOptions,
) -> ValidationReport {
    let has_shapes_graph = shapes_reference_shapes_graph(shapes);
    match mode {
        ValidationGraphMode::Data => {
            let frozen = if has_shapes_graph {
                FrozenIndexedDataset::from_graphs(data, &shapes.graph)
            } else {
                FrozenIndexedDataset::from_graph(data)
            };
            validate_report_context(shapes, data, frozen, has_shapes_graph, options)
        }
        ValidationGraphMode::Union => {
            let frozen = if has_shapes_graph {
                FrozenIndexedDataset::from_graph_union_with_shapes(data, &shapes.graph)
            } else {
                FrozenIndexedDataset::from_graph_union(data, &shapes.graph)
            };
            validate_report_context(shapes, data, frozen, has_shapes_graph, options)
        }
        ValidationGraphMode::UnionAll => {
            let union = graph_union(data, &shapes.graph);
            let frozen = if has_shapes_graph {
                FrozenIndexedDataset::from_graphs(&union, &shapes.graph)
            } else {
                FrozenIndexedDataset::from_graph(&union)
            };
            validate_report_context(shapes, &union, frozen, has_shapes_graph, options)
        }
    }
}

/// Collect [`PropertyWitness`]es for every `sh:property` shape (reached
/// through `sh:property`, `sh:and`, and `sh:node` from a target/profile node
/// shape) at every focus node that *conforms* to that node shape — the
/// inverse of [`validate_report_graphs_with_mode`]. `key_path`, when given, is
/// evaluated from each property shape's own node *over the shapes graph* to
/// produce a stable `PropertyWitness::key`; property shapes where it resolves
/// to no value fall back to their own source node as the key.
pub fn property_witnesses_graphs_with_mode(
    shapes: &Loaded,
    data: &Graph,
    mode: ValidationGraphMode,
    key_path: Option<&Path>,
) -> Vec<PropertyWitness> {
    property_witnesses_graphs_with_mode_and_options(
        shapes,
        data,
        mode,
        key_path,
        &ValidationOptions::default(),
    )
}

/// [`property_witnesses_graphs_with_mode`] with an explicit severity policy,
/// so conformance agrees exactly with [`validate_report_graphs_with_mode_and_options`]
/// under the same options.
pub fn property_witnesses_graphs_with_mode_and_options(
    shapes: &Loaded,
    data: &Graph,
    mode: ValidationGraphMode,
    key_path: Option<&Path>,
    options: &ValidationOptions,
) -> Vec<PropertyWitness> {
    let has_shapes_graph = shapes_reference_shapes_graph(shapes);
    let (focus_data, frozen, union_owner);
    match mode {
        ValidationGraphMode::Data => {
            frozen = if has_shapes_graph {
                FrozenIndexedDataset::from_graphs(data, &shapes.graph)
            } else {
                FrozenIndexedDataset::from_graph(data)
            };
            focus_data = data;
        }
        ValidationGraphMode::Union => {
            frozen = if has_shapes_graph {
                FrozenIndexedDataset::from_graph_union_with_shapes(data, &shapes.graph)
            } else {
                FrozenIndexedDataset::from_graph_union(data, &shapes.graph)
            };
            focus_data = data;
        }
        ValidationGraphMode::UnionAll => {
            union_owner = graph_union(data, &shapes.graph);
            frozen = if has_shapes_graph {
                FrozenIndexedDataset::from_graphs(&union_owner, &shapes.graph)
            } else {
                FrozenIndexedDataset::from_graph(&union_owner)
            };
            focus_data = &union_owner;
        }
    }
    let r = build_reporter(shapes, focus_data, frozen, has_shapes_graph, options);
    let mut out = Vec::new();
    for shape in r.target_shapes() {
        let foci = r.focus_nodes(&shape);
        r.prefetch_sparql(&shape, &foci);
        for focus in &foci {
            let mut check = HashSet::new();
            let mut results = Vec::new();
            r.collect(&shape, focus, &mut results, &mut check, &[]);
            let conforms = !results.iter().any(|result| {
                Severity::from_named_node(result.severity.clone()).meets(&options.minimum_severity)
            });
            if !conforms {
                continue;
            }
            let mut visited = HashSet::new();
            r.collect_property_witnesses(&shape, focus, &shape, key_path, &mut visited, &mut out);
        }
    }
    out
}

/// Build the shared [`Reporter`] setup (SPARQL executor, class index, custom
/// components) used by both violation reporting and property witnessing, so
/// the two traversals stay in lockstep on what counts as "the shape holds".
fn build_reporter<'a>(
    shapes: &'a Loaded,
    focus_data: &'a Graph,
    frozen: FrozenIndexedDataset,
    has_shapes_graph: bool,
    options: &'a ValidationOptions,
) -> Reporter<'a> {
    // Only execute SPARQL target/constraint work when the shapes graph contains
    // those features. Query execution shares the frozen validation dataset.
    let needs_sparql = shapes
        .graph
        .triples_for_predicate(vocab::SH_SPARQL)
        .next()
        .is_some()
        || shapes
            .graph
            .triples_for_predicate(vocab::SH_TARGET)
            .next()
            .is_some();
    let mut sparql = SparqlExecutor::from_frozen(frozen, needs_sparql && has_shapes_graph);
    sparql.set_functions(collect_functions(shapes), options.engine.unsupported);
    // Index class membership once (instead of a forward scan over every node per
    // class-target shape): this is the report path's analogue of the plan's
    // backward `PathToConst` focus source, amortized across all shapes.
    let has_explicit_class_target = shapes
        .graph
        .triples_for_predicate(vocab::SH_TARGET_CLASS)
        .next()
        .is_some();
    let has_implicit_class_target = shapes.graph.iter().any(|triple| {
        let subject = triple.subject.into_owned();
        is_shape_node(shapes, &subject)
            && (shapes.is_instance_of(&subject, vocab::RDFS_CLASS)
                || shapes.is_instance_of(&subject, vocab::OWL_CLASS))
    });
    let needs_class_index = has_explicit_class_target || has_implicit_class_target;
    let class_index = if needs_class_index {
        build_class_index(
            focus_data,
            sparql
                .frozen()
                .expect("report validation always has a frozen dataset"),
        )
    } else {
        HashMap::new()
    };
    Reporter {
        shapes,
        focus_data,
        sparql,
        needs_sparql,
        class_index,
        path_cache: RefCell::new(HashMap::new()),
        components: build_components(shapes, options.engine.unsupported),
        entry_shape_names: &options.entry_shape_names,
    }
}

fn validate_report_context(
    shapes: &Loaded,
    focus_data: &Graph,
    frozen: FrozenIndexedDataset,
    has_shapes_graph: bool,
    options: &ValidationOptions,
) -> ValidationReport {
    let r = build_reporter(shapes, focus_data, frozen, has_shapes_graph, options);
    let mut results = Vec::new();
    for shape in r.target_shapes() {
        let foci = r.focus_nodes(&shape);
        r.prefetch_sparql(&shape, &foci);
        for focus in &foci {
            let mut visited = HashSet::new();
            r.collect(&shape, focus, &mut results, &mut visited, &[]);
        }
    }
    // Synthesize a default `sh:resultMessage` for any result whose source shape
    // (and its ancestry) declared no `sh:message`, so every violation carries a
    // human-readable explanation. Runs before sorting so content is order-free.
    for result in &mut results {
        if result.messages.is_empty() {
            let message = r.default_message(result);
            result.messages = vec![Term::Literal(Literal::new_simple_literal(message))];
        }
    }
    if options.sort_results {
        results.sort_by(|left, right| {
            Severity::from_named_node(right.severity.clone())
                .rank()
                .cmp(&Severity::from_named_node(left.severity.clone()).rank())
                .then_with(|| left.focus.to_string().cmp(&right.focus.to_string()))
                .then_with(|| {
                    left.source_shape
                        .to_string()
                        .cmp(&right.source_shape.to_string())
                })
                .then_with(|| left.component.as_str().cmp(right.component.as_str()))
        });
    }
    ValidationReport {
        conforms: !results.iter().any(|result| {
            Severity::from_named_node(result.severity.clone()).meets(&options.minimum_severity)
        }),
        results,
    }
}

/// Serialize a report as an RDF `sh:ValidationReport` graph (W3C shape).
pub fn report_to_graph(report: &ValidationReport) -> Graph {
    let mut g = Graph::new();
    let root = BlankNode::default();
    let t = |s: NamedOrBlankNode, p: NamedNodeRef, o: Term| Triple::new(s, p.into_owned(), o);

    g.insert(&t(
        root.clone().into(),
        vocab::RDF_TYPE,
        vocab::SH_VALIDATION_REPORT.into_owned().into(),
    ));
    g.insert(&t(
        root.clone().into(),
        vocab::SH_CONFORMS,
        Literal::from(report.conforms).into(),
    ));

    for r in &report.results {
        let rn = BlankNode::default();
        g.insert(&t(root.clone().into(), vocab::SH_RESULT, rn.clone().into()));
        g.insert(&t(
            rn.clone().into(),
            vocab::RDF_TYPE,
            vocab::SH_VALIDATION_RESULT.into_owned().into(),
        ));
        g.insert(&t(rn.clone().into(), vocab::SH_FOCUS_NODE, r.focus.clone()));
        if let Some(path) = &r.path {
            g.insert(&t(rn.clone().into(), vocab::SH_RESULT_PATH, path.clone()));
        }
        if let Some(value) = &r.value {
            g.insert(&t(rn.clone().into(), vocab::SH_VALUE, value.clone()));
        }
        g.insert(&t(
            rn.clone().into(),
            vocab::SH_RESULT_SEVERITY,
            r.severity.clone().into(),
        ));
        g.insert(&t(
            rn.clone().into(),
            vocab::SH_SOURCE_CONSTRAINT_COMPONENT,
            r.component.clone().into(),
        ));
        for msg in &r.messages {
            g.insert(&t(rn.clone().into(), vocab::SH_RESULT_MESSAGE, msg.clone()));
        }
        g.insert(&t(
            rn.into(),
            vocab::SH_SOURCE_SHAPE,
            r.source_shape.clone(),
        ));
    }
    g
}

/// Substitute `{$varName}` / `{?varName}` placeholders in `sh:message` literals.
///
/// `$this` is resolved from `focus`; all other names are looked up in
/// `bindings` (keyed without the `$`/`?` sigil). Unresolved placeholders are
/// left as-is. Only `sh:Literal` messages are processed; IRI/blank-node
/// message terms pass through unchanged.
fn substitute_messages(
    messages: &[Term],
    focus: &Term,
    bindings: &HashMap<String, Term>,
) -> Vec<Term> {
    messages
        .iter()
        .map(|msg| {
            let Term::Literal(lit) = msg else {
                return msg.clone();
            };
            let text = lit.value();
            let substituted = apply_message_template(text, focus, bindings);
            if substituted == text {
                msg.clone()
            } else {
                Term::Literal(Literal::new_simple_literal(&substituted))
            }
        })
        .collect()
}

/// A SPARQL-based custom constraint component (SHACL §6.2–6.3): a named
/// component IRI, its parameters, and the validators that apply to node shapes,
/// property shapes, or both.
struct CustomComponent {
    /// The component IRI, reported as `sh:sourceConstraintComponent`.
    iri: NamedNode,
    params: Vec<ComponentParam>,
    /// `sh:nodeValidator` — used when the component is applied to a node shape.
    node_validator: Option<ComponentValidator>,
    /// `sh:propertyValidator` — used when applied to a property shape.
    property_validator: Option<ComponentValidator>,
    /// `sh:validator` — an ASK validator usable for either shape kind.
    generic_validator: Option<ComponentValidator>,
}

struct ComponentParam {
    /// The parameter's `sh:path` predicate; the shape supplies its value here.
    path: NamedNode,
    /// The pre-bound SPARQL variable name (the local name of `path`).
    var: String,
    optional: bool,
}

struct ComponentValidator {
    kind: SparqlQueryKind,
    /// Prefix-expanded query text (`sh:ask` / `sh:select`).
    query: String,
    messages: Vec<Term>,
}

fn resolve_validator(
    shapes: &Loaded,
    node: Term,
    component_iri: &NamedNode,
    policy: UnsupportedPolicy,
) -> Option<ComponentValidator> {
    match parse_validator(shapes, &node) {
        Ok(v) => Some(v),
        Err(e) => {
            assert!(
                policy != UnsupportedPolicy::Error,
                "invalid SPARQL in custom constraint component <{component_iri}>: {e}"
            );
            None
        }
    }
}

/// Discover every SPARQL-based custom constraint component in the shapes graph:
/// a named subject carrying `sh:parameter`(s) and at least one validator. (A
/// `sh:SPARQLFunction` also has `sh:parameter` but no validator, so it is
/// excluded.)
///
/// Under [`UnsupportedPolicy::Error`], a component whose validator query is
/// invalid SPARQL causes a panic with a diagnostic message so the problem
/// surfaces immediately rather than producing a silent wrong answer.
/// Under [`UnsupportedPolicy::Ignore`], such components are silently skipped
/// (the constraint is not enforced, which is the historical default behaviour).
fn build_components(shapes: &Loaded, policy: UnsupportedPolicy) -> Vec<CustomComponent> {
    let mut out = Vec::new();
    let mut seen = HashSet::new();
    for triple in shapes.graph.triples_for_predicate(vocab::SH_PARAMETER) {
        let subject = triple.subject.into_owned();
        if !seen.insert(subject.clone()) {
            continue;
        }
        let NamedOrBlankNode::NamedNode(iri) = &subject else {
            continue; // a component must be named to be a sourceConstraintComponent
        };
        if vocab::NATIVE_CONSTRAINT_COMPONENTS.contains(&iri.as_ref()) {
            continue; // SHACL Core component; already implemented natively
        }

        let node_validator = shapes
            .object(&subject, vocab::SH_NODE_VALIDATOR)
            .and_then(|v| resolve_validator(shapes, v, iri, policy));
        let property_validator = shapes
            .object(&subject, vocab::SH_PROPERTY_VALIDATOR)
            .and_then(|v| resolve_validator(shapes, v, iri, policy));
        let generic_validator = shapes
            .object(&subject, vocab::SH_VALIDATOR)
            .and_then(|v| resolve_validator(shapes, v, iri, policy));
        if node_validator.is_none() && property_validator.is_none() && generic_validator.is_none() {
            continue; // not a constraint component (e.g. a sh:SPARQLFunction)
        }
        let mut params = Vec::new();
        for p in shapes.objects(&subject, vocab::SH_PARAMETER) {
            let Some(pn) = term_to_node(&p) else { continue };
            let Some(Term::NamedNode(path)) = shapes.object(&pn, vocab::SH_PATH) else {
                continue;
            };
            let var = local_name(path.as_str()).to_string();
            let optional = matches!(
                shapes.object(&pn, vocab::SH_OPTIONAL),
                Some(Term::Literal(ref l)) if l.value() == "true"
            );
            params.push(ComponentParam {
                path,
                var,
                optional,
            });
        }
        if params.is_empty() {
            continue;
        }
        out.push(CustomComponent {
            iri: iri.clone(),
            params,
            node_validator,
            property_validator,
            generic_validator,
        });
    }
    out.sort_by(|a, b| a.iri.as_str().cmp(b.iri.as_str()));
    out
}

/// Parse a validator node (`sh:SPARQLAskValidator` / `sh:SPARQLSelectValidator`
/// or a subclass), resolving its `sh:prefixes` into a canonical query string.
/// Returns `Err` (with the parse error message) when the query is invalid SPARQL.
fn parse_validator(shapes: &Loaded, node: &Term) -> Result<ComponentValidator, String> {
    let node = term_to_node(node)
        .ok_or_else(|| "validator node is not an IRI or blank node".to_string())?;
    let (kind, raw) = if let Some(Term::Literal(q)) = shapes.object(&node, vocab::SH_ASK) {
        (SparqlQueryKind::Ask, q.value().to_string())
    } else if let Some(Term::Literal(q)) = shapes.object(&node, vocab::SH_SELECT) {
        (SparqlQueryKind::Select, q.value().to_string())
    } else {
        return Err("validator has neither sh:ask nor sh:select".to_string());
    };
    let (_, query) = canonical_sparql_query(shapes, &node, &raw)
        .map_err(|e| format!("invalid SPARQL in {node}: {e}"))?;
    let messages = shapes.objects(&node, vocab::SH_MESSAGE);
    Ok(ComponentValidator {
        kind,
        query,
        messages,
    })
}

/// The local name of an IRI (after the last `#` or `/`) — the SHACL rule for a
/// parameter's pre-bound variable name (SHACL §6.2.1).
fn local_name(iri: &str) -> &str {
    iri.rsplit(['#', '/']).next().unwrap_or(iri)
}

/// Discover `sh:SPARQLFunction`s in the shapes graph (SHACL-AF §5) and build
/// their registrable [`FunctionDef`]s: the function IRI, its parameter variable
/// names in positional order (`sh:order`, then local name), and its prefix-
/// expanded `sh:select`/`sh:ask` body.
pub(crate) fn collect_functions(shapes: &Loaded) -> Vec<FunctionDef> {
    let mut out = Vec::new();
    for func in shapes
        .graph
        .subjects_for_predicate_object(vocab::RDF_TYPE, vocab::SH_SPARQL_FUNCTION)
        .map(|s| s.into_owned())
        .collect::<Vec<_>>()
    {
        let NamedOrBlankNode::NamedNode(iri) = &func else {
            continue;
        };
        let raw = match shapes
            .object(&func, vocab::SH_SELECT)
            .or_else(|| shapes.object(&func, vocab::SH_ASK))
        {
            Some(Term::Literal(q)) => q.value().to_string(),
            _ => continue,
        };
        let Ok((_, query)) = canonical_sparql_query(shapes, &func, &raw) else {
            continue;
        };
        out.push(FunctionDef {
            iri: iri.clone(),
            params: function_param_names(shapes, &func),
            reads_graph: crate::sparql::query_reads_graph(&query),
            query,
        });
    }
    out
}

/// Parameter variable names of a function, ordered by `sh:order` then by the
/// local name of `sh:path` (matching the node-expression evaluator).
fn function_param_names(shapes: &Loaded, func: &NamedOrBlankNode) -> Vec<String> {
    let mut params: Vec<(i64, String)> = shapes
        .objects(func, vocab::SH_PARAMETER)
        .iter()
        .filter_map(|p| {
            let pn = term_to_node(p)?;
            let order = match shapes.object(&pn, vocab::SH_ORDER) {
                Some(Term::Literal(l)) => l.value().parse::<i64>().unwrap_or(0),
                _ => 0,
            };
            let name = match shapes.object(&pn, vocab::SH_NAME) {
                Some(Term::Literal(l)) => l.value().to_string(),
                _ => match shapes.object(&pn, vocab::SH_PATH) {
                    Some(Term::NamedNode(n)) => local_name(n.as_str()).to_string(),
                    _ => return None,
                },
            };
            Some((order, name))
        })
        .collect();
    params.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
    params.into_iter().map(|(_, name)| name).collect()
}

struct Reporter<'a> {
    shapes: &'a Loaded,
    focus_data: &'a Graph,
    sparql: SparqlExecutor,
    needs_sparql: bool,
    /// `class → focus-data instances` under `rdf:type / rdfs:subClassOf*`, built
    /// once and shared by every `sh:targetClass` / implicit-class lookup.
    class_index: HashMap<Term, Vec<Term>>,
    /// Parsed `sh:path` per shape node, so `collect` does not re-parse the path
    /// RDF on every (shape, focus) visit. `None` = shape has no/invalid path.
    path_cache: RefCell<HashMap<NamedOrBlankNode, PathCacheEntry>>,
    /// SPARQL-based custom constraint components declared in the shapes graph
    /// (empty for the common case of no custom components).
    components: Vec<CustomComponent>,
    /// Optional named top-level shapes to validate. Referenced helper shapes
    /// are still traversed normally from selected entries.
    entry_shape_names: &'a [String],
}

type Visited = HashSet<(NamedOrBlankNode, Term)>;

/// Cached parsed path and its term representation for sh:path expressions
type PathCacheEntry = (Option<Term>, Option<Path>);

impl Reporter<'_> {
    fn frozen(&self) -> &FrozenIndexedDataset {
        self.sparql
            .frozen()
            .expect("report validation always has a frozen dataset")
    }

    fn target_shapes(&self) -> Vec<NamedOrBlankNode> {
        let mut found: HashSet<NamedOrBlankNode> = HashSet::new();
        for t in self.shapes.graph.iter() {
            let p = t.predicate;
            if p == vocab::SH_TARGET_NODE
                || p == vocab::SH_TARGET_CLASS
                || p == vocab::SH_TARGET_SUBJECTS_OF
                || p == vocab::SH_TARGET_OBJECTS_OF
            {
                found.insert(t.subject.into_owned());
            }
            // SPARQL-based target: sh:target [ sh:select "…" ]
            if p == vocab::SH_TARGET
                && let Some(target) = term_to_node(&t.object.into_owned())
                && self.shapes.object(&target, vocab::SH_SELECT).is_some()
            {
                found.insert(t.subject.into_owned());
            }
            // implicit class target: a shape that is also an rdfs:Class / owl:Class
            if p == vocab::RDF_TYPE {
                let s = t.subject.into_owned();
                if self.is_class(&s) && self.is_shape(&s) {
                    found.insert(s);
                }
            }
        }
        let mut v: Vec<_> = found.into_iter().collect();
        v.retain(|shape| self.entry_shape_selected(shape));
        v.sort_by_key(|n| n.to_string());
        v
    }

    fn entry_shape_selected(&self, shape: &NamedOrBlankNode) -> bool {
        let actual = match shape {
            NamedOrBlankNode::NamedNode(named) => Some(named.as_str()),
            NamedOrBlankNode::BlankNode(_) => None,
        };
        entry_shape_name_selected(self.entry_shape_names, actual)
    }

    /// Does this node look like a SHACL shape (so its class-ness implies a target)?
    fn is_shape(&self, n: &NamedOrBlankNode) -> bool {
        is_shape_node(self.shapes, n)
    }

    fn is_class(&self, n: &NamedOrBlankNode) -> bool {
        self.shapes.is_instance_of(n, vocab::RDFS_CLASS)
            || self.shapes.is_instance_of(n, vocab::OWL_CLASS)
    }

    fn deactivated(&self, n: &NamedOrBlankNode) -> bool {
        matches!(self.shapes.object(n, vocab::SH_DEACTIVATED),
            Some(Term::Literal(ref l)) if l.value() == "true")
    }

    fn focus_nodes(&self, shape: &NamedOrBlankNode) -> Vec<Term> {
        let mut nodes = Vec::new();
        nodes.extend(self.shapes.objects(shape, vocab::SH_TARGET_NODE));
        for c in self.shapes.objects(shape, vocab::SH_TARGET_CLASS) {
            if let Some(instances) = self.class_index.get(&c) {
                nodes.extend(instances.iter().cloned());
            }
        }
        for p in self.shapes.objects(shape, vocab::SH_TARGET_SUBJECTS_OF) {
            if let Term::NamedNode(n) = p {
                nodes.extend(
                    self.focus_data
                        .triples_for_predicate(n.as_ref())
                        .map(|t| node_term(t.subject)),
                );
            }
        }
        for p in self.shapes.objects(shape, vocab::SH_TARGET_OBJECTS_OF) {
            if let Term::NamedNode(n) = p {
                nodes.extend(
                    self.focus_data
                        .triples_for_predicate(n.as_ref())
                        .map(|t| t.object.into_owned()),
                );
            }
        }
        // SPARQL-based targets: sh:target [ sh:select "…" ]. The query selects
        // `?this` focus nodes from the context store.
        if self.needs_sparql {
            let exec = &self.sparql;
            for target in self.shapes.objects(shape, vocab::SH_TARGET) {
                let Some(target_node) = term_to_node(&target) else {
                    continue;
                };
                let Some(Term::Literal(query)) = self.shapes.object(&target_node, vocab::SH_SELECT)
                else {
                    continue;
                };
                // Drop targets that fail to canonicalize, matching the lowering path.
                let Ok((_, canonical)) =
                    canonical_sparql_query(self.shapes, &target_node, query.value())
                else {
                    continue;
                };
                if let Ok(found) = exec.target_nodes(&canonical) {
                    nodes.extend(found);
                }
            }
        }
        // implicit class target: instances of the shape (which is also a class)
        if let NamedOrBlankNode::NamedNode(n) = shape
            && self.is_class(shape)
        {
            let class = Term::NamedNode(n.clone());
            if let Some(instances) = self.class_index.get(&class) {
                nodes.extend(instances.iter().cloned());
            }
        }
        let mut seen = HashSet::new();
        nodes.retain(|t| seen.insert(t.clone()));
        nodes
    }

    /// The shape's `sh:path` as both its raw RDF node (for `sh:resultPath`) and
    /// the parsed path algebra, memoized so repeated visits don't re-parse it.
    fn shape_path(&self, shape: &NamedOrBlankNode) -> (Option<Term>, Option<Path>) {
        if let Some(cached) = self.path_cache.borrow().get(shape) {
            return cached.clone();
        }
        let path_term = self.shapes.object(shape, vocab::SH_PATH);
        let parsed = path_term
            .as_ref()
            .and_then(|t| parse_path(self.shapes, t).ok());
        let entry = (path_term, parsed);
        self.path_cache
            .borrow_mut()
            .insert(shape.clone(), entry.clone());
        entry
    }

    /// `shape`'s own `sh:message`, falling back to `inherited` — the nearest
    /// enclosing shape's `sh:message` — when `shape` declares none. Mirrors the
    /// algebra path's "nearest-enclosing shape" resolution (see `explain` in
    /// `lib.rs`) so a message authored on an outer node shape still surfaces on
    /// violations from an unlabeled nested property shape.
    fn messages_or_inherited(&self, shape: &NamedOrBlankNode, inherited: &[Term]) -> Vec<Term> {
        let own = self.messages(shape);
        if own.is_empty() {
            inherited.to_vec()
        } else {
            own
        }
    }

    /// Collect the results of validating `focus` against `shape`.
    ///
    /// `inherited` is the nearest enclosing shape's `sh:message` (empty at the
    /// top-level target shapes), used when `shape` itself has none.
    fn collect(
        &self,
        shape: &NamedOrBlankNode,
        focus: &Term,
        out: &mut Vec<ValidationResult>,
        visited: &mut Visited,
        inherited: &[Term],
    ) {
        if self.deactivated(shape) {
            return; // deactivated shapes produce no results
        }
        let key = (shape.clone(), focus.clone());
        if !visited.insert(key.clone()) {
            return; // recursion: conform on the back-edge (gfp)
        }

        let (path_term, parsed) = self.shape_path(shape);
        let value_nodes: Vec<Term> = match &parsed {
            Some(p) => succ(self.frozen(), focus, p).into_iter().collect(),
            None => vec![focus.clone()],
        };
        let severity = self.severity(shape);
        let messages = self.messages_or_inherited(shape, inherited);
        let push = |out: &mut Vec<ValidationResult>, value, component| {
            out.push(ValidationResult {
                focus: focus.clone(),
                path: path_term.clone(),
                value,
                component,
                source_shape: node_term_ref(shape),
                severity: severity.clone(),
                messages: messages.clone(),
            });
        };

        // cardinality (only meaningful with a path)
        if parsed.is_some() {
            if let Some(min) = self.int(shape, vocab::SH_MIN_COUNT)
                && (value_nodes.len() as u64) < min
            {
                push(out, None, vocab::SH_CC_MIN_COUNT.into_owned());
            }
            if let Some(max) = self.int(shape, vocab::SH_MAX_COUNT)
                && (value_nodes.len() as u64) > max
            {
                push(out, None, vocab::SH_CC_MAX_COUNT.into_owned());
            }
        }

        // sh:hasValue — one of the value nodes must equal the constant
        for hv in self.shapes.objects(shape, vocab::SH_HAS_VALUE) {
            if !value_nodes.contains(&hv) {
                push(out, None, vocab::SH_CC_HAS_VALUE.into_owned());
            }
        }

        self.collect_closed(shape, focus, &value_nodes, out, &messages);
        self.collect_property_pairs(shape, focus, &path_term, &value_nodes, out, &messages);
        self.collect_unique_lang(shape, focus, &path_term, &value_nodes, out, &messages);
        self.collect_qualified_counts(
            shape,
            focus,
            &path_term,
            &value_nodes,
            out,
            visited,
            &messages,
        );

        // value-scoped components
        for u in &value_nodes {
            for (component, ok) in self.value_checks(shape, u, visited) {
                if !ok {
                    push(out, Some(u.clone()), component);
                }
            }
        }

        // nested property shapes: delegate (each value node is a focus for P),
        // passing this shape's resolved message down as the inherited fallback.
        for prop in self.shapes.objects(shape, vocab::SH_PROPERTY) {
            if let Some(pn) = term_to_node(&prop) {
                for u in &value_nodes {
                    self.collect(&pn, u, out, visited, &messages);
                }
            }
        }

        self.collect_sparql(shape, focus, &path_term, &parsed, out, &messages);
        self.collect_expression(shape, focus, out, visited, &messages);
        self.collect_components(
            shape,
            focus,
            &path_term,
            &parsed,
            &value_nodes,
            out,
            &messages,
        );

        visited.remove(&key);
    }

    /// Walk from a (conforming) target shape down through `sh:property`,
    /// `sh:and`, and `sh:node` — the shape forms that keep `focus` as the
    /// same node — collecting one [`PropertyWitness`] per `sh:property` shape
    /// reached. `sh:or`/`sh:xone`/`sh:not` are not descended: which branch
    /// applies is not a fixed set of roles, so there is no single binding to
    /// report.
    fn collect_property_witnesses(
        &self,
        shape: &NamedOrBlankNode,
        focus: &Term,
        profile: &NamedOrBlankNode,
        key_path: Option<&Path>,
        visited: &mut Visited,
        out: &mut Vec<PropertyWitness>,
    ) {
        if self.deactivated(shape) {
            return;
        }
        let key = (shape.clone(), focus.clone());
        if !visited.insert(key.clone()) {
            return;
        }

        for prop in self.shapes.objects(shape, vocab::SH_PROPERTY) {
            if let Some(pn) = term_to_node(&prop) {
                self.collect_property_binding(&pn, focus, profile, key_path, visited, out);
            }
        }
        for list in self.shapes.objects(shape, vocab::SH_AND) {
            for member in self.shapes.read_list(&list) {
                if let Some(mn) = term_to_node(&member) {
                    self.collect_property_witnesses(&mn, focus, profile, key_path, visited, out);
                }
            }
        }
        for n in self.shapes.objects(shape, vocab::SH_NODE) {
            if let Some(nn) = term_to_node(&n) {
                self.collect_property_witnesses(&nn, focus, profile, key_path, visited, out);
            }
        }

        visited.remove(&key);
    }

    /// The single [`PropertyWitness`] for one `sh:property` shape at `focus`:
    /// its `sh:path` value nodes, narrowed to the `sh:qualifiedValueShape`
    /// matches when the property shape declares one (mirroring the *counted*
    /// set in [`Reporter::collect_qualified_counts`], but keeping the values
    /// themselves rather than just their count). Property shapes without a
    /// `sh:path` are not addressable and are skipped.
    fn collect_property_binding(
        &self,
        pn: &NamedOrBlankNode,
        focus: &Term,
        profile: &NamedOrBlankNode,
        key_path: Option<&Path>,
        visited: &mut Visited,
        out: &mut Vec<PropertyWitness>,
    ) {
        if self.deactivated(pn) {
            return;
        }
        let (_, parsed_path) = self.shape_path(pn);
        let Some(path) = parsed_path else { return };

        // `key_path` is evaluated over the *shapes* graph, from the property
        // shape's own node — a different graph and starting point than the
        // `sh:path` evaluation below (which reads the data, from `focus`).
        // When it resolves to several values, the first in string order is
        // used, for a deterministic result independent of set iteration order.
        let key = key_path
            .and_then(|kp| {
                let mut matches: Vec<Term> = succ(&self.shapes.graph, &node_term_ref(pn), kp)
                    .into_iter()
                    .collect();
                matches.sort_by_key(ToString::to_string);
                matches.into_iter().next()
            })
            .unwrap_or_else(|| node_term_ref(pn));

        let value_nodes: Vec<Term> = succ(self.frozen(), focus, &path).into_iter().collect();
        let values = match self.shapes.object(pn, vocab::SH_QUALIFIED_VALUE_SHAPE) {
            Some(qualifier_term) => {
                let Some(qualifier) = term_to_node(&qualifier_term) else {
                    return;
                };
                let siblings = if self.bool(pn, vocab::SH_QUALIFIED_VALUE_SHAPES_DISJOINT) {
                    self.sibling_qualified_shapes(pn, &qualifier)
                } else {
                    Vec::new()
                };
                value_nodes
                    .into_iter()
                    .filter(|v| {
                        self.conforms(&qualifier, v, visited)
                            && siblings
                                .iter()
                                .all(|sibling| !self.conforms(sibling, v, visited))
                    })
                    .collect()
            }
            None => value_nodes,
        };

        out.push(PropertyWitness {
            focus: focus.clone(),
            shape: node_term_ref(profile),
            key,
            values,
        });
    }

    /// SPARQL-based custom constraint components (SHACL §6.3). A component is
    /// *activated* for `shape` iff the shape supplies a value for each of its
    /// mandatory parameters; those values (plus `$this`, `$value`, `$PATH`,
    /// `$currentShape`) are pre-bound into the validator query. ASK validators
    /// run per value node (violation iff they return `false`); SELECT validators
    /// run once per focus (each solution row is a violation).
    #[allow(clippy::too_many_arguments)]
    fn collect_components(
        &self,
        shape: &NamedOrBlankNode,
        focus: &Term,
        path_term: &Option<Term>,
        parsed_path: &Option<Path>,
        value_nodes: &[Term],
        out: &mut Vec<ValidationResult>,
        inherited: &[Term],
    ) {
        if self.components.is_empty() {
            return;
        }
        let is_property_shape = parsed_path.is_some();
        for component in &self.components {
            // Activation: every mandatory parameter must have a value on `shape`.
            let mut params: Vec<(String, Term)> = Vec::new();
            let mut activated = true;
            for p in &component.params {
                if let Some(value) = self.shapes.object(shape, p.path.as_ref()) {
                    params.push((p.var.clone(), value));
                } else if !p.optional {
                    activated = false;
                    break;
                }
            }
            if !activated {
                continue;
            }

            let validator = if is_property_shape {
                component
                    .property_validator
                    .as_ref()
                    .or(component.generic_validator.as_ref())
            } else {
                component
                    .node_validator
                    .as_ref()
                    .or(component.generic_validator.as_ref())
            };
            let Some(validator) = validator else { continue };

            // Bindings shared across value nodes: parameters and $currentShape.
            // For property shapes, `$PATH` is pre-bound to the shape's path
            // (simple predicate or complex property path) inside the executor.
            let mut base = params;
            base.push(("currentShape".to_string(), node_term_ref(shape)));
            let path = parsed_path.as_ref();

            match validator.kind {
                SparqlQueryKind::Ask => {
                    for value in value_nodes {
                        let mut bindings = base.clone();
                        bindings.push(("this".to_string(), focus.clone()));
                        bindings.push(("value".to_string(), value.clone()));
                        // Conform iff ASK is true; a runtime error fails closed.
                        let violates = match self.sparql.eval_ask(&validator.query, path, &bindings)
                        {
                            Ok(conforms) => !conforms,
                            Err(_) => true,
                        };
                        if violates {
                            self.push_component_result(
                                out,
                                component,
                                shape,
                                focus,
                                path_term.clone(),
                                Some(value.clone()),
                                &bindings,
                                &validator.messages,
                                inherited,
                            );
                        }
                    }
                }
                SparqlQueryKind::Select => {
                    let mut bindings = base.clone();
                    bindings.push(("this".to_string(), focus.clone()));
                    match self.sparql.eval_select(&validator.query, path, &bindings) {
                        Ok(rows) => {
                            for row in rows {
                                // ?value projected; for node validators it is the
                                // focus node itself when not projected.
                                let value = row
                                    .get("value")
                                    .cloned()
                                    .or_else(|| (!is_property_shape).then(|| focus.clone()));
                                let path = row.get("path").cloned().or_else(|| path_term.clone());
                                let mut binds = bindings.clone();
                                binds.extend(row);
                                self.push_component_result(
                                    out,
                                    component,
                                    shape,
                                    focus,
                                    path,
                                    value,
                                    &binds,
                                    &validator.messages,
                                    inherited,
                                );
                            }
                        }
                        Err(_) => self.push_component_result(
                            out,
                            component,
                            shape,
                            focus,
                            path_term.clone(),
                            None,
                            &bindings,
                            &validator.messages,
                            inherited,
                        ),
                    }
                }
            }
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn push_component_result(
        &self,
        out: &mut Vec<ValidationResult>,
        component: &CustomComponent,
        shape: &NamedOrBlankNode,
        focus: &Term,
        path: Option<Term>,
        value: Option<Term>,
        bindings: &[(String, Term)],
        validator_messages: &[Term],
        inherited: &[Term],
    ) {
        let raw = if validator_messages.is_empty() {
            self.messages_or_inherited(shape, inherited)
        } else {
            validator_messages.to_vec()
        };
        let bind_map: HashMap<String, Term> = bindings.iter().cloned().collect();
        let messages = substitute_messages(&raw, focus, &bind_map);
        out.push(ValidationResult {
            focus: focus.clone(),
            path,
            value,
            component: component.iri.clone(),
            source_shape: node_term_ref(shape),
            severity: self.severity(shape),
            messages,
        });
    }

    /// `sh:expression` constraints (SHACL-AF §5). The node expression is
    /// evaluated with the focus node as `?this`; every produced value that is
    /// not the boolean `true` yields one `sh:ExpressionConstraintComponent`
    /// result whose `sh:value` is that value. Expression forms the report path
    /// cannot evaluate (function applications) are skipped, matching the
    /// lowering path which diagnoses them rather than under-constraining.
    fn collect_expression(
        &self,
        shape: &NamedOrBlankNode,
        focus: &Term,
        out: &mut Vec<ValidationResult>,
        visited: &mut Visited,
        inherited: &[Term],
    ) {
        for expr_term in self.shapes.objects(shape, vocab::SH_EXPRESSION) {
            let Some(results) = self.eval_node_expr(&expr_term, focus, visited) else {
                continue;
            };
            for value in results {
                if is_boolean_true(&value) {
                    continue;
                }
                out.push(ValidationResult {
                    focus: focus.clone(),
                    path: None,
                    value: Some(value),
                    component: vocab::SH_CC_EXPRESSION.into_owned(),
                    source_shape: node_term_ref(shape),
                    severity: self.severity(shape),
                    messages: self.messages_or_inherited(shape, inherited),
                });
            }
        }
    }

    /// Evaluate a SHACL-AF node expression term (read straight from the shapes
    /// graph) with `focus` as `?this`. `None` means the expression uses a form
    /// the report path cannot evaluate (e.g. a function application), so the
    /// caller skips the owning constraint.
    fn eval_node_expr(
        &self,
        term: &Term,
        focus: &Term,
        visited: &mut Visited,
    ) -> Option<Vec<Term>> {
        match term {
            Term::NamedNode(n) if n.as_ref() == vocab::SH_THIS => Some(vec![focus.clone()]),
            Term::NamedNode(_) | Term::Literal(_) => Some(vec![term.clone()]),
            Term::BlankNode(_) => {
                let node = term_to_node(term)?;
                if let Some(path_term) = self.shapes.object(&node, vocab::SH_PATH) {
                    let path = parse_path(self.shapes, &path_term).ok()?;
                    Some(succ(self.frozen(), focus, &path).into_iter().collect())
                } else if let Some(filter_shape) = self.shapes.object(&node, vocab::SH_FILTER_SHAPE)
                {
                    let filter_shape = term_to_node(&filter_shape)?;
                    let nodes_term = self.shapes.object(&node, vocab::SH_NODES)?;
                    let inputs = self.eval_node_expr(&nodes_term, focus, visited)?;
                    Some(
                        inputs
                            .into_iter()
                            .filter(|x| self.conforms(&filter_shape, x, visited))
                            .collect(),
                    )
                } else if let Some(list) = self.shapes.object(&node, vocab::SH_INTERSECTION) {
                    self.eval_node_expr_set(&list, focus, visited, true)
                } else if let Some(list) = self.shapes.object(&node, vocab::SH_UNION) {
                    self.eval_node_expr_set(&list, focus, visited, false)
                } else {
                    // Function application or unrecognized form: unsupported here.
                    None
                }
            }
        }
    }

    /// Evaluate the members of an `sh:intersection` / `sh:union` list and combine
    /// them (`intersect = true` for intersection, set union otherwise),
    /// preserving each member's order while deduplicating.
    fn eval_node_expr_set(
        &self,
        list_head: &Term,
        focus: &Term,
        visited: &mut Visited,
        intersect: bool,
    ) -> Option<Vec<Term>> {
        let members = self.shapes.read_list(list_head);
        if members.is_empty() {
            return None;
        }
        let mut iter = members.iter();
        let mut acc = self.eval_node_expr(iter.next().unwrap(), focus, visited)?;
        for member in iter {
            let next = self.eval_node_expr(member, focus, visited)?;
            if intersect {
                acc.retain(|x| next.contains(x));
            } else {
                for t in next {
                    if !acc.contains(&t) {
                        acc.push(t);
                    }
                }
            }
        }
        Some(acc)
    }

    /// `sh:sparql` constraints (SHACL-SPARQL). Each `SELECT`/`ASK` query runs for
    /// the focus node against the context store; every solution (or a `true`
    /// `ASK`) is one `sh:SPARQLConstraintComponent` result. A `value`/`path`
    /// projected by the query overrides the value node / `sh:resultPath`.
    /// Build the [`SparqlConstraint`] for a `sh:sparql` constraint node, applying
    /// the same canonicalization the lowering path uses. `None` when the node has
    /// neither `sh:select` nor `sh:ask`, or when canonicalization fails (matching
    /// the lowering path, which omits such constraints with a diagnostic).
    fn build_sparql_constraint(
        &self,
        shape: &NamedOrBlankNode,
        constraint_node: &NamedOrBlankNode,
        parsed_path: &Option<Path>,
    ) -> Option<SparqlConstraint> {
        let (kind, raw) = if let Some(Term::Literal(query)) =
            self.shapes.object(constraint_node, vocab::SH_SELECT)
        {
            (SparqlQueryKind::Select, query.value().to_string())
        } else if let Some(Term::Literal(query)) =
            self.shapes.object(constraint_node, vocab::SH_ASK)
        {
            (SparqlQueryKind::Ask, query.value().to_string())
        } else {
            return None;
        };
        let (_, query) = canonical_sparql_query(self.shapes, constraint_node, &raw).ok()?;
        Some(SparqlConstraint {
            kind,
            query,
            path: parsed_path.clone(),
            shape: Some(node_term_ref(shape)),
            // The report path resolves messages itself, so the constraint's own
            // message slot is left empty here.
            messages: Vec::new(),
            extra_bindings: Vec::new(),
            bind_value_to_this: false,
        })
    }

    /// Batch-evaluate a shape's direct `sh:sparql` constraints over its whole
    /// focus set before the per-focus walk, so fallback queries run once over a
    /// `VALUES` table (doc §189) rather than once per focus.
    fn prefetch_sparql(&self, shape: &NamedOrBlankNode, foci: &[Term]) {
        if !self.needs_sparql || foci.len() < 2 {
            return;
        }
        let (_, parsed_path) = self.shape_path(shape);
        for constraint_term in self.shapes.objects(shape, vocab::SH_SPARQL) {
            let Some(constraint_node) = term_to_node(&constraint_term) else {
                continue;
            };
            if let Some(constraint) =
                self.build_sparql_constraint(shape, &constraint_node, &parsed_path)
            {
                let _ = self.sparql.prefetch_constraint(&constraint, foci);
            }
        }
    }

    fn collect_sparql(
        &self,
        shape: &NamedOrBlankNode,
        focus: &Term,
        path_term: &Option<Term>,
        parsed_path: &Option<Path>,
        out: &mut Vec<ValidationResult>,
        inherited: &[Term],
    ) {
        if !self.needs_sparql {
            return;
        }
        let sparql = &self.sparql;
        let severity = self.severity(shape);
        for constraint_term in self.shapes.objects(shape, vocab::SH_SPARQL) {
            let Some(constraint_node) = term_to_node(&constraint_term) else {
                continue;
            };
            let Some(constraint) =
                self.build_sparql_constraint(shape, &constraint_node, parsed_path)
            else {
                continue;
            };
            // Mirror lower.rs §179-184: constraint-node sh:message takes
            // precedence; absent that, fall back to the owning shape's
            // sh:message, then to the nearest enclosing shape's.
            let raw_messages = {
                let on_constraint = self.shapes.objects(&constraint_node, vocab::SH_MESSAGE);
                if on_constraint.is_empty() {
                    self.messages_or_inherited(shape, inherited)
                } else {
                    on_constraint
                }
            };
            match sparql.constraint_violations(&constraint, focus) {
                Ok(violations) => {
                    for violation in violations {
                        let messages =
                            substitute_messages(&raw_messages, focus, &violation.bindings);
                        // SHACL-AF §8.4.1: for SELECT constraints, when ?value is
                        // not projected, the focus node itself is used as sh:value.
                        let value = violation.value.or_else(|| match constraint.kind {
                            SparqlQueryKind::Select => Some(focus.clone()),
                            SparqlQueryKind::Ask => None,
                        });
                        out.push(ValidationResult {
                            focus: focus.clone(),
                            path: violation.path.or_else(|| path_term.clone()),
                            value,
                            component: vocab::SH_CC_SPARQL.into_owned(),
                            source_shape: node_term_ref(shape),
                            severity: severity.clone(),
                            messages,
                        });
                    }
                }
                // Runtime failure (e.g. an unsupported graph-reading function
                // under UnsupportedPolicy::Error, or complex-path prebinding):
                // fail closed, surfacing the error so it is not a silent miss.
                Err(error) => {
                    let mut messages = raw_messages;
                    messages.push(Term::Literal(Literal::new_simple_literal(format!(
                        "SPARQL constraint evaluation failed: {error}"
                    ))));
                    out.push(ValidationResult {
                        focus: focus.clone(),
                        path: path_term.clone(),
                        value: None,
                        component: vocab::SH_CC_SPARQL.into_owned(),
                        source_shape: node_term_ref(shape),
                        severity: severity.clone(),
                        messages,
                    });
                }
            }
        }
    }

    fn collect_closed(
        &self,
        shape: &NamedOrBlankNode,
        focus: &Term,
        value_nodes: &[Term],
        out: &mut Vec<ValidationResult>,
        inherited: &[Term],
    ) {
        if !self.bool(shape, vocab::SH_CLOSED) {
            return;
        }
        let mut allowed = HashSet::new();
        for prop in self.shapes.objects(shape, vocab::SH_PROPERTY) {
            let Some(prop) = term_to_node(&prop) else {
                continue;
            };
            if let Some(Term::NamedNode(path)) = self.shapes.object(&prop, vocab::SH_PATH) {
                allowed.insert(path);
            }
        }
        for list in self.shapes.objects(shape, vocab::SH_IGNORED_PROPERTIES) {
            for term in self.shapes.read_list(&list) {
                if let Term::NamedNode(predicate) = term {
                    allowed.insert(predicate);
                }
            }
        }
        for value_node in value_nodes {
            for (predicate, object) in self.frozen().outgoing(value_node) {
                if allowed.contains(&predicate) {
                    continue;
                }
                out.push(ValidationResult {
                    focus: focus.clone(),
                    path: Some(Term::NamedNode(predicate)),
                    value: Some(object),
                    component: vocab::SH_CC_CLOSED.into_owned(),
                    source_shape: node_term_ref(shape),
                    severity: self.severity(shape),
                    messages: self.messages_or_inherited(shape, inherited),
                });
            }
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn collect_property_pairs(
        &self,
        shape: &NamedOrBlankNode,
        focus: &Term,
        path: &Option<Term>,
        value_nodes: &[Term],
        out: &mut Vec<ValidationResult>,
        inherited: &[Term],
    ) {
        for predicate in self.shapes.objects(shape, vocab::SH_EQUALS) {
            let Term::NamedNode(predicate) = predicate else {
                continue;
            };
            let other = succ(self.frozen(), focus, &Path::Pred(predicate));
            for value in value_nodes.iter().filter(|value| !other.contains(*value)) {
                self.push(
                    out,
                    shape,
                    focus,
                    path.clone(),
                    Some((*value).clone()),
                    vocab::SH_CC_EQUALS,
                    inherited,
                );
            }
            for value in other.iter().filter(|value| !value_nodes.contains(*value)) {
                self.push(
                    out,
                    shape,
                    focus,
                    path.clone(),
                    Some(value.clone()),
                    vocab::SH_CC_EQUALS,
                    inherited,
                );
            }
        }
        for predicate in self.shapes.objects(shape, vocab::SH_DISJOINT) {
            let Term::NamedNode(predicate) = predicate else {
                continue;
            };
            let other = succ(self.frozen(), focus, &Path::Pred(predicate));
            for value in value_nodes.iter().filter(|value| other.contains(*value)) {
                self.push(
                    out,
                    shape,
                    focus,
                    path.clone(),
                    Some((*value).clone()),
                    vocab::SH_CC_DISJOINT,
                    inherited,
                );
            }
        }
        for (constraint, component, inclusive) in [
            (vocab::SH_LESS_THAN, vocab::SH_CC_LESS_THAN, false),
            (
                vocab::SH_LESS_THAN_OR_EQUALS,
                vocab::SH_CC_LESS_THAN_OR_EQUALS,
                true,
            ),
        ] {
            for predicate in self.shapes.objects(shape, constraint) {
                let Term::NamedNode(predicate) = predicate else {
                    continue;
                };
                for left in value_nodes {
                    for right in succ(self.frozen(), focus, &Path::Pred(predicate.clone())) {
                        let ordering = compare_terms(left, &right);
                        let passes = ordering == Some(Ordering::Less)
                            || inclusive && ordering == Some(Ordering::Equal);
                        if !passes {
                            self.push(
                                out,
                                shape,
                                focus,
                                path.clone(),
                                Some(left.clone()),
                                component,
                                inherited,
                            );
                        }
                    }
                }
            }
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn collect_unique_lang(
        &self,
        shape: &NamedOrBlankNode,
        focus: &Term,
        path: &Option<Term>,
        value_nodes: &[Term],
        out: &mut Vec<ValidationResult>,
        inherited: &[Term],
    ) {
        if !self.bool(shape, vocab::SH_UNIQUE_LANG) {
            return;
        }
        let mut counts = HashMap::new();
        for value in value_nodes {
            if let Term::Literal(literal) = value
                && let Some(language) = literal.language()
            {
                *counts
                    .entry(language.to_ascii_lowercase())
                    .or_insert(0usize) += 1;
            }
        }
        for _ in counts.values().filter(|count| **count > 1) {
            self.push(
                out,
                shape,
                focus,
                path.clone(),
                None,
                vocab::SH_CC_UNIQUE_LANG,
                inherited,
            );
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn collect_qualified_counts(
        &self,
        shape: &NamedOrBlankNode,
        focus: &Term,
        path: &Option<Term>,
        value_nodes: &[Term],
        out: &mut Vec<ValidationResult>,
        visited: &mut Visited,
        inherited: &[Term],
    ) {
        for qualifier in self.shapes.objects(shape, vocab::SH_QUALIFIED_VALUE_SHAPE) {
            let Some(qualifier) = term_to_node(&qualifier) else {
                continue;
            };
            let siblings = if self.bool(shape, vocab::SH_QUALIFIED_VALUE_SHAPES_DISJOINT) {
                self.sibling_qualified_shapes(shape, &qualifier)
            } else {
                Vec::new()
            };
            let count = value_nodes
                .iter()
                .filter(|value| {
                    self.conforms(&qualifier, value, visited)
                        && siblings
                            .iter()
                            .all(|sibling| !self.conforms(sibling, value, visited))
                })
                .count() as u64;
            if let Some(min) = self.int(shape, vocab::SH_QUALIFIED_MIN_COUNT)
                && count < min
            {
                self.push(
                    out,
                    shape,
                    focus,
                    path.clone(),
                    None,
                    vocab::SH_CC_QUALIFIED_MIN_COUNT,
                    inherited,
                );
            }
            if let Some(max) = self.int(shape, vocab::SH_QUALIFIED_MAX_COUNT)
                && count > max
            {
                self.push(
                    out,
                    shape,
                    focus,
                    path.clone(),
                    None,
                    vocab::SH_CC_QUALIFIED_MAX_COUNT,
                    inherited,
                );
            }
        }
    }

    fn sibling_qualified_shapes(
        &self,
        shape: &NamedOrBlankNode,
        qualifier: &NamedOrBlankNode,
    ) -> Vec<NamedOrBlankNode> {
        let shape_term = node_term_ref(shape);
        let mut siblings = HashSet::new();
        for triple in self.shapes.graph.triples_for_predicate(vocab::SH_PROPERTY) {
            if triple.object != shape_term.as_ref() {
                continue;
            }
            let parent = triple.subject.into_owned();
            for property in self.shapes.objects(&parent, vocab::SH_PROPERTY) {
                let Some(property) = term_to_node(&property) else {
                    continue;
                };
                for qualifier in self
                    .shapes
                    .objects(&property, vocab::SH_QUALIFIED_VALUE_SHAPE)
                {
                    if let Some(qualifier) = term_to_node(&qualifier) {
                        siblings.insert(qualifier);
                    }
                }
            }
        }
        siblings.remove(qualifier);
        siblings.into_iter().collect()
    }

    #[allow(clippy::too_many_arguments)]
    fn push(
        &self,
        out: &mut Vec<ValidationResult>,
        shape: &NamedOrBlankNode,
        focus: &Term,
        path: Option<Term>,
        value: Option<Term>,
        component: NamedNodeRef<'static>,
        inherited: &[Term],
    ) {
        let mut bindings = HashMap::new();
        if let Some(v) = &value {
            bindings.insert("value".to_string(), v.clone());
        }
        if let Some(p) = &path {
            bindings.insert("path".to_string(), p.clone());
        }
        let raw = self.messages_or_inherited(shape, inherited);
        let messages = substitute_messages(&raw, focus, &bindings);
        out.push(ValidationResult {
            focus: focus.clone(),
            path,
            value,
            component: component.into_owned(),
            source_shape: node_term_ref(shape),
            severity: self.severity(shape),
            messages,
        });
    }

    /// Read `sh:message` values from `shape` to propagate as `sh:resultMessage`.
    fn messages(&self, shape: &NamedOrBlankNode) -> Vec<Term> {
        self.shapes.objects(shape, vocab::SH_MESSAGE)
    }

    /// A concise fallback `sh:resultMessage` for a result that carries no
    /// authored `sh:message`, synthesized from the constraint component, the
    /// parameter value read back off the source shape, and the result's
    /// value/path. Clauses referencing the value or path are omitted when the
    /// result has none (e.g. `sh:minCount`, which has no single value node).
    fn default_message(&self, result: &ValidationResult) -> String {
        let comp = result.component.as_ref();
        let value = result.value.as_ref().map(render_term);
        let path = result.path.as_ref().map(render_term);
        let Some(shape) = term_to_node(&result.source_shape) else {
            return format!(
                "Value does not conform to constraint component <{}>",
                comp.as_str()
            );
        };
        // Read a shape parameter (as a rendered term or an integer) to inline.
        let param = |p: NamedNodeRef| self.shapes.object(&shape, p).as_ref().map(render_term);
        let int_param = |p: NamedNodeRef| self.int(&shape, p).map(|n| n.to_string());
        let some_or = |o: Option<String>, default: &str| o.unwrap_or_else(|| default.to_string());
        let val = || value.clone().unwrap_or_else(|| "the value".to_string());
        let on_path = || {
            path.as_ref()
                .map(|p| format!(" on path {p}"))
                .unwrap_or_default()
        };

        if comp == vocab::SH_CC_MIN_COUNT {
            format!(
                "Fewer than {} values{}",
                some_or(int_param(vocab::SH_MIN_COUNT), "the required number of"),
                on_path()
            )
        } else if comp == vocab::SH_CC_MAX_COUNT {
            format!(
                "More than {} values{}",
                some_or(int_param(vocab::SH_MAX_COUNT), "the allowed number of"),
                on_path()
            )
        } else if comp == vocab::SH_CC_CLASS {
            format!(
                "Value {} is not an instance of class {}",
                val(),
                some_or(param(vocab::SH_CLASS), "the required class")
            )
        } else if comp == vocab::SH_CC_DATATYPE {
            format!(
                "Value {} does not have datatype {}",
                val(),
                some_or(param(vocab::SH_DATATYPE), "the required datatype")
            )
        } else if comp == vocab::SH_CC_NODE_KIND {
            format!(
                "Value {} does not have node kind {}",
                val(),
                some_or(param(vocab::SH_NODE_KIND), "the required node kind")
            )
        } else if comp == vocab::SH_CC_MIN_INCLUSIVE {
            format!(
                "Value {} is less than minimum {}",
                val(),
                some_or(param(vocab::SH_MIN_INCLUSIVE), "the minimum")
            )
        } else if comp == vocab::SH_CC_MIN_EXCLUSIVE {
            format!(
                "Value {} is not greater than exclusive minimum {}",
                val(),
                some_or(param(vocab::SH_MIN_EXCLUSIVE), "the minimum")
            )
        } else if comp == vocab::SH_CC_MAX_INCLUSIVE {
            format!(
                "Value {} is greater than maximum {}",
                val(),
                some_or(param(vocab::SH_MAX_INCLUSIVE), "the maximum")
            )
        } else if comp == vocab::SH_CC_MAX_EXCLUSIVE {
            format!(
                "Value {} is not less than exclusive maximum {}",
                val(),
                some_or(param(vocab::SH_MAX_EXCLUSIVE), "the maximum")
            )
        } else if comp == vocab::SH_CC_MIN_LENGTH {
            format!(
                "Value {} is shorter than {} characters",
                val(),
                some_or(int_param(vocab::SH_MIN_LENGTH), "the minimum number of")
            )
        } else if comp == vocab::SH_CC_MAX_LENGTH {
            format!(
                "Value {} is longer than {} characters",
                val(),
                some_or(int_param(vocab::SH_MAX_LENGTH), "the maximum number of")
            )
        } else if comp == vocab::SH_CC_PATTERN {
            format!(
                "Value {} does not match pattern \"{}\"",
                val(),
                some_or(param(vocab::SH_PATTERN), "the required pattern")
            )
        } else if comp == vocab::SH_CC_IN {
            format!("Value {} is not in the list of allowed values", val())
        } else if comp == vocab::SH_CC_LANGUAGE_IN {
            format!("Value {} has a language tag that is not allowed", val())
        } else if comp == vocab::SH_CC_HAS_VALUE {
            format!(
                "Missing required value {}{}",
                some_or(param(vocab::SH_HAS_VALUE), "the expected value"),
                on_path()
            )
        } else if comp == vocab::SH_CC_UNIQUE_LANG {
            format!("Values{} do not have unique language tags", on_path())
        } else if comp == vocab::SH_CC_EQUALS {
            format!(
                "Value {} must equal the values of {}",
                val(),
                some_or(param(vocab::SH_EQUALS), "the compared property")
            )
        } else if comp == vocab::SH_CC_DISJOINT {
            format!(
                "Value {} must be disjoint from the values of {}",
                val(),
                some_or(param(vocab::SH_DISJOINT), "the compared property")
            )
        } else if comp == vocab::SH_CC_LESS_THAN {
            format!(
                "Value {} is not less than the values of {}",
                val(),
                some_or(param(vocab::SH_LESS_THAN), "the compared property")
            )
        } else if comp == vocab::SH_CC_LESS_THAN_OR_EQUALS {
            format!(
                "Value {} is not less than or equal to the values of {}",
                val(),
                some_or(
                    param(vocab::SH_LESS_THAN_OR_EQUALS),
                    "the compared property"
                )
            )
        } else if comp == vocab::SH_CC_AND {
            format!(
                "Value {} does not conform to all of the given shapes",
                val()
            )
        } else if comp == vocab::SH_CC_OR {
            format!(
                "Value {} does not conform to any of the given shapes",
                val()
            )
        } else if comp == vocab::SH_CC_XONE {
            format!(
                "Value {} does not conform to exactly one of the given shapes",
                val()
            )
        } else if comp == vocab::SH_CC_NOT {
            format!("Value {} conforms to a shape it must not", val())
        } else if comp == vocab::SH_CC_NODE {
            format!(
                "Value {} does not conform to shape {}",
                val(),
                some_or(param(vocab::SH_NODE), "the required shape")
            )
        } else if comp == vocab::SH_CC_CLOSED {
            format!(
                "Predicate{} is not allowed on {} (closed shape)",
                path.as_ref().map(|p| format!(" {p}")).unwrap_or_default(),
                val()
            )
        } else if comp == vocab::SH_CC_QUALIFIED_MIN_COUNT {
            format!(
                "Fewer than {} values{} conform to the qualified shape",
                some_or(
                    int_param(vocab::SH_QUALIFIED_MIN_COUNT),
                    "the required number of"
                ),
                on_path()
            )
        } else if comp == vocab::SH_CC_QUALIFIED_MAX_COUNT {
            format!(
                "More than {} values{} conform to the qualified shape",
                some_or(
                    int_param(vocab::SH_QUALIFIED_MAX_COUNT),
                    "the allowed number of"
                ),
                on_path()
            )
        } else if comp == vocab::SH_CC_EXPRESSION {
            format!("Expression constraint not satisfied for value {}", val())
        } else if comp == vocab::SH_CC_SPARQL {
            "SPARQL constraint not satisfied".to_string()
        } else {
            format!(
                "Value does not conform to constraint component <{}>",
                comp.as_str()
            )
        }
    }

    fn conforms(&self, shape: &NamedOrBlankNode, focus: &Term, visited: &mut Visited) -> bool {
        let mut scratch = Vec::new();
        self.collect(shape, focus, &mut scratch, visited, &[]);
        scratch.is_empty()
    }

    /// Each value-scoped constraint component on `shape` and whether it holds at
    /// value node `u`. `sh:and`/`or`/`not`/`node` report as a unit.
    fn value_checks(
        &self,
        shape: &NamedOrBlankNode,
        u: &Term,
        visited: &mut Visited,
    ) -> Vec<(NamedNode, bool)> {
        let mut checks = Vec::new();

        for c in self.shapes.objects(shape, vocab::SH_CLASS) {
            checks.push((vocab::SH_CC_CLASS.into_owned(), self.is_instance(u, &c)));
        }
        for d in self.shapes.objects(shape, vocab::SH_DATATYPE) {
            if let Term::NamedNode(dt) = d {
                let ok = value_type_holds(&ValueType::Datatype(dt), u);
                checks.push((vocab::SH_CC_DATATYPE.into_owned(), ok));
            }
        }
        for k in self.shapes.objects(shape, vocab::SH_NODE_KIND) {
            if let Some(set) = map_node_kind(&k) {
                checks.push((vocab::SH_CC_NODE_KIND.into_owned(), set.matches(u)));
            }
        }
        // numeric ranges (each bound is its own component)
        for (pred_iri, comp, inclusive) in [
            (vocab::SH_MIN_INCLUSIVE, vocab::SH_CC_MIN_INCLUSIVE, true),
            (vocab::SH_MIN_EXCLUSIVE, vocab::SH_CC_MIN_EXCLUSIVE, false),
        ] {
            if let Some(Term::Literal(b)) = self.shapes.object(shape, pred_iri) {
                let vt = ValueType::NumericRange {
                    lo: Some(Bound {
                        value: b,
                        inclusive,
                    }),
                    hi: None,
                };
                checks.push((comp.into_owned(), value_type_holds(&vt, u)));
            }
        }
        for (pred_iri, comp, inclusive) in [
            (vocab::SH_MAX_INCLUSIVE, vocab::SH_CC_MAX_INCLUSIVE, true),
            (vocab::SH_MAX_EXCLUSIVE, vocab::SH_CC_MAX_EXCLUSIVE, false),
        ] {
            if let Some(Term::Literal(b)) = self.shapes.object(shape, pred_iri) {
                let vt = ValueType::NumericRange {
                    lo: None,
                    hi: Some(Bound {
                        value: b,
                        inclusive,
                    }),
                };
                checks.push((comp.into_owned(), value_type_holds(&vt, u)));
            }
        }
        // length / pattern
        let min_len = self.int(shape, vocab::SH_MIN_LENGTH);
        let max_len = self.int(shape, vocab::SH_MAX_LENGTH);
        if let Some(m) = min_len {
            let vt = ValueType::Length {
                min: Some(m),
                max: None,
            };
            checks.push((
                vocab::SH_CC_MIN_LENGTH.into_owned(),
                value_type_holds(&vt, u),
            ));
        }
        if let Some(m) = max_len {
            let vt = ValueType::Length {
                min: None,
                max: Some(m),
            };
            checks.push((
                vocab::SH_CC_MAX_LENGTH.into_owned(),
                value_type_holds(&vt, u),
            ));
        }
        if let Some(Term::Literal(re)) = self.shapes.object(shape, vocab::SH_PATTERN) {
            let flags = match self.shapes.object(shape, vocab::SH_FLAGS) {
                Some(Term::Literal(f)) => f.value().to_string(),
                _ => String::new(),
            };
            let vt = ValueType::Pattern {
                regex: re.value().to_string(),
                flags,
            };
            checks.push((vocab::SH_CC_PATTERN.into_owned(), value_type_holds(&vt, u)));
        }
        // sh:in
        for list in self.shapes.objects(shape, vocab::SH_IN) {
            let members = self.shapes.read_list(&list);
            checks.push((vocab::SH_CC_IN.into_owned(), members.contains(u)));
        }
        for list in self.shapes.objects(shape, vocab::SH_LANGUAGE_IN) {
            let languages = self
                .shapes
                .read_list(&list)
                .into_iter()
                .filter_map(|term| match term {
                    Term::Literal(literal) => Some(literal.value().to_string()),
                    _ => None,
                })
                .collect();
            checks.push((
                vocab::SH_CC_LANGUAGE_IN.into_owned(),
                value_type_holds(&ValueType::LangIn(languages), u),
            ));
        }

        // logical (unit results)
        for list in self.shapes.objects(shape, vocab::SH_AND) {
            let ok = self
                .shapes
                .read_list(&list)
                .iter()
                .filter_map(term_to_node)
                .all(|m| self.conforms(&m, u, visited));
            checks.push((vocab::SH_CC_AND.into_owned(), ok));
        }
        for list in self.shapes.objects(shape, vocab::SH_OR) {
            let ok = self
                .shapes
                .read_list(&list)
                .iter()
                .filter_map(term_to_node)
                .any(|m| self.conforms(&m, u, visited));
            checks.push((vocab::SH_CC_OR.into_owned(), ok));
        }
        for list in self.shapes.objects(shape, vocab::SH_XONE) {
            let count = self
                .shapes
                .read_list(&list)
                .iter()
                .filter_map(term_to_node)
                .filter(|m| self.conforms(m, u, visited))
                .count();
            checks.push((vocab::SH_CC_XONE.into_owned(), count == 1));
        }
        for n in self.shapes.objects(shape, vocab::SH_NOT) {
            if let Some(nn) = term_to_node(&n) {
                checks.push((
                    vocab::SH_CC_NOT.into_owned(),
                    !self.conforms(&nn, u, visited),
                ));
            }
        }
        for n in self.shapes.objects(shape, vocab::SH_NODE) {
            if let Some(nn) = term_to_node(&n) {
                checks.push((
                    vocab::SH_CC_NODE.into_owned(),
                    self.conforms(&nn, u, visited),
                ));
            }
        }

        checks
    }

    fn is_instance(&self, u: &Term, class: &Term) -> bool {
        succ(self.frozen(), u, &class_path()).contains(class)
    }

    fn int(&self, s: &NamedOrBlankNode, p: NamedNodeRef) -> Option<u64> {
        match self.shapes.object(s, p) {
            Some(Term::Literal(l)) => l.value().parse().ok(),
            _ => None,
        }
    }

    fn bool(&self, s: &NamedOrBlankNode, p: NamedNodeRef) -> bool {
        matches!(
            self.shapes.object(s, p),
            Some(Term::Literal(ref literal)) if matches!(literal.value(), "true" | "1")
        )
    }

    /// `sh:resultSeverity` for results from `shape`: its declared `sh:severity`
    /// (an IRI such as `sh:Warning`/`sh:Info`), defaulting to `sh:Violation`.
    fn severity(&self, shape: &NamedOrBlankNode) -> NamedNode {
        match self.shapes.object(shape, vocab::SH_SEVERITY) {
            Some(Term::NamedNode(n)) => n,
            _ => vocab::SH_VIOLATION.into_owned(),
        }
    }
}

fn is_shape_node(shapes: &Loaded, node: &NamedOrBlankNode) -> bool {
    shapes.has_type(node, vocab::SH_NODE_SHAPE)
        || shapes.has_type(node, vocab::SH_PROPERTY_SHAPE)
        || [
            vocab::SH_PROPERTY,
            vocab::SH_NODE,
            vocab::SH_AND,
            vocab::SH_OR,
            vocab::SH_NOT,
            vocab::SH_XONE,
            vocab::SH_DATATYPE,
            vocab::SH_CLASS,
            vocab::SH_NODE_KIND,
            vocab::SH_IN,
            vocab::SH_HAS_VALUE,
            vocab::SH_PROPERTY,
        ]
        .iter()
        .any(|predicate| shapes.object(node, *predicate).is_some())
}

/// Whether any `sh:select` / `sh:ask` query references `$shapesGraph`, so the
/// shapes graph must be mirrored into a named graph for evaluation.
fn shapes_reference_shapes_graph(shapes: &Loaded) -> bool {
    [vocab::SH_SELECT, vocab::SH_ASK].iter().any(|predicate| {
        shapes.graph.triples_for_predicate(*predicate).any(
            |t| matches!(t.object, oxrdf::TermRef::Literal(l) if l.value().contains("shapesGraph")),
        )
    })
}

fn class_path() -> Path {
    Path::seq(vec![
        Path::Pred(vocab::rdf_type()),
        Path::star(Path::Pred(vocab::rdfs_subclassof())),
    ])
}

/// Index `class → focus-data instances` under `rdf:type / rdfs:subClassOf*`.
///
/// One pass over the `rdf:type` triples replaces the per-shape forward scan
/// (`graph_nodes(data).filter(node is instance of c)`), which was
/// `O(shapes × nodes × type-closure)`. Each instance is attributed to every
/// superclass of its declared type, and the reflexive `subClassOf*` closure of
/// each distinct type is computed at most once. Only nodes present in the focus
/// (data) graph are indexed, matching the original target-selection semantics.
fn build_class_index(
    focus_data: &Graph,
    frozen: &FrozenIndexedDataset,
) -> HashMap<Term, Vec<Term>> {
    let focus_nodes = graph_nodes(focus_data);
    let subclass_star = Path::star(Path::Pred(vocab::rdfs_subclassof()));
    let mut supers: HashMap<Term, Vec<Term>> = HashMap::new();
    let mut index: HashMap<Term, Vec<Term>> = HashMap::new();
    let mut seen: HashSet<(Term, Term)> = HashSet::new();
    for (node, ty) in frozen.triples_for_predicate(&vocab::rdf_type()) {
        if !focus_nodes.contains(&node) {
            continue;
        }
        let classes = supers
            .entry(ty.clone())
            .or_insert_with(|| succ(frozen, &ty, &subclass_star).into_iter().collect());
        for class in classes.iter() {
            if seen.insert((class.clone(), node.clone())) {
                index.entry(class.clone()).or_default().push(node.clone());
            }
        }
    }
    index
}

fn graph_nodes(graph: &Graph) -> HashSet<Term> {
    let mut nodes = HashSet::new();
    for triple in graph.iter() {
        nodes.insert(node_term(triple.subject));
        nodes.insert(triple.object.into_owned());
    }
    nodes
}

fn node_term(s: oxrdf::NamedOrBlankNodeRef) -> Term {
    crate::path::term_of(s.into_owned())
}

/// Render a term for embedding in a default `sh:resultMessage`, matching
/// [`apply_message_template`]'s conventions: IRIs as `<iri>`, blank nodes as
/// `_:id`, literals as their lexical value.
fn render_term(t: &Term) -> String {
    match t {
        Term::NamedNode(n) => format!("<{}>", n.as_str()),
        Term::BlankNode(b) => format!("_:{}", b.as_str()),
        Term::Literal(l) => l.value().to_string(),
    }
}

fn node_term_ref(s: &NamedOrBlankNode) -> Term {
    match s {
        NamedOrBlankNode::NamedNode(n) => Term::NamedNode(n.clone()),
        NamedOrBlankNode::BlankNode(b) => Term::BlankNode(b.clone()),
    }
}

fn map_node_kind(term: &Term) -> Option<NodeKindSet> {
    let Term::NamedNode(n) = term else {
        return None;
    };
    let r = n.as_ref();
    Some(if r == vocab::SH_IRI {
        NodeKindSet::IRI
    } else if r == vocab::SH_BLANK_NODE {
        NodeKindSet::BLANK_NODE
    } else if r == vocab::SH_LITERAL {
        NodeKindSet::LITERAL
    } else if r == vocab::SH_BLANK_NODE_OR_IRI {
        NodeKindSet::BLANK_NODE_OR_IRI
    } else if r == vocab::SH_BLANK_NODE_OR_LITERAL {
        NodeKindSet::BLANK_NODE_OR_LITERAL
    } else if r == vocab::SH_IRI_OR_LITERAL {
        NodeKindSet::IRI_OR_LITERAL
    } else {
        return None;
    })
}