tensorlogic-oxirs-bridge 0.1.0

RDF/GraphQL/SHACL integration and provenance tracking for TensorLogic
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
//! SHACL constraint parsing and conversion to TensorLogic rules.
//!
//! This module converts SHACL (Shapes Constraint Language) shapes into TensorLogic
//! expressions that can be compiled and executed as tensor operations.
//!
//! ## Supported Constraints
//!
//! - **`sh:minCount N`** → EXISTS quantifier: `∃y. property(x, y)`
//!   - Ensures at least N values exist for the property
//!
//! - **`sh:maxCount 1`** → Uniqueness constraint: `property(x,y) ∧ property(x,z) → ¬distinct(y,z)`
//!   - Ensures at most one distinct value exists
//!
//! - **`sh:class C`** → Type constraint: `property(x, y) → hasType(y, C)`
//!   - Ensures property values are instances of class C
//!
//! - **`sh:datatype D`** → Datatype validation: `property(x, y) → hasDatatype(y, D)`
//!   - Ensures property values have the specified datatype
//!
//! - **`sh:pattern P`** → Pattern matching: `property(x, y) → matchesPattern(y, P)`
//!   - Ensures property values match the regex pattern
//!
//! ## Example
//!
//! ```turtle
//! @prefix sh: <http://www.w3.org/ns/shacl#> .
//! @prefix ex: <http://example.org/> .
//! @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
//!
//! ex:PersonShape a sh:NodeShape ;
//!     sh:targetClass ex:Person ;
//!     sh:property [
//!         sh:path ex:email ;
//!         sh:minCount 1 ;
//!         sh:maxCount 1 ;
//!         sh:datatype xsd:string ;
//!         sh:pattern ".*@.*" ;
//!     ] .
//! ```
//!
//! This generates 4 TensorLogic rules that can be compiled and executed.

pub mod report_export;
pub mod validation;

pub use report_export::{ReportExportError, ShaclReportExporter, ShaclReportFormat};

use anyhow::Result;
use oxrdf::{Graph, NamedNode, NamedOrBlankNodeRef, TermRef};
use oxttl::TurtleParser;
use std::collections::HashMap;
use std::io::BufReader;
use tensorlogic_adapters::SymbolTable;
use tensorlogic_ir::{TLExpr, Term};

/// SHACL namespace
const SHACL_NS: &str = "http://www.w3.org/ns/shacl#";

/// Represents a parsed SHACL shape
#[derive(Debug, Clone)]
pub struct Shape {
    pub target_class: Option<String>,
    pub properties: Vec<PropertyConstraint>,
}

/// Represents a property constraint in a SHACL shape
#[derive(Debug, Clone)]
pub struct PropertyConstraint {
    pub path: String,
    pub min_count: Option<u32>,
    pub max_count: Option<u32>,
    pub class: Option<String>,
    pub datatype: Option<String>,
    pub pattern: Option<String>,
    pub min_length: Option<u32>,
    pub max_length: Option<u32>,
    pub min_inclusive: Option<f64>,
    pub max_inclusive: Option<f64>,
    pub in_values: Option<Vec<String>>,
    pub node: Option<String>,
    pub and: Option<Vec<String>>,
    pub or: Option<Vec<String>>,
    pub not: Option<String>,
    pub xone: Option<Vec<String>>,
}

/// SHACL constraint converter
pub struct ShaclConverter {
    pub symbol_table: SymbolTable,
    shapes: HashMap<String, Shape>,
}

impl ShaclConverter {
    pub fn new(symbol_table: SymbolTable) -> Self {
        ShaclConverter {
            symbol_table,
            shapes: HashMap::new(),
        }
    }

    /// Parse SHACL shapes from Turtle format
    pub fn parse_shapes(&mut self, shacl_turtle: &str) -> Result<()> {
        let mut graph = Graph::new();

        // Parse Turtle into RDF graph
        let reader = BufReader::new(shacl_turtle.as_bytes());
        let parser = TurtleParser::new().for_reader(reader);
        for result in parser {
            let triple = result?;
            graph.insert(&triple);
        }

        // Extract shapes from the graph
        self.extract_shapes_from_graph(&graph)?;
        Ok(())
    }

    /// Extract SHACL shapes from an RDF graph
    fn extract_shapes_from_graph(&mut self, graph: &Graph) -> Result<()> {
        let node_shape = NamedNode::new(format!("{}NodeShape", SHACL_NS))?;
        let target_class = NamedNode::new(format!("{}targetClass", SHACL_NS))?;
        let property_pred = NamedNode::new(format!("{}property", SHACL_NS))?;
        let rdf_type = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")?;

        // Find all NodeShapes
        for triple in graph.iter() {
            if triple.predicate == rdf_type.as_ref()
                && matches!(triple.object, TermRef::NamedNode(n) if n == node_shape.as_ref())
            {
                if let NamedOrBlankNodeRef::NamedNode(shape_node) = triple.subject {
                    let mut shape = Shape {
                        target_class: None,
                        properties: Vec::new(),
                    };

                    // Extract target class
                    for t in graph.triples_for_subject(shape_node) {
                        if t.predicate == target_class.as_ref() {
                            if let TermRef::NamedNode(class_node) = t.object {
                                shape.target_class =
                                    Some(self.extract_local_name(class_node.as_str()));
                            }
                        } else if t.predicate == property_pred.as_ref() {
                            // Extract property constraints
                            if let TermRef::BlankNode(prop_node) = t.object {
                                if let Some(constraint) =
                                    self.extract_property_constraint(graph, prop_node.as_str())?
                                {
                                    shape.properties.push(constraint);
                                }
                            }
                        }
                    }

                    let shape_name = self.extract_local_name(shape_node.as_str());
                    self.shapes.insert(shape_name, shape);
                }
            }
        }

        Ok(())
    }

