Skip to main content

shacl_rdf/rdf_to_shacl/
parser.rs

1use crate::error::ShaclParserError;
2use crate::rdf_to_shacl::parsers::{node_shape, property_shape};
3use prefixmap::PrefixMap;
4use rudof_rdf::rdf_core::parser::rdf_node_parser::ParserExt;
5use rudof_rdf::rdf_core::vocabs::{RdfVocab, ShaclVocab};
6use rudof_rdf::rdf_core::{
7    Any, FocusRDF, RDFError, Rdf,
8    parser::{
9        RDFParse,
10        rdf_node_parser::{
11            RDFNodeParse,
12            constructors::{ListParser, SuccessParser},
13        },
14    },
15    term::{Object, Triple},
16};
17use shacl_ast::{schema::ShaclSchema, shape::Shape};
18use std::collections::{HashMap, HashSet};
19
20/// State used during the parsing process
21/// This is used to keep track of pending shapes to be parsed
22struct State {
23    pending: Vec<Object>,
24}
25
26impl State {
27    fn pop_pending(&mut self) -> Option<Object> {
28        self.pending.pop()
29    }
30}
31
32impl From<Vec<Object>> for State {
33    fn from(value: Vec<Object>) -> Self {
34        Self { pending: value }
35    }
36}
37
38pub struct ShaclParser<RDF: FocusRDF> {
39    rdf_parser: RDFParse<RDF>,
40    shapes: HashMap<Object, Shape<RDF>>,
41}
42
43impl<RDF: FocusRDF> ShaclParser<RDF> {
44    pub fn new(rdf: RDF) -> ShaclParser<RDF> {
45        ShaclParser {
46            rdf_parser: RDFParse::new(rdf),
47            shapes: HashMap::new(),
48        }
49    }
50
51    pub fn parse(&mut self) -> Result<ShaclSchema<RDF>, ShaclParserError> {
52        let prefixmap: PrefixMap = self.rdf_parser.prefixmap().unwrap_or_default();
53
54        let mut state: State = self.shapes_candidates()?.into();
55        while let Some(node) = state.pop_pending() {
56            if let std::collections::hash_map::Entry::Vacant(e) = self.shapes.entry(node.clone()) {
57                self.rdf_parser.rdf_mut().set_focus(&node.clone().into());
58                let shape = Self::shape()
59                    .parse_focused(self.rdf_parser.rdf_mut())
60                    .map_err(|e| ShaclParserError::RDFParseError { err: e })?;
61                e.insert(shape);
62            }
63        }
64
65        Ok(ShaclSchema::new()
66            .with_prefixmap(prefixmap)
67            .with_shapes(self.shapes.clone()))
68    }
69
70    /// Shapes candidates are defined in Appendix A of SHACL spec (Syntax rules)
71    /// The text is:
72    /// A shape is an IRI or blank node s that fulfills at least one of the following conditions in the shapes graph:
73    /// - s is a SHACL instance of sh:NodeShape or sh:PropertyShape.
74    /// - s is subject of a triple that has sh:targetClass, sh:targetNode, sh:targetObjectsOf or sh:targetSubjectsOf as predicate.
75    /// - s is subject of a triple that has a parameter as predicate.
76    /// - s is a value of a shape-expecting, non-list-taking parameter such as sh:node,
77    ///   or a member of a SHACL list that is a value of a shape-expecting and list-taking parameter such as sh:or.
78    fn shapes_candidates(&mut self) -> Result<Vec<Object>, ShaclParserError> {
79        // instances of `sh:NodeShape`
80        let node_shape_instances: HashSet<_> = self
81            .rdf_parser
82            .rdf()
83            .triples_matching(&Any, &Self::rdf_type_iri(), &Self::sh_node_shape_iri())
84            .map_err(|e| ShaclParserError::Custom { msg: e.to_string() })?
85            .map(Triple::into_subject)
86            .collect();
87
88        // instances of `sh:PropertyShape`
89        let property_shapes_instances: HashSet<_> = self
90            .rdf_parser
91            .rdf()
92            .triples_matching(&Any, &Self::rdf_type_iri(), &Self::sh_property_shape_iri())
93            .map_err(|e| ShaclParserError::Custom { msg: e.to_string() })?
94            .map(Triple::into_subject)
95            .collect();
96
97        // Instances of `sh:Shape`
98        let shape_instances: HashSet<_> = self
99            .rdf_parser
100            .rdf()
101            .triples_matching(&Any, &Self::rdf_type_iri(), &Self::sh_shape_iri())
102            .map_err(|e| ShaclParserError::Custom { msg: e.to_string() })?
103            .map(Triple::into_subject)
104            .collect();
105
106        // Subjects of sh:targetClass
107        let subjects_target_class: HashSet<_> = self
108            .rdf_parser
109            .rdf()
110            .triples_matching::<_, RDF::IRI, _>(&Any, &ShaclVocab::sh_target_class().clone().into(), &Any)
111            .map_err(|e| ShaclParserError::Custom { msg: e.to_string() })?
112            .map(Triple::into_subject)
113            .collect();
114
115        // Subjects of sh:targetSubjectsOf
116        let subjects_target_subjects_of: HashSet<_> = self
117            .rdf_parser
118            .rdf()
119            .triples_matching::<_, RDF::IRI, _>(&Any, &ShaclVocab::sh_target_subjects_of().clone().into(), &Any)
120            .map_err(|e| ShaclParserError::Custom { msg: e.to_string() })?
121            .map(Triple::into_subject)
122            .collect();
123
124        // Subjects of sh:targetObjectsOf
125        let subjects_target_objects_of: HashSet<_> = self
126            .rdf_parser
127            .rdf()
128            .triples_matching::<_, RDF::IRI, _>(&Any, &ShaclVocab::sh_target_objects_of().clone().into(), &Any)
129            .map_err(|e| ShaclParserError::Custom { msg: e.to_string() })?
130            .map(Triple::into_subject)
131            .collect();
132
133        // Subjects of sh:targetNode
134        let subjects_target_node: HashSet<_> = self
135            .rdf_parser
136            .rdf()
137            .triples_matching::<_, RDF::IRI, _>(&Any, &ShaclVocab::sh_target_node().clone().into(), &Any)
138            .map_err(|e| ShaclParserError::Custom { msg: e.to_string() })?
139            .map(Triple::into_subject)
140            .collect();
141
142        // Search shape expecting parameters: https://www.w3.org/TR/shacl12-core/#dfn-shape-expecting
143        // elements of `sh:and` list
144        let sh_and_values = self.get_sh_and_values()?;
145
146        // elements of `sh:or` list
147        let sh_or_values = self.get_sh_or_values()?;
148
149        // elements of `sh:not` list
150        let sh_not_values = self.get_sh_not_values()?;
151
152        // subjects with property `sh:property`
153        let subjects_property = self.objects_with_predicate(Self::sh_property_iri())?;
154
155        // elements of `sh:node` list
156        let sh_qualified_value_shape_nodes = self.get_sh_qualified_value_shape()?;
157
158        // elements of `sh:node` list
159        let sh_node_values = self.get_sh_node_values()?;
160
161        // elements of `sh:xone` list
162        let sh_xone_values = self.get_sh_xone_values()?;
163
164        // elements of `sh:reifierShape` list
165        let sh_reifier_shape_values = self.get_sh_reifier_shape_values()?;
166
167        // I would prefer a code like: node_shape_instances.union(subjects_property).union(...)
168        // But looking to the union API in HashSet, I think it can't be chained
169        let mut candidates = HashSet::new();
170        candidates.extend(node_shape_instances);
171        candidates.extend(subjects_property);
172        candidates.extend(sh_or_values);
173        candidates.extend(sh_xone_values);
174        candidates.extend(sh_and_values);
175        candidates.extend(sh_not_values);
176        candidates.extend(sh_qualified_value_shape_nodes);
177        candidates.extend(sh_node_values);
178        candidates.extend(property_shapes_instances);
179        candidates.extend(sh_reifier_shape_values);
180        candidates.extend(shape_instances);
181        candidates.extend(subjects_target_class);
182        candidates.extend(subjects_target_subjects_of);
183        candidates.extend(subjects_target_objects_of);
184        candidates.extend(subjects_target_node);
185
186        Ok(subjects_as_nodes::<RDF>(candidates)?)
187    }
188
189    fn get_sh_or_values(&mut self) -> Result<HashSet<RDF::Subject>, ShaclParserError> {
190        let mut rs = HashSet::new();
191        for subject in self.objects_with_predicate(Self::sh_or_iri())? {
192            self.rdf_parser.set_focus(&subject.into());
193            let vs = ListParser::new().parse_focused(self.rdf_parser.rdf_mut())?;
194            for v in vs {
195                if let Ok(subj) = term_to_subject::<RDF>(&v, "sh:or") {
196                    rs.insert(subj.clone());
197                } else {
198                    return Err(ShaclParserError::OrValueNoSubject { term: format!("{v}") });
199                }
200            }
201        }
202        Ok(rs)
203    }
204
205    fn get_sh_xone_values(&mut self) -> Result<HashSet<RDF::Subject>, ShaclParserError> {
206        let mut rs = HashSet::new();
207        for subject in self.objects_with_predicate(Self::sh_xone_iri())? {
208            self.rdf_parser.set_focus(&subject.into());
209            let vs = ListParser::new().parse_focused(self.rdf_parser.rdf_mut())?;
210            for v in vs {
211                if let Ok(subj) = &term_to_subject::<RDF>(&v, "sh:xone") {
212                    rs.insert(subj.clone());
213                } else {
214                    return Err(ShaclParserError::XOneValueNoSubject { term: format!("{v}") });
215                }
216            }
217        }
218        Ok(rs)
219    }
220
221    fn get_sh_reifier_shape_values(&mut self) -> Result<HashSet<RDF::Subject>, ShaclParserError> {
222        let mut rs = HashSet::new();
223        for s in self.objects_with_predicate(Self::sh_reifier_shape_iri())? {
224            rs.insert(s);
225        }
226        Ok(rs)
227    }
228
229    fn get_sh_and_values(&mut self) -> Result<HashSet<RDF::Subject>, ShaclParserError> {
230        let mut rs = HashSet::new();
231        for subject in self.objects_with_predicate(Self::sh_and_iri())? {
232            self.rdf_parser.set_focus(&subject.into());
233            let vs = ListParser::new().parse_focused(self.rdf_parser.rdf_mut())?;
234            for v in vs {
235                if let Ok(subj) = term_to_subject::<RDF>(&v, "sh:and") {
236                    rs.insert(subj);
237                } else {
238                    return Err(ShaclParserError::AndValueNoSubject { term: format!("{v}") });
239                }
240            }
241        }
242        Ok(rs)
243    }
244
245    fn get_sh_not_values(&mut self) -> Result<HashSet<RDF::Subject>, ShaclParserError> {
246        let mut rs = HashSet::new();
247        for s in self.objects_with_predicate(Self::sh_not_iri())? {
248            rs.insert(s);
249        }
250        Ok(rs)
251    }
252
253    fn get_sh_qualified_value_shape(&mut self) -> Result<HashSet<RDF::Subject>, ShaclParserError> {
254        let mut rs = HashSet::new();
255        for s in self.objects_with_predicate(Self::sh_qualified_value_shape_iri())? {
256            rs.insert(s);
257        }
258        Ok(rs)
259    }
260
261    fn get_sh_node_values(&mut self) -> Result<HashSet<RDF::Subject>, ShaclParserError> {
262        let mut rs = HashSet::new();
263        for s in self.objects_with_predicate(Self::sh_node_iri())? {
264            rs.insert(s);
265        }
266        Ok(rs)
267    }
268
269    fn objects_with_predicate(&self, pred: RDF::IRI) -> Result<HashSet<RDF::Subject>, ShaclParserError> {
270        let msg = format!("objects with predicate {pred}");
271        let values_as_subjects = self
272            .rdf_parser
273            .rdf()
274            .triples_with_predicate(&pred)
275            .map_err(|e| ShaclParserError::Custom { msg: e.to_string() })?
276            .map(Triple::into_object)
277            .flat_map(|t| term_to_subject::<RDF>(&t.clone(), msg.as_str()))
278            .collect();
279        Ok(values_as_subjects)
280    }
281
282    fn rdf_type_iri() -> RDF::IRI {
283        RdfVocab::rdf_type().clone().into()
284    }
285
286    fn sh_node_shape_iri() -> RDF::Term {
287        RDF::iris_as_term(ShaclVocab::sh_node_shape())
288    }
289
290    fn sh_property_shape_iri() -> RDF::Term {
291        RDF::iris_as_term(ShaclVocab::sh_property_shape())
292    }
293
294    fn sh_shape_iri() -> RDF::Term {
295        RDF::iris_as_term(ShaclVocab::sh_shape())
296    }
297
298    fn sh_property_iri() -> RDF::IRI {
299        ShaclVocab::sh_property().clone().into()
300    }
301
302    fn sh_or_iri() -> RDF::IRI {
303        ShaclVocab::sh_or().clone().into()
304    }
305
306    fn sh_xone_iri() -> RDF::IRI {
307        ShaclVocab::sh_xone().clone().into()
308    }
309
310    fn sh_reifier_shape_iri() -> RDF::IRI {
311        ShaclVocab::sh_reifier_shape().clone().into()
312    }
313
314    fn sh_and_iri() -> RDF::IRI {
315        ShaclVocab::sh_and().clone().into()
316    }
317
318    fn sh_not_iri() -> RDF::IRI {
319        ShaclVocab::sh_not().clone().into()
320    }
321
322    fn sh_node_iri() -> RDF::IRI {
323        ShaclVocab::sh_node().clone().into()
324    }
325
326    fn sh_qualified_value_shape_iri() -> RDF::IRI {
327        ShaclVocab::sh_qualified_value_shape().clone().into()
328    }
329
330    fn shape() -> impl RDFNodeParse<RDF, Output = Shape<RDF>>
331    where
332        RDF: FocusRDF + 'static,
333    {
334        node_shape()
335            .then(move |ns| SuccessParser::new(Shape::NodeShape(Box::new(ns))))
336            .or(property_shape().then(|ps| SuccessParser::new(Shape::PropertyShape(Box::new(ps)))))
337    }
338}
339
340fn term_to_subject<RDF>(term: &RDF::Term, context: &str) -> Result<RDF::Subject, ShaclParserError>
341where
342    RDF: FocusRDF,
343{
344    RDF::term_as_subject(term).map_err(|_| ShaclParserError::ExpectedSubject {
345        term: term.to_string(),
346        context: context.to_string(),
347    })
348}
349
350fn subjects_as_nodes<RDF: Rdf>(subjs: HashSet<RDF::Subject>) -> Result<Vec<Object>, RDFError> {
351    subjs
352        .into_iter()
353        .map(|s| RDF::subject_as_node(&s).map_err(|_| RDFError::FailedSubjectToRDFNodeError { subject: s.to_string() }))
354        .collect()
355}