shapes_converter/shacl_to_shex/
shacl2shex.rs

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
use super::{Shacl2ShExConfig, Shacl2ShExError};
use iri_s::IriS;
use prefixmap::IriRef;
use shacl_ast::{
    component::Component, node_shape::NodeShape, property_shape::PropertyShape,
    shape::Shape as ShaclShape, target::Target, Schema as ShaclSchema,
};
use shex_ast::{
    BNode, NodeConstraint, Schema as ShExSchema, Shape as ShExShape, ShapeExpr, ShapeExprLabel,
    TripleExpr, TripleExprWrapper, ValueSetValue,
};
use srdf::{Object, RDFNode, SHACLPath};
use tracing::debug;

#[allow(dead_code)] // TODO: only for config...
pub struct Shacl2ShEx {
    config: Shacl2ShExConfig,
    current_shex: ShExSchema,
}

impl Shacl2ShEx {
    pub fn new(config: &Shacl2ShExConfig) -> Shacl2ShEx {
        Shacl2ShEx {
            config: config.clone(),
            current_shex: ShExSchema::new(),
        }
    }

    pub fn current_shex(&self) -> &ShExSchema {
        &self.current_shex
    }

    pub fn convert(&mut self, schema: &ShaclSchema) -> Result<(), Shacl2ShExError> {
        let prefixmap = schema.prefix_map().without_rich_qualifying();
        self.current_shex = ShExSchema::new().with_prefixmap(Some(prefixmap));
        for (_, shape) in schema.iter() {
            match &shape {
                shacl_ast::shape::Shape::NodeShape(ns) => {
                    let (label, shape_expr, is_abstract) = self.convert_shape(ns, schema)?;
                    self.current_shex.add_shape(label, shape_expr, is_abstract)
                }
                shacl_ast::shape::Shape::PropertyShape(_) => {
                    // Ignoring property shapes at top level conversion
                }
            }
        }
        Ok(())
    }

    pub fn convert_shape(
        &self,
        shape: &NodeShape,
        schema: &ShaclSchema,
    ) -> Result<(ShapeExprLabel, ShapeExpr, bool), Shacl2ShExError> {
        let label = self.rdfnode2label(shape.id())?;
        let shape_expr = self.node_shape2shape_expr(shape, schema)?;
        let is_abstract = false; // TODO: No virtual shapes in SHACL so it is always false
        Ok((label, shape_expr, is_abstract))
    }

    pub fn rdfnode2label(&self, node: &RDFNode) -> Result<ShapeExprLabel, Shacl2ShExError> {
        match node {
            srdf::Object::Iri(iri) => Ok(ShapeExprLabel::iri(iri.clone())),
            srdf::Object::BlankNode(bn) => Ok(ShapeExprLabel::bnode(BNode::new(bn))),
            srdf::Object::Literal(lit) => Err(Shacl2ShExError::RDFNode2LabelLiteral {
                literal: lit.clone(),
            }),
        }
    }

    pub fn node_shape2shape_expr(
        &self,
        shape: &NodeShape,
        schema: &ShaclSchema,
    ) -> Result<ShapeExpr, Shacl2ShExError> {
        let mut exprs = Vec::new();
        for node in shape.property_shapes() {
            match schema.get_shape(node) {
                None => todo!(),
                Some(shape) => match shape {
                    ShaclShape::PropertyShape(ps) => {
                        let tc = self.property_shape2triple_constraint(ps)?;
                        exprs.push(tc);
                        Ok(())
                    }
                    ShaclShape::NodeShape(ns) => Err(Shacl2ShExError::NotExpectedNodeShape {
                        node_shape: ns.clone(),
                    }),
                },
            }?
        }
        let is_closed = None; // TODO: Check real value
        let extra = None; // TODO: Check if we could find a way to obtain extras in SHACL ?
        let mut te = if exprs.is_empty() {
            None
        } else {
            Some(TripleExpr::each_of(exprs))
        };
        if self.config.add_target_class() {
            let target_class_expr = self.convert_target_decls(shape.targets(), schema)?;
            te = match (te, target_class_expr) {
                (None, None) => None,
                (None, Some(t)) => Some(t),
                (Some(t), None) => Some(t),
                (Some(t1), Some(t2)) => Some(self.merge_triple_exprs(&t1, &t2)),
            };
        }
        let shape = ShExShape::new(is_closed, extra, te);
        Ok(ShapeExpr::shape(shape))
    }