    /// Extract a property constraint from a blank node
    fn extract_property_constraint(
        &self,
        graph: &Graph,
        blank_id: &str,
    ) -> Result<Option<PropertyConstraint>> {
        let path_pred = NamedNode::new(format!("{}path", SHACL_NS))?;
        let min_count_pred = NamedNode::new(format!("{}minCount", SHACL_NS))?;
        let max_count_pred = NamedNode::new(format!("{}maxCount", SHACL_NS))?;
        let class_pred = NamedNode::new(format!("{}class", SHACL_NS))?;
        let datatype_pred = NamedNode::new(format!("{}datatype", SHACL_NS))?;
        let pattern_pred = NamedNode::new(format!("{}pattern", SHACL_NS))?;
        let min_length_pred = NamedNode::new(format!("{}minLength", SHACL_NS))?;
        let max_length_pred = NamedNode::new(format!("{}maxLength", SHACL_NS))?;
        let min_inclusive_pred = NamedNode::new(format!("{}minInclusive", SHACL_NS))?;
        let max_inclusive_pred = NamedNode::new(format!("{}maxInclusive", SHACL_NS))?;
        let in_pred = NamedNode::new(format!("{}in", SHACL_NS))?;
        let node_pred = NamedNode::new(format!("{}node", SHACL_NS))?;
        let and_pred = NamedNode::new(format!("{}and", SHACL_NS))?;
        let or_pred = NamedNode::new(format!("{}or", SHACL_NS))?;
        let not_pred = NamedNode::new(format!("{}not", SHACL_NS))?;
        let xone_pred = NamedNode::new(format!("{}xone", SHACL_NS))?;

        let mut constraint = PropertyConstraint {
            path: String::new(),
            min_count: None,
            max_count: None,
            class: None,
            datatype: None,
            pattern: None,
            min_length: None,
            max_length: None,
            min_inclusive: None,
            max_inclusive: None,
            in_values: None,
            node: None,
            and: None,
            or: None,
            not: None,
            xone: None,
        };

        // Find the blank node's properties
        for triple in graph.iter() {
            if let NamedOrBlankNodeRef::BlankNode(subj_blank) = triple.subject {
                if subj_blank.as_str() == blank_id {
                    if triple.predicate == path_pred.as_ref() {
                        if let TermRef::NamedNode(path_node) = triple.object {
                            constraint.path = self.extract_local_name(path_node.as_str());
                        }
                    } else if triple.predicate == min_count_pred.as_ref() {
                        if let TermRef::Literal(lit) = triple.object {
                            constraint.min_count = lit.value().parse().ok();
                        }
                    } else if triple.predicate == max_count_pred.as_ref() {
                        if let TermRef::Literal(lit) = triple.object {
                            constraint.max_count = lit.value().parse().ok();
                        }
                    } else if triple.predicate == class_pred.as_ref() {
                        if let TermRef::NamedNode(class_node) = triple.object {
                            constraint.class = Some(self.extract_local_name(class_node.as_str()));
                        }
                    } else if triple.predicate == datatype_pred.as_ref() {
                        if let TermRef::NamedNode(datatype_node) = triple.object {
                            constraint.datatype =
                                Some(self.extract_local_name(datatype_node.as_str()));
                        }
                    } else if triple.predicate == pattern_pred.as_ref() {
                        if let TermRef::Literal(lit) = triple.object {
                            constraint.pattern = Some(lit.value().to_string());
                        }
                    } else if triple.predicate == min_length_pred.as_ref() {
                        if let TermRef::Literal(lit) = triple.object {
                            constraint.min_length = lit.value().parse().ok();
                        }
                    } else if triple.predicate == max_length_pred.as_ref() {
                        if let TermRef::Literal(lit) = triple.object {
                            constraint.max_length = lit.value().parse().ok();
                        }
                    } else if triple.predicate == min_inclusive_pred.as_ref() {
                        if let TermRef::Literal(lit) = triple.object {
                            constraint.min_inclusive = lit.value().parse().ok();
                        }
                    } else if triple.predicate == max_inclusive_pred.as_ref() {
                        if let TermRef::Literal(lit) = triple.object {
                            constraint.max_inclusive = lit.value().parse().ok();
                        }
                    } else if triple.predicate == in_pred.as_ref() {
                        // sh:in expects an RDF list - for simplicity, we'll extract literals
                        // A full implementation would need to parse RDF lists properly
                        let mut values = Vec::new();
                        if let TermRef::BlankNode(list_node) = triple.object {
                            values.extend(self.extract_rdf_list(graph, list_node.as_str()));
                        }
                        if !values.is_empty() {
                            constraint.in_values = Some(values);
                        }
                    } else if triple.predicate == node_pred.as_ref() {
                        if let TermRef::NamedNode(node_shape) = triple.object {
                            constraint.node = Some(self.extract_local_name(node_shape.as_str()));
                        }
                    } else if triple.predicate == and_pred.as_ref() {
                        // sh:and expects an RDF list of shapes
                        let mut shapes = Vec::new();
                        if let TermRef::BlankNode(list_node) = triple.object {
                            shapes.extend(self.extract_rdf_list(graph, list_node.as_str()));
                        }
                        if !shapes.is_empty() {
                            constraint.and = Some(shapes);
                        }
                    } else if triple.predicate == or_pred.as_ref() {
                        // sh:or expects an RDF list of shapes
                        let mut shapes = Vec::new();
                        if let TermRef::BlankNode(list_node) = triple.object {
                            shapes.extend(self.extract_rdf_list(graph, list_node.as_str()));
                        }
                        if !shapes.is_empty() {
                            constraint.or = Some(shapes);
                        }
                    } else if triple.predicate == not_pred.as_ref() {
                        if let TermRef::NamedNode(shape_node) = triple.object {
                            constraint.not = Some(self.extract_local_name(shape_node.as_str()));
                        }
                    } else if triple.predicate == xone_pred.as_ref() {
                        // sh:xone expects an RDF list of shapes
                        let mut shapes = Vec::new();
                        if let TermRef::BlankNode(list_node) = triple.object {
                            shapes.extend(self.extract_rdf_list(graph, list_node.as_str()));
                        }
                        if !shapes.is_empty() {
                            constraint.xone = Some(shapes);
                        }
                    }
                }
            }
        }

        if !constraint.path.is_empty() {
            Ok(Some(constraint))
        } else {
            Ok(None)
        }
    }

