1use super::compiled_shacl_error::CompiledShaclError;
2use super::shape::ShapeIR;
3use crate::dependency_graph::{DependencyGraph, PosNeg};
4use crate::shape_label_idx::ShapeLabelIdx;
5use either::Either::{self, Left, Right};
6use iri_s::IriS;
7use prefixmap::PrefixMap;
8use rudof_rdf::rdf_core::{RDFFormat, Rdf, term::Object};
9use rudof_rdf::rdf_impl::{InMemoryGraph, ReaderMode};
10use shacl_ast::ShaclSchema;
11use shacl_rdf::ShaclParser;
12use std::collections::hash_map::Entry;
13use std::collections::{HashMap, HashSet};
14use std::fmt::Display;
15use std::io;
16use tracing::{debug, info, trace};
17
18#[derive(Clone, Debug)]
19pub struct SchemaIR {
20 labels_idx_map: HashMap<Object, ShapeLabelIdx>,
23 idx_labels_map: HashMap<ShapeLabelIdx, Object>,
24 shapes: HashMap<ShapeLabelIdx, ShapeIR>,
25 prefixmap: PrefixMap,
26 base: Option<IriS>,
27 dependency_graph: DependencyGraph,
28 shape_label_counter: usize,
29}
30
31impl SchemaIR {
32 pub fn new(prefixmap: PrefixMap, base: Option<IriS>) -> SchemaIR {
33 SchemaIR {
34 labels_idx_map: HashMap::new(),
35 idx_labels_map: HashMap::new(),
36 shapes: HashMap::new(),
37 prefixmap,
38 base,
39 dependency_graph: DependencyGraph::new(),
40 shape_label_counter: 0,
41 }
42 }
43
44 pub fn from_reader<R: io::Read>(
45 read: &mut R,
46 source_name: &str,
47 format: &RDFFormat,
48 base: Option<&str>,
49 reader_mode: &ReaderMode,
50 ) -> Result<SchemaIR, Box<CompiledShaclError>> {
51 let mut rdf = InMemoryGraph::new();
52 rdf.merge_from_reader(read, source_name, format, base, reader_mode)
53 .map_err(|e| CompiledShaclError::RdfGraphError { err: Box::new(e) })?;
54 let schema = ShaclParser::new(rdf)
55 .parse()
56 .map_err(|e| CompiledShaclError::ShaclParserError { err: Box::new(e) })?;
57 let schema_ir: SchemaIR = schema.try_into()?;
58 Ok(schema_ir)
59 }
60
61 pub fn from_str(
62 data: &str,
63 format: &RDFFormat,
64 base: Option<&str>,
65 reader_mode: &ReaderMode,
66 ) -> Result<SchemaIR, Box<CompiledShaclError>> {
67 Self::from_reader(&mut std::io::Cursor::new(&data), "String", format, base, reader_mode)
68 }
69
70 pub fn add_shape_idx(
73 &mut self,
74 sref: Object,
75 ) -> Result<Either<ShapeLabelIdx, ShapeLabelIdx>, Box<CompiledShaclError>> {
76 match self.labels_idx_map.entry(sref.clone()) {
77 Entry::Occupied(entry) => Ok(Left(*entry.get())),
78 Entry::Vacant(entry) => {
79 let label_idx = ShapeLabelIdx::new(self.shape_label_counter);
80 self.shape_label_counter += 1;
81 entry.insert(label_idx);
82 self.idx_labels_map.insert(label_idx, sref);
83 Ok(Right(label_idx))
84 },
85 }
86 }
87
88 pub fn prefix_map(&self) -> PrefixMap {
89 self.prefixmap.clone()
90 }
91
92 pub fn base(&self) -> &Option<IriS> {
93 &self.base
94 }
95
96 pub fn iter(&self) -> impl Iterator<Item = (&Object, &ShapeIR)> {
97 self.labels_idx_map.iter().map(move |(node, label_idx)| {
98 let shape = self.shapes.get(label_idx).unwrap_or_else(|| {
99 panic!(
100 "Internal error: Shape label index {label_idx} for node {node} not found in shapes map: {:?}",
101 self.shapes
102 )
103 });
104 (node, shape)
105 })
106 }
107
108 pub fn iter_with_targets(&self) -> impl Iterator<Item = (&Object, &ShapeIR)> {
110 self.iter().filter(|(_, shape)| !shape.targets().is_empty())
111 }
112
113 pub fn get_shape_idx(&self, sref: &Object) -> Option<ShapeLabelIdx> {
115 self.labels_idx_map.get(sref).copied()
116 }
117
118 pub fn get_shape(&self, sref: &Object) -> Option<&ShapeIR> {
119 self.labels_idx_map.get(sref).map(|label_idx| {
120 self.shapes
121 .get(label_idx)
122 .unwrap_or_else(|| panic!("Internal error: SHACL/SchemaIR. Shape label index {label_idx} corresponding to {sref} not found in shapes map {:?}", self.shapes))
123 })
124 }
125
126 pub fn add_shape(&mut self, idx: ShapeLabelIdx, shape: ShapeIR) -> Result<ShapeLabelIdx, Box<CompiledShaclError>> {
127 self.shapes.insert(idx, shape);
128 Ok(idx)
129 }
130
131 pub fn compile<RDF: Rdf>(schema: &ShaclSchema<RDF>) -> Result<SchemaIR, Box<CompiledShaclError>> {
132 trace!("Compiling SHACL schema");
133 let mut schema_ir = SchemaIR::new(schema.prefix_map(), schema.base());
134 for (rdf_node, shape) in schema.iter() {
135 match schema_ir.add_shape_idx(rdf_node.clone())? {
136 Right(idx) => {
137 trace!("Compiling shape {} with new index {}", rdf_node, idx);
138 let _idx = ShapeIR::compile(shape.to_owned(), schema, &idx, &mut schema_ir)?;
139 },
140 Left(idx) => {
141 trace!("Shape {} already compiled with {}, skipping", rdf_node, idx);
142 },
143 }
144 }
145 schema_ir.build_dependency_graph();
146 if schema_ir.dependency_graph.has_cycles() {
147 info!(
148 "Warning: The dependency graph has cycles. This is known as a recursive schema and the SHACL semantics for these schemas is implementation dependent"
149 );
150 info!(
151 "More information about recursive schemas can be found at https://www.w3.org/TR/shacl/#shapes-recursion"
152 );
153 debug!("Dependency graph with cycles: {}", schema_ir.dependency_graph);
154 }
155 if schema_ir.dependency_graph.has_neg_cycle() {
156 info!(
157 "Warning: The dependency graph has negative cycles. This may lead to unexpected behavior in SHACL validation due to non-stratified negation"
158 );
159 let neg_cycles_str: String = schema_ir
160 .dependency_graph
161 .neg_cycles()
162 .iter()
163 .map(|cycles| cycles.iter().map(show_cycle).collect::<Vec<_>>().join("\n "))
164 .collect::<Vec<_>>()
165 .join("\n---\n");
166 debug!("Negative cycles: {}", neg_cycles_str);
167 }
168 Ok(schema_ir)
169 }
170
171 pub fn get_shape_from_idx(&self, shape_idx: &ShapeLabelIdx) -> Option<&ShapeIR> {
172 self.shapes.get(shape_idx)
173 }
174
175 pub(crate) fn build_dependency_graph(&mut self) {
176 let mut dg = DependencyGraph::new();
177 let mut visited = HashSet::new();
178 for (shape_idx, shape_ir) in self.shapes.iter() {
179 shape_ir.add_edges(*shape_idx, &mut dg, PosNeg::pos(), self, &mut visited);
181 }
182 self.dependency_graph = dg;
183 }
184}
185
186impl<RDF: Rdf> TryFrom<ShaclSchema<RDF>> for SchemaIR {
187 type Error = Box<CompiledShaclError>;
188
189 fn try_from(schema: ShaclSchema<RDF>) -> Result<Self, Self::Error> {
190 Self::compile(&schema)
191 }
192}
193
194impl<RDF: Rdf> TryFrom<&ShaclSchema<RDF>> for SchemaIR {
195 type Error = Box<CompiledShaclError>;
196
197 fn try_from(schema: &ShaclSchema<RDF>) -> Result<Self, Self::Error> {
198 Self::compile(schema)
199 }
200}
201
202impl Display for SchemaIR {
203 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
204 writeln!(f, "SHACL shapes graph IR",)?;
205 for (node, shape) in self.shapes.iter() {
206 let node_label = self
207 .idx_labels_map
208 .get(node)
209 .map(|n| n.show_qualified(&self.prefixmap))
210 .unwrap_or("?".to_string());
211 writeln!(f, "{node_label}[{node}] -> {shape}")?;
212 }
213 writeln!(f, "Dependency graph: {}", self.dependency_graph)?;
214 Ok(())
215 }
216}
217
218fn show_cycle(cycle: &(ShapeLabelIdx, ShapeLabelIdx, Vec<ShapeLabelIdx>)) -> String {
219 let (from, to, shapes) = cycle;
220 let shapes_str = shapes.iter().map(|s| s.to_string()).collect::<Vec<_>>().join(" -> ");
221 format!("Cycle from {} to {}: {}", from, to, shapes_str)
222}
223
224#[cfg(test)]
225mod tests {
226 use std::io::Cursor;
227
228 use rudof_rdf::rdf_core::RDFFormat;
229 use rudof_rdf::rdf_impl::{InMemoryGraph, ReaderMode};
230
231 use shacl_rdf::ShaclParser;
232
233 use super::SchemaIR;
234
235 const SCHEMA: &str = r#"
236 @prefix sh: <http://www.w3.org/ns/shacl#> .
237 @prefix ex: <http://example.org/> .
238 @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
239
240 ex:PersonShape a sh:NodeShape ;
241 sh:targetClass ex:Person ;
242 sh:property [
243 sh:path ex:name ;
244 sh:datatype xsd:string ;
245 sh:minCount 1 ;
246 sh:maxCount 1 ;
247 ] ;
248 sh:property [
249 sh:path ex:age ;
250 sh:datatype xsd:integer ;
251 sh:minCount 1 ;
252 sh:maxCount 1 ;
253 ] .
254
255 ex:PersonShape2 a sh:NodeShape ;
256 sh:targetClass ex:Person ;
257 sh:property [
258 sh:path ex:name ;
259 sh:datatype xsd:string ;
260 sh:minCount 1 ;
261 sh:maxCount 1 ;
262 ] ;
263 sh:property [
264 sh:path ex:age ;
265 sh:datatype xsd:integer ;
266 sh:minCount 1 ;
267 sh:maxCount 1 ;
268 ] .
269 "#;
270
271 fn load_schema(shacl_schema: &str) -> SchemaIR {
272 let mut reader = Cursor::new(shacl_schema);
273 let rdf_format = RDFFormat::Turtle;
274 let base = None;
275
276 let rdf = InMemoryGraph::from_reader(&mut reader, "String", &rdf_format, base, &ReaderMode::default()).unwrap();
277
278 ShaclParser::new(rdf).parse().unwrap().try_into().unwrap()
279 }
280
281 #[test]
282 fn test_schema_iterator() {
283 let schema = load_schema(SCHEMA);
284 let actual = schema.iter_with_targets().count();
285 let expected = 2;
286 assert_eq!(actual, expected);
287 }
288}