    /// Collect targetClass declarations and add a rdf:type constraint for each
    pub fn convert_target_decls(
        &self,
        targets: &Vec<Target>,
        schema: &ShaclSchema,
    ) -> Result<Option<TripleExpr>, Shacl2ShExError> {
        let mut values = Vec::new();
        for target in targets {
            if let Some(value) = self.target2value_set_value(target, schema)? {
                values.push(value);
            }
        }
        let value_cls = ShapeExpr::node_constraint(NodeConstraint::new().with_values(values));
        let tc = TripleExpr::triple_constraint(
            None,
            None,
            IriRef::iri(IriS::rdf_type()),
            Some(value_cls),
            None,
            None,
        );
        Ok(Some(tc))
    }

    pub fn target2value_set_value(
        &self,
        target: &Target,
        _schema: &ShaclSchema,
    ) -> Result<Option<ValueSetValue>, Shacl2ShExError> {
        match target {
            Target::TargetNode(_) => Ok(None),
            Target::TargetClass(cls) => {
                let value_set_value = match cls {
                    Object::Iri(iri) => Ok(ValueSetValue::iri(IriRef::iri(iri.clone()))),
                    Object::BlankNode(bn) => {
                        Err(Shacl2ShExError::UnexpectedBlankNodeForTargetClass {
                            bnode: bn.clone(),
                        })
                    }
                    Object::Literal(lit) => Err(Shacl2ShExError::UnexpectedLiteralForTargetClass {
                        literal: lit.clone(),
                    }),
                }?;
                Ok(Some(value_set_value))
            }
            Target::TargetSubjectsOf(_) => Ok(None),
            Target::TargetObjectsOf(_) => Ok(None),
        }
    }

    pub fn merge_triple_exprs(&self, te1: &TripleExpr, te2: &TripleExpr) -> TripleExpr {
        match te1 {
            TripleExpr::EachOf {
                id,
                expressions,
                min,
                max,
                sem_acts,
                annotations,
            } => match te2 {
                TripleExpr::EachOf {
                    id: _,
                    expressions: exprs,
                    min: _,
                    max: _,
                    sem_acts: _,
                    annotations: _,
                } => TripleExpr::EachOf {
                    id: id.clone(),
                    expressions: Self::merge_expressions(expressions, exprs),
                    min: *min,
                    max: *max,
                    sem_acts: sem_acts.clone(),
                    annotations: annotations.clone(),
                },
                tc @ TripleExpr::TripleConstraint {
                    id,
                    negated: _,
                    inverse: _,
                    predicate: _,
                    value_expr: _,
                    min,
                    max,
                    sem_acts,
                    annotations,
                } => TripleExpr::EachOf {
                    id: id.clone(),
                    expressions: Self::merge_expressions(
                        expressions,
                        &vec![TripleExprWrapper { te: tc.clone() }],
                    ),
                    min: *min,
                    max: *max,
                    sem_acts: sem_acts.clone(),
                    annotations: annotations.clone(),
                },
                _ => todo!(),
            },
            tc @ TripleExpr::TripleConstraint {
                id,
                negated: _,
                inverse: _,
                predicate: _,
                value_expr: _,
                min,
                max,
                sem_acts,
                annotations,
            } => match te2 {
                TripleExpr::EachOf {
                    id: _,
                    expressions: exprs,
                    min: _,
                    max: _,
                    sem_acts: _,
                    annotations: _,
                } => TripleExpr::EachOf {
                    id: id.clone(),
                    expressions: Self::merge_expressions(
                        &vec![TripleExprWrapper { te: tc.clone() }],
                        exprs,
                    ),
                    min: *min,
                    max: *max,
                    sem_acts: sem_acts.clone(),
                    annotations: annotations.clone(),
                },
                tc2 @ TripleExpr::TripleConstraint {
                    id,
                    negated: _,
                    inverse: _,
                    predicate: _,
                    value_expr: _,
                    min,
                    max,
                    sem_acts,
                    annotations,
                } => TripleExpr::EachOf {
                    id: id.clone(),
                    expressions: vec![
                        TripleExprWrapper { te: tc.clone() },
                        TripleExprWrapper { te: tc2.clone() },
                    ],
                    min: *min,
                    max: *max,
                    sem_acts: sem_acts.clone(),
                    annotations: annotations.clone(),
                },
                _ => todo!(),
            },
            _ => todo!(),
        }
    }

    pub fn merge_expressions(
        e1: &Vec<TripleExprWrapper>,
        e2: &Vec<TripleExprWrapper>,
    ) -> Vec<TripleExprWrapper> {
        let mut es = Vec::new();
        for e in e1 {
            es.push(e.clone())
        }
        for e in e2 {
            es.push(e.clone())
        }
        es
    }