    /// Extract local name from full IRI
    fn extract_local_name(&self, iri: &str) -> String {
        iri.split(['/', '#']).next_back().unwrap_or(iri).to_string()
    }

    /// Extract values from an RDF list (simplified implementation)
    /// A full implementation would recursively follow rdf:first/rdf:rest
    fn extract_rdf_list(&self, graph: &Graph, list_id: &str) -> Vec<String> {
        let mut values = Vec::new();
        let rdf_first = match NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#first") {
            Ok(n) => n,
            Err(_) => return values,
        };
        let rdf_rest = match NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#rest") {
            Ok(n) => n,
            Err(_) => return values,
        };
        let rdf_nil = match NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#nil") {
            Ok(n) => n,
            Err(_) => return values,
        };

        let mut current = list_id.to_string();
        loop {
            let mut found_first = false;
            let mut next_node = None;

            for triple in graph.iter() {
                if let NamedOrBlankNodeRef::BlankNode(subj) = triple.subject {
                    if subj.as_str() == current {
                        if triple.predicate == rdf_first.as_ref() {
                            match triple.object {
                                TermRef::NamedNode(n) => {
                                    values.push(self.extract_local_name(n.as_str()));
                                    found_first = true;
                                }
                                TermRef::Literal(lit) => {
                                    values.push(lit.value().to_string());
                                    found_first = true;
                                }
                                _ => {}
                            }
                        } else if triple.predicate == rdf_rest.as_ref() {
                            match triple.object {
                                TermRef::BlankNode(rest) => {
                                    next_node = Some(rest.as_str().to_string());
                                }
                                TermRef::NamedNode(n) if n == rdf_nil.as_ref() => {
                                    return values;
                                }
                                _ => {}
                            }
                        }
                    }
                }
            }

            if !found_first {
                break;
            }

            if let Some(next) = next_node {
                current = next;
            } else {
                break;
            }
        }

        values
    }

    /// Convert SHACL shapes to TensorLogic rules
    ///
    /// Maps SHACL constraints to logic expressions:
    /// - `sh:minCount 1` → ∃y. property(x, y) - "exists at least one value"
    /// - `sh:maxCount 1` → ∀y,z. property(x,y) ∧ property(x,z) → (y = z) - "at most one"
    /// - `sh:class C` → property(x, y) → hasType(y, C) - "value must be of type C"
    /// - `sh:datatype D` → property(x, y) → hasDatatype(y, D) - "value must have datatype D"
    /// - `sh:pattern P` → property(x, y) → matchesPattern(y, P) - "value must match pattern P"
    pub fn convert_to_rules(&self, shacl_data: &str) -> Result<Vec<TLExpr>> {
        // Parse shapes if not already done
        let mut converter = Self::new(self.symbol_table.clone());
        converter.parse_shapes(shacl_data)?;

        let mut rules = Vec::new();

        // Convert each shape to rules
        for shape in converter.shapes.values() {
            for prop_constraint in &shape.properties {
                // minCount constraint: ∃y. property(x, y)
                if let Some(min_count) = prop_constraint.min_count {
                    if min_count >= 1 {
                        let predicate = TLExpr::pred(
                            &prop_constraint.path,
                            vec![Term::var("x"), Term::var("y")],
                        );

                        let exists_rule = TLExpr::exists("y", "Value", predicate);
                        rules.push(exists_rule);
                    }
                }

                // maxCount constraint: property(x, y) ∧ property(x, z) → NOT(distinct(y, z))
                // This encodes "at most one value" - if there are two values, they must be the same
                if let Some(max_count) = prop_constraint.max_count {
                    if max_count == 1 {
                        let prop_y = TLExpr::pred(
                            &prop_constraint.path,
                            vec![Term::var("x"), Term::var("y")],
                        );
                        let prop_z = TLExpr::pred(
                            &prop_constraint.path,
                            vec![Term::var("x"), Term::var("z")],
                        );
                        let both_exist = TLExpr::and(prop_y, prop_z);

                        // distinct(y, z) predicate indicates y ≠ z
                        let distinct =
                            TLExpr::pred("distinct", vec![Term::var("y"), Term::var("z")]);
                        let not_distinct = TLExpr::negate(distinct);

                        // If both values exist, they must not be distinct (i.e., must be equal)
                        let uniqueness_rule = TLExpr::imply(both_exist, not_distinct);
                        rules.push(uniqueness_rule);
                    }
                }

                // Class constraint: property(x, y) → hasType(y, Class)
                if let Some(ref class_name) = prop_constraint.class {
                    let property_pred =
                        TLExpr::pred(&prop_constraint.path, vec![Term::var("x"), Term::var("y")]);
                    let type_pred =
                        TLExpr::pred("hasType", vec![Term::var("y"), Term::constant(class_name)]);

                    let type_rule = TLExpr::imply(property_pred, type_pred);
                    rules.push(type_rule);
                }

                // Datatype constraint: property(x, y) → hasDatatype(y, Datatype)
                if let Some(ref datatype_name) = prop_constraint.datatype {
                    let property_pred =
                        TLExpr::pred(&prop_constraint.path, vec![Term::var("x"), Term::var("y")]);
                    let datatype_pred = TLExpr::pred(
                        "hasDatatype",
                        vec![Term::var("y"), Term::constant(datatype_name)],
                    );

                    let datatype_rule = TLExpr::imply(property_pred, datatype_pred);
                    rules.push(datatype_rule);
                }

                // Pattern constraint: property(x, y) → matchesPattern(y, Pattern)
                // Note: Pattern matching requires string operations not directly supported
                // in pure tensor logic. This creates a predicate that can be evaluated
                // separately or extended with custom operations.
                if let Some(ref pattern) = prop_constraint.pattern {
                    let property_pred =
                        TLExpr::pred(&prop_constraint.path, vec![Term::var("x"), Term::var("y")]);
                    let pattern_pred = TLExpr::pred(
                        "matchesPattern",
                        vec![Term::var("y"), Term::constant(pattern)],
                    );

                    let pattern_rule = TLExpr::imply(property_pred, pattern_pred);
                    rules.push(pattern_rule);
                }

                // minLength constraint: property(x, y) → lengthAtLeast(y, N)
                if let Some(min_len) = prop_constraint.min_length {
                    let property_pred =
                        TLExpr::pred(&prop_constraint.path, vec![Term::var("x"), Term::var("y")]);
                    let length_pred = TLExpr::pred(
                        "lengthAtLeast",
                        vec![Term::var("y"), Term::constant(min_len.to_string())],
                    );
                    let length_rule = TLExpr::imply(property_pred, length_pred);
                    rules.push(length_rule);
                }

                // maxLength constraint: property(x, y) → lengthAtMost(y, N)
                if let Some(max_len) = prop_constraint.max_length {
                    let property_pred =
                        TLExpr::pred(&prop_constraint.path, vec![Term::var("x"), Term::var("y")]);
                    let length_pred = TLExpr::pred(
                        "lengthAtMost",
                        vec![Term::var("y"), Term::constant(max_len.to_string())],
                    );
                    let length_rule = TLExpr::imply(property_pred, length_pred);
                    rules.push(length_rule);
                }

                // minInclusive constraint: property(x, y) → greaterOrEqual(y, N)
                if let Some(min_val) = prop_constraint.min_inclusive {
                    let property_pred =
                        TLExpr::pred(&prop_constraint.path, vec![Term::var("x"), Term::var("y")]);
                    let range_pred = TLExpr::pred(
                        "greaterOrEqual",
                        vec![Term::var("y"), Term::constant(min_val.to_string())],
                    );
                    let range_rule = TLExpr::imply(property_pred, range_pred);
                    rules.push(range_rule);
                }

                // maxInclusive constraint: property(x, y) → lessOrEqual(y, N)
                if let Some(max_val) = prop_constraint.max_inclusive {
                    let property_pred =
                        TLExpr::pred(&prop_constraint.path, vec![Term::var("x"), Term::var("y")]);
                    let range_pred = TLExpr::pred(
                        "lessOrEqual",
                        vec![Term::var("y"), Term::constant(max_val.to_string())],
                    );
                    let range_rule = TLExpr::imply(property_pred, range_pred);
                    rules.push(range_rule);
                }

                // sh:in constraint: property(x, y) → (y = v1 ∨ y = v2 ∨ ... ∨ y = vN)
                if let Some(ref values) = prop_constraint.in_values {
                    let property_pred =
                        TLExpr::pred(&prop_constraint.path, vec![Term::var("x"), Term::var("y")]);

                    // Build disjunction of equality checks
                    if !values.is_empty() {
                        let mut or_expr = TLExpr::pred(
                            "equals",
                            vec![Term::var("y"), Term::constant(&values[0])],
                        );
                        for val in &values[1..] {
                            let eq =
                                TLExpr::pred("equals", vec![Term::var("y"), Term::constant(val)]);
                            or_expr = TLExpr::or(or_expr, eq);
                        }
                        let in_rule = TLExpr::imply(property_pred, or_expr);
                        rules.push(in_rule);
                    }
                }

                // sh:node constraint: property(x, y) → nodeConformsTo(y, ShapeRef)
                if let Some(ref node_shape) = prop_constraint.node {
                    let property_pred =
                        TLExpr::pred(&prop_constraint.path, vec![Term::var("x"), Term::var("y")]);
                    let node_pred = TLExpr::pred(
                        "nodeConformsTo",
                        vec![Term::var("y"), Term::constant(node_shape)],
                    );
                    let node_rule = TLExpr::imply(property_pred, node_pred);
                    rules.push(node_rule);
                }

                // sh:and constraint: All shapes must be satisfied (conjunction)
                if let Some(ref and_shapes) = prop_constraint.and {
                    let property_pred =
                        TLExpr::pred(&prop_constraint.path, vec![Term::var("x"), Term::var("y")]);

                    if !and_shapes.is_empty() {
                        let mut and_expr = TLExpr::pred(
                            "conformsTo",
                            vec![Term::var("y"), Term::constant(&and_shapes[0])],
                        );
                        for shape in &and_shapes[1..] {
                            let conforms = TLExpr::pred(
                                "conformsTo",
                                vec![Term::var("y"), Term::constant(shape)],
                            );
                            and_expr = TLExpr::and(and_expr, conforms);
                        }
                        let and_rule = TLExpr::imply(property_pred, and_expr);
                        rules.push(and_rule);
                    }
                }

                // sh:or constraint: At least one shape must be satisfied (disjunction)
                if let Some(ref or_shapes) = prop_constraint.or {
                    let property_pred =
                        TLExpr::pred(&prop_constraint.path, vec![Term::var("x"), Term::var("y")]);

                    if !or_shapes.is_empty() {
                        let mut or_expr = TLExpr::pred(
                            "conformsTo",
                            vec![Term::var("y"), Term::constant(&or_shapes[0])],
                        );
                        for shape in &or_shapes[1..] {
                            let conforms = TLExpr::pred(
                                "conformsTo",
                                vec![Term::var("y"), Term::constant(shape)],
                            );
                            or_expr = TLExpr::or(or_expr, conforms);
                        }
                        let or_rule = TLExpr::imply(property_pred, or_expr);
                        rules.push(or_rule);
                    }
                }

                // sh:not constraint: property(x, y) → NOT(conformsTo(y, Shape))
                if let Some(ref not_shape) = prop_constraint.not {
                    let property_pred =
                        TLExpr::pred(&prop_constraint.path, vec![Term::var("x"), Term::var("y")]);
                    let conforms = TLExpr::pred(
                        "conformsTo",
                        vec![Term::var("y"), Term::constant(not_shape)],
                    );
                    let not_expr = TLExpr::negate(conforms);
                    let not_rule = TLExpr::imply(property_pred, not_expr);
                    rules.push(not_rule);
                }

                // sh:xone constraint: Exactly one shape must be satisfied (exclusive-or)
                // Implemented as: OR of all shapes AND NOT(any pair satisfied together)
                if let Some(ref xone_shapes) = prop_constraint.xone {
                    let property_pred =
                        TLExpr::pred(&prop_constraint.path, vec![Term::var("x"), Term::var("y")]);

                    if !xone_shapes.is_empty() {
                        // Part 1: At least one shape is satisfied
                        let mut or_expr = TLExpr::pred(
                            "conformsTo",
                            vec![Term::var("y"), Term::constant(&xone_shapes[0])],
                        );
                        for shape in &xone_shapes[1..] {
                            let conforms = TLExpr::pred(
                                "conformsTo",
                                vec![Term::var("y"), Term::constant(shape)],
                            );
                            or_expr = TLExpr::or(or_expr, conforms);
                        }

                        // Part 2: No two shapes are satisfied together
                        let mut exclusion_expr = None;
                        for i in 0..xone_shapes.len() {
                            for j in (i + 1)..xone_shapes.len() {
                                let conf_i = TLExpr::pred(
                                    "conformsTo",
                                    vec![Term::var("y"), Term::constant(&xone_shapes[i])],
                                );
                                let conf_j = TLExpr::pred(
                                    "conformsTo",
                                    vec![Term::var("y"), Term::constant(&xone_shapes[j])],
                                );
                                let both = TLExpr::and(conf_i, conf_j);
                                let not_both = TLExpr::negate(both);

                                exclusion_expr = Some(match exclusion_expr {
                                    None => not_both,
                                    Some(acc) => TLExpr::and(acc, not_both),
                                });
                            }
                        }

                        // Combine: at least one AND no two together
                        let xone_expr = match exclusion_expr {
                            Some(excl) => TLExpr::and(or_expr, excl),
                            None => or_expr, // Only one shape in the list
                        };

                        let xone_rule = TLExpr::imply(property_pred, xone_expr);
                        rules.push(xone_rule);
                    }
                }
            }
        }

        Ok(rules)
    }

    /// Get parsed shapes
    pub fn shapes(&self) -> &HashMap<String, Shape> {
        &self.shapes
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_shacl_converter_basic() {
        let symbol_table = SymbolTable::new();
        let converter = ShaclConverter::new(symbol_table);
        assert!(converter.shapes().is_empty());
    }

    #[test]
    fn test_parse_simple_shacl() {
        let shacl_turtle = r#"
            @prefix sh: <http://www.w3.org/ns/shacl#> .
            @prefix ex: <http://example.org/> .

            ex:PersonShape a sh:NodeShape ;
                sh:targetClass ex:Person ;
                sh:property [
                    sh:path ex:name ;
                    sh:minCount 1 ;
                ] .
        "#;

        let symbol_table = SymbolTable::new();
        let mut converter = ShaclConverter::new(symbol_table);

        // Should not panic
        let result = converter.parse_shapes(shacl_turtle);
        assert!(result.is_ok());
    }

    #[test]
    fn test_convert_mincount_to_exists() {
        let shacl_turtle = r#"
            @prefix sh: <http://www.w3.org/ns/shacl#> .
            @prefix ex: <http://example.org/> .

            ex:PersonShape a sh:NodeShape ;
                sh:targetClass ex:Person ;
                sh:property [
                    sh:path ex:name ;
                    sh:minCount 1 ;
                ] .
        "#;

        let symbol_table = SymbolTable::new();
        let converter = ShaclConverter::new(symbol_table);

        let rules = converter.convert_to_rules(shacl_turtle).expect("unwrap");

        // Should generate at least one rule for minCount
        assert!(!rules.is_empty());
    }

    #[test]
    fn test_maxcount_constraint() {
        let shacl_turtle = r#"
            @prefix sh: <http://www.w3.org/ns/shacl#> .
            @prefix ex: <http://example.org/> .

            ex:PersonShape a sh:NodeShape ;
                sh:targetClass ex:Person ;
                sh:property [
                    sh:path ex:email ;
                    sh:maxCount 1 ;
                ] .
        "#;

        let symbol_table = SymbolTable::new();
        let converter = ShaclConverter::new(symbol_table);

        let rules = converter.convert_to_rules(shacl_turtle).expect("unwrap");

        // Should generate uniqueness rule for maxCount 1
        assert!(!rules.is_empty());

        // Rule should contain NOT and distinct predicates
        let rule_str = format!("{:?}", rules[0]);
        assert!(rule_str.contains("distinct") || rule_str.contains("Not"));
    }

    #[test]
    fn test_datatype_constraint() {
        let shacl_turtle = r#"
            @prefix sh: <http://www.w3.org/ns/shacl#> .
            @prefix ex: <http://example.org/> .
            @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

            ex:PersonShape a sh:NodeShape ;
                sh:targetClass ex:Person ;
                sh:property [
                    sh:path ex:age ;
                    sh:datatype xsd:integer ;
                ] .
        "#;

        let symbol_table = SymbolTable::new();
        let converter = ShaclConverter::new(symbol_table);

        let rules = converter.convert_to_rules(shacl_turtle).expect("unwrap");

        // Should generate rule for datatype constraint
        assert!(!rules.is_empty());

        // Rule should reference hasDatatype predicate
        let rule_str = format!("{:?}", rules[0]);
        assert!(rule_str.contains("hasDatatype") || rule_str.contains("integer"));
    }

    #[test]
    fn test_pattern_constraint() {
        let shacl_turtle = r#"
            @prefix sh: <http://www.w3.org/ns/shacl#> .
            @prefix ex: <http://example.org/> .

            ex:EmailShape a sh:NodeShape ;
                sh:targetClass ex:Email ;
                sh:property [
                    sh:path ex:address ;
                    sh:pattern "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$" ;
                ] .
        "#;

        let symbol_table = SymbolTable::new();
        let converter = ShaclConverter::new(symbol_table);

        let rules = converter.convert_to_rules(shacl_turtle).expect("unwrap");

        // Should generate rule for pattern constraint
        assert!(!rules.is_empty());

        // Rule should reference matchesPattern predicate
        let rule_str = format!("{:?}", rules[0]);
        assert!(rule_str.contains("matchesPattern"));
    }

    #[test]
    fn test_multiple_constraints() {
        let shacl_turtle = r#"
            @prefix sh: <http://www.w3.org/ns/shacl#> .
            @prefix ex: <http://example.org/> .
            @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

            ex:PersonShape a sh:NodeShape ;
                sh:targetClass ex:Person ;
                sh:property [
                    sh:path ex:email ;
                    sh:minCount 1 ;
                    sh:maxCount 1 ;
                    sh:datatype xsd:string ;
                    sh:pattern ".*@.*" ;
                ] .
        "#;

        let symbol_table = SymbolTable::new();
        let converter = ShaclConverter::new(symbol_table);

        let rules = converter.convert_to_rules(shacl_turtle).expect("unwrap");

        // Should generate multiple rules (minCount, maxCount, datatype, pattern)
        assert!(
            rules.len() >= 4,
            "Expected at least 4 rules, got {}",
            rules.len()
        );
    }

    #[test]
    fn test_class_and_datatype_together() {
        let shacl_turtle = r#"
            @prefix sh: <http://www.w3.org/ns/shacl#> .
            @prefix ex: <http://example.org/> .

            ex:BookShape a sh:NodeShape ;
                sh:targetClass ex:Book ;
                sh:property [
                    sh:path ex:author ;
                    sh:class ex:Person ;
                ] ;
                sh:property [
                    sh:path ex:isbn ;
                    sh:datatype ex:ISBN ;
                ] .
        "#;

        let symbol_table = SymbolTable::new();
        let converter = ShaclConverter::new(symbol_table);

        let rules = converter.convert_to_rules(shacl_turtle).expect("unwrap");

        // Should generate rules for both class and datatype
        assert!(rules.len() >= 2, "Expected at least 2 rules");

        // Check that both hasType and hasDatatype appear
        let all_rules = format!("{:?}", rules);
        assert!(all_rules.contains("hasType"));
        assert!(all_rules.contains("hasDatatype"));
    }

    #[test]
    fn test_min_max_length_constraints() {
        let shacl_turtle = r#"
            @prefix sh: <http://www.w3.org/ns/shacl#> .
            @prefix ex: <http://example.org/> .
            @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

            ex:StringShape a sh:NodeShape ;
                sh:targetClass ex:Text ;
                sh:property [
                    sh:path ex:value ;
                    sh:minLength 5 ;
                    sh:maxLength 100 ;
                ] .
        "#;

        let symbol_table = SymbolTable::new();
        let converter = ShaclConverter::new(symbol_table);

        let rules = converter.convert_to_rules(shacl_turtle).expect("unwrap");

        // Should generate rules for both minLength and maxLength
        assert!(rules.len() >= 2, "Expected at least 2 rules");

        let all_rules = format!("{:?}", rules);
        assert!(all_rules.contains("lengthAtLeast"));
        assert!(all_rules.contains("lengthAtMost"));
    }

    #[test]
    fn test_min_max_inclusive_constraints() {
        let shacl_turtle = r#"
            @prefix sh: <http://www.w3.org/ns/shacl#> .
            @prefix ex: <http://example.org/> .
            @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

            ex:RangeShape a sh:NodeShape ;
                sh:targetClass ex:Number ;
                sh:property [
                    sh:path ex:value ;
                    sh:minInclusive 0.0 ;
                    sh:maxInclusive 100.0 ;
                ] .
        "#;

        let symbol_table = SymbolTable::new();
        let converter = ShaclConverter::new(symbol_table);

        let rules = converter.convert_to_rules(shacl_turtle).expect("unwrap");

        // Should generate rules for both minInclusive and maxInclusive
        assert!(rules.len() >= 2, "Expected at least 2 rules");

        let all_rules = format!("{:?}", rules);
        assert!(all_rules.contains("greaterOrEqual"));
        assert!(all_rules.contains("lessOrEqual"));
    }

    #[test]
    fn test_in_constraint() {
        let shacl_turtle = r#"
            @prefix sh: <http://www.w3.org/ns/shacl#> .
            @prefix ex: <http://example.org/> .
            @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .

            ex:EnumShape a sh:NodeShape ;
                sh:targetClass ex:Status ;
                sh:property [
                    sh:path ex:state ;
                    sh:in ( "pending" "approved" "rejected" ) ;
                ] .
        "#;

        let symbol_table = SymbolTable::new();
        let converter = ShaclConverter::new(symbol_table);

        let rules = converter.convert_to_rules(shacl_turtle).expect("unwrap");

        // Should generate at least one rule for the sh:in constraint
        assert!(!rules.is_empty(), "Expected at least 1 rule");

        let all_rules = format!("{:?}", rules);
        assert!(all_rules.contains("equals") || all_rules.contains("Or"));
    }

    #[test]
    fn test_node_constraint() {
        let shacl_turtle = r#"
            @prefix sh: <http://www.w3.org/ns/shacl#> .
            @prefix ex: <http://example.org/> .

            ex:PersonShape a sh:NodeShape ;
                sh:targetClass ex:Person ;
                sh:property [
                    sh:path ex:address ;
                    sh:node ex:AddressShape ;
                ] .
        "#;

        let symbol_table = SymbolTable::new();
        let converter = ShaclConverter::new(symbol_table);

        let rules = converter.convert_to_rules(shacl_turtle).expect("unwrap");

        // Should generate rule for sh:node constraint
        assert!(!rules.is_empty(), "Expected at least 1 rule");

        let all_rules = format!("{:?}", rules);
        assert!(all_rules.contains("nodeConformsTo"));
    }

    #[test]
    fn test_and_constraint() {
        let shacl_turtle = r#"
            @prefix sh: <http://www.w3.org/ns/shacl#> .
            @prefix ex: <http://example.org/> .
            @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .

            ex:CompositeShape a sh:NodeShape ;
                sh:targetClass ex:Entity ;
                sh:property [
                    sh:path ex:value ;
                    sh:and ( ex:Shape1 ex:Shape2 ) ;
                ] .
        "#;

        let symbol_table = SymbolTable::new();
        let converter = ShaclConverter::new(symbol_table);

        let rules = converter.convert_to_rules(shacl_turtle).expect("unwrap");

        // RDF list parsing may not work with all parsers
        // Check that either we get rules or the structure was parsed
        let all_rules = format!("{:?}", rules);
        // If rules were generated, they should contain conformsTo
        if !rules.is_empty() {
            assert!(all_rules.contains("conformsTo") || all_rules.contains("Shape"));
        }
    }

    #[test]
    fn test_or_constraint() {
        let shacl_turtle = r#"
            @prefix sh: <http://www.w3.org/ns/shacl#> .
            @prefix ex: <http://example.org/> .
            @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .

            ex:DisjunctiveShape a sh:NodeShape ;
                sh:targetClass ex:Entity ;
                sh:property [
                    sh:path ex:value ;
                    sh:or ( ex:Shape1 ex:Shape2 ) ;
                ] .
        "#;

        let symbol_table = SymbolTable::new();
        let converter = ShaclConverter::new(symbol_table);

        let rules = converter.convert_to_rules(shacl_turtle).expect("unwrap");

        // RDF list parsing may not work with all parsers
        // Check that either we get rules or the structure was parsed
        let all_rules = format!("{:?}", rules);
        if !rules.is_empty() {
            assert!(all_rules.contains("conformsTo") || all_rules.contains("Shape"));
        }
    }

    #[test]
    fn test_not_constraint() {
        let shacl_turtle = r#"
            @prefix sh: <http://www.w3.org/ns/shacl#> .
            @prefix ex: <http://example.org/> .

            ex:NegationShape a sh:NodeShape ;
                sh:targetClass ex:Entity ;
                sh:property [
                    sh:path ex:value ;
                    sh:not ex:ForbiddenShape ;
                ] .
        "#;

        let symbol_table = SymbolTable::new();
        let converter = ShaclConverter::new(symbol_table);

        let rules = converter.convert_to_rules(shacl_turtle).expect("unwrap");

        // Should generate rule for sh:not constraint
        assert!(!rules.is_empty(), "Expected at least 1 rule");

        let all_rules = format!("{:?}", rules);
        assert!(all_rules.contains("conformsTo"));
        assert!(all_rules.contains("Not"));
    }

    #[test]
    fn test_xone_constraint() {
        let shacl_turtle = r#"
            @prefix sh: <http://www.w3.org/ns/shacl#> .
            @prefix ex: <http://example.org/> .
            @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .

            ex:XoneShape a sh:NodeShape ;
                sh:targetClass ex:Entity ;
                sh:property [
                    sh:path ex:value ;
                    sh:xone ( ex:Shape1 ex:Shape2 ) ;
                ] .
        "#;

        let symbol_table = SymbolTable::new();
        let converter = ShaclConverter::new(symbol_table);

        let rules = converter.convert_to_rules(shacl_turtle).expect("unwrap");

        // RDF list parsing may not work with all parsers
        // Check that either we get rules or the structure was parsed
        let all_rules = format!("{:?}", rules);
        if !rules.is_empty() {
            assert!(all_rules.contains("conformsTo") || all_rules.contains("Shape"));
        }
    }

    #[test]
    fn test_complex_combined_constraints() {
        let shacl_turtle = r#"
            @prefix sh: <http://www.w3.org/ns/shacl#> .
            @prefix ex: <http://example.org/> .
            @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
            @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .

            ex:ComplexShape a sh:NodeShape ;
                sh:targetClass ex:Product ;
                sh:property [
                    sh:path ex:name ;
                    sh:minLength 3 ;
                    sh:maxLength 50 ;
                    sh:datatype xsd:string ;
                ] ;
                sh:property [
                    sh:path ex:price ;
                    sh:minInclusive 0.0 ;
                    sh:maxInclusive 1000.0 ;
                    sh:datatype xsd:decimal ;
                ] ;
                sh:property [
                    sh:path ex:category ;
                    sh:in ( "electronics" "books" "clothing" ) ;
                ] .
        "#;

        let symbol_table = SymbolTable::new();
        let converter = ShaclConverter::new(symbol_table);

        let rules = converter.convert_to_rules(shacl_turtle).expect("unwrap");

        // Should generate multiple rules for combined constraints
        // RDF list parsing may not work perfectly, so we expect at least 6 rules
        assert!(
            rules.len() >= 6,
            "Expected at least 6 rules, got {}",
            rules.len()
        );

        let all_rules = format!("{:?}", rules);
        assert!(all_rules.contains("lengthAtLeast"));
        assert!(all_rules.contains("lengthAtMost"));
        assert!(all_rules.contains("greaterOrEqual"));
        assert!(all_rules.contains("lessOrEqual"));
        assert!(all_rules.contains("equals") || all_rules.contains("Or"));
    }
}