    pub fn property_shape2triple_constraint(
        &self,
        shape: &PropertyShape,
    ) -> Result<TripleExpr, Shacl2ShExError> {
        let predicate = self.shacl_path2predicate(shape.path())?;
        let negated = None;
        let inverse = None;
        let se = self.components2shape_expr(shape.components())?;
        let min = None;
        let max = None;
        Ok(TripleExpr::triple_constraint(
            negated, inverse, predicate, se, min, max,
        ))
    }

    pub fn components2shape_expr(
        &self,
        components: &Vec<Component>,
    ) -> Result<Option<ShapeExpr>, Shacl2ShExError> {
        let mut ses = Vec::new();
        for c in components {
            let se = self.component2shape_expr(c)?;
            ses.push(se);
        }
        if ses.is_empty() {
            Ok(None)
        } else {
            match ses.len() {
                1 => {
                    let se = &ses[0];
                    Ok(Some(se.clone()))
                }
                _ => {
                    // Err(Shacl2ShExError::not_implemented("Conversion of shapes with multiple components is not implemented yet: {components:?}"))}
                    debug!("More than one component: {components:?}, taking only the first one");
                    let se = &ses[0];
                    Ok(Some(se.clone()))
                }
            }
        }
    }

    pub fn create_class_constraint(&self, cls: &RDFNode) -> Result<ShapeExpr, Shacl2ShExError> {
        let rdf_type = IriRef::iri(IriS::rdf_type());
        let value = match cls {
            Object::Iri(iri) => ValueSetValue::iri(IriRef::iri(iri.clone())),
            Object::BlankNode(_) => todo!(),
            Object::Literal(_) => todo!(),
        };
        let cls = NodeConstraint::new().with_values(vec![value]);
        let te = TripleExpr::triple_constraint(
            None,
            None,
            rdf_type,
            Some(ShapeExpr::node_constraint(cls)),
            None,
            None,
        );
        let se = ShapeExpr::shape(ShExShape::new(None, None, Some(te)));
        Ok(se)
    }

    pub fn component2shape_expr(
        &self,
        component: &Component,
    ) -> Result<ShapeExpr, Shacl2ShExError> {
        match component {
            Component::Class(cls) => {
                debug!("TODO: Converting Class components for {cls:?} doesn't match rdfs:subClassOf semantics of SHACL yet");
                let se = self.create_class_constraint(cls)?;
                Ok(se)
            }
            Component::Datatype(dt) => Ok(ShapeExpr::node_constraint(
                NodeConstraint::new().with_datatype(dt.clone()),
            )),
            Component::NodeKind(_) => todo!(),
            Component::MinCount(_) => todo!(),
            Component::MaxCount(_) => todo!(),
            Component::MinExclusive(_) => todo!(),
            Component::MaxExclusive(_) => todo!(),
            Component::MinInclusive(_) => todo!(),
            Component::MaxInclusive(_) => todo!(),
            Component::MinLength(_) => todo!(),
            Component::MaxLength(_) => todo!(),
            Component::Pattern {
                pattern: _,
                flags: _,
            } => todo!(),
            Component::UniqueLang(_) => todo!(),
            Component::LanguageIn { langs: _ } => todo!(),
            Component::Equals(_) => todo!(),
            Component::Disjoint(_) => todo!(),
            Component::LessThan(_) => todo!(),
            Component::LessThanOrEquals(_) => todo!(),
            Component::Or { shapes: _ } => {
                debug!("Not implemented OR Shapes");
                Ok(ShapeExpr::empty_shape())
            }
            Component::And { shapes: _ } => todo!(),
            Component::Not { shape: _ } => todo!(),
            Component::Xone { shapes: _ } => todo!(),
            Component::Closed {
                is_closed: _,
                ignored_properties: _,
            } => todo!(),
            Component::Node { shape: _ } => todo!(),
            Component::HasValue { value: _ } => todo!(),
            Component::In { values: _ } => todo!(),
            Component::QualifiedValueShape {
                shape: _,
                qualified_min_count: _,
                qualified_max_count: _,
                qualified_value_shapes_disjoint: _,
            } => todo!(),
        }
    }

    pub fn shacl_path2predicate(&self, path: &SHACLPath) -> Result<IriRef, Shacl2ShExError> {
        match path {
            SHACLPath::Predicate { pred } => Ok(IriRef::iri(pred.clone())),
            _ => todo!(),
        }
    }
}