-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathreader.rs
More file actions
3317 lines (3028 loc) · 124 KB
/
Copy pathreader.rs
File metadata and controls
3317 lines (3028 loc) · 124 KB
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
use Term::*;
use oxrdf::{BlankNode, NamedNode, NamedOrBlankNode, Triple};
use crate::{error::HornedError, io::ParserConfiguration, vocab::Facet};
use crate::{model::Literal, ontology::component_mapped::ComponentMappedOntology};
use crate::{model::*, vocab::Vocab};
use crate::ontology::indexed::ForIndex;
use crate::vocab::OWL as VOWL;
use crate::vocab::OWL2Datatype;
use crate::vocab::RDF as VRDF;
use crate::vocab::SWRL as VSWRL;
use crate::vocab::is_annotation_builtin;
use crate::{
ontology::{
declaration_mapped::DeclarationMappedIndex,
indexed::ThreeIndexedOntology,
logically_equal::{LogicallyEqualIndex, update_or_insert_logically_equal_component},
set::{SetIndex, SetIndexIter, SetOntology},
},
resolve::strict_resolve_iri,
vocab::RDFS as VRDFS,
};
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt::Debug;
use std::io::Cursor;
use std::{io::BufRead, marker::PhantomData};
type OxTerm<'a> = ::oxrdf::Term;
/// Evaluate $body which should return a value while allowing the use
/// of the ? operator within body.
///
/// This is useful for unpacking multiple Option return values. The
/// first that unpacks to return makes the whole body return None.
macro_rules! ok_some {
($body:expr) => {
(if let Some(retn) = (|| Some($body))() {
Ok(Some(retn))
} else {
Ok(None)
})
};
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, Ord, PartialOrd)]
pub struct BNode<A: ForIRI>(A);
// The order of the variants in the enum is crucial for round-tripping.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum Term<A: ForIRI> {
OWL(VOWL),
RDF(VRDF),
RDFS(VRDFS),
SWRL(VSWRL),
FacetTerm(Facet),
Iri(IRI<A>),
BNode(BNode<A>),
Literal(Literal<A>),
}
impl<A: ForIRI> From<&VOWL> for Term<A> {
fn from(value: &VOWL) -> Self {
Self::OWL(value.clone())
}
}
impl<A: ForIRI> From<&VRDF> for Term<A> {
fn from(value: &VRDF) -> Self {
Self::RDF(value.clone())
}
}
impl<A: ForIRI> From<&VRDFS> for Term<A> {
fn from(value: &VRDFS) -> Self {
Self::RDFS(value.clone())
}
}
impl<A: ForIRI> From<&VSWRL> for Term<A> {
fn from(value: &VSWRL) -> Self {
Self::SWRL(value.clone())
}
}
impl<A: ForIRI> From<&Facet> for Term<A> {
fn from(value: &Facet) -> Self {
Self::FacetTerm(value.clone())
}
}
impl<A: ForIRI> From<IRI<A>> for Term<A> {
fn from(value: IRI<A>) -> Self {
Self::Iri(value)
}
}
impl<A: ForIRI> From<BNode<A>> for Term<A> {
fn from(value: BNode<A>) -> Self {
Self::BNode(value)
}
}
impl<A: ForIRI> From<Literal<A>> for Term<A> {
fn from(value: Literal<A>) -> Self {
Self::Literal(value)
}
}
impl<A: ForIRI> TryFrom<&crate::vocab::Vocab> for Term<A> {
type Error = HornedError;
fn try_from(value: &crate::vocab::Vocab) -> Result<Self, Self::Error> {
match value {
crate::vocab::Vocab::Facet(facet) => Ok(facet.into()),
crate::vocab::Vocab::RDF(rdf) => Ok(rdf.into()),
crate::vocab::Vocab::RDFS(rdfs) => Ok(rdfs.into()),
crate::vocab::Vocab::OWL(owl) => Ok(owl.into()),
crate::vocab::Vocab::SWRL(swrl) => Ok(swrl.into()),
_ => Err(HornedError::invalid(value.to_string())),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[allow(dead_code)]
enum OrTerm<A: ForIRI> {
Term(Term<A>),
ClassExpression(ClassExpression<A>),
}
impl<A: ForIRI> From<ClassExpression<A>> for OrTerm<A> {
fn from(c: ClassExpression<A>) -> OrTerm<A> {
OrTerm::ClassExpression(c)
}
}
impl<A: ForIRI> From<Term<A>> for OrTerm<A> {
fn from(t: Term<A>) -> OrTerm<A> {
OrTerm::Term(t)
}
}
impl<A: ForIRI> Term<A> {
fn substitute(self) -> Term<A> {
if let Term::Iri(ref iri) = self
&& let Some(vocab) = Vocab::lookup(iri)
{
return match vocab {
crate::vocab::Vocab::Facet(facet) => facet.into(),
crate::vocab::Vocab::RDF(rdf) => rdf.into(),
crate::vocab::Vocab::RDFS(rdfs) => rdfs.into(),
crate::vocab::Vocab::OWL(owl) => owl.into(),
crate::vocab::Vocab::SWRL(swrl) => swrl.into(),
_ => self,
};
}
self
}
}
impl<A: ForIRI> TryFrom<&NamedNode> for Term<A> {
type Error = HornedError;
fn try_from(value: &NamedNode) -> Result<Self, Self::Error> {
if let Some(res) = Vocab::lookup(value.as_str()) {
Term::try_from(res)
} else {
Err(HornedError::invalid(value.as_str()))
}
}
}
impl TryFrom<&NamedNode> for crate::vocab::XSD {
type Error = HornedError;
fn try_from(value: &NamedNode) -> Result<Self, Self::Error> {
value.as_str().parse::<Self>()
}
}
impl<A: ForIRI> Build<A> {
fn to_term_bn(nn: &BlankNode) -> Term<A> {
Term::BNode(BNode(nn.clone().into_string().into()))
}
fn convert_to_pos_triple(&self, rio_triple: Triple, pos: u64) -> PosTriple<A> {
PosTriple(
[
self.to_term_bnn(&rio_triple.subject),
self.to_term_nn(&rio_triple.predicate),
self.to_term(&rio_triple.object),
],
pos,
)
}
fn substitute_term(&self, term: [Term<A>; 3]) -> [Term<A>; 3] {
let [subject, predicate, object] = term;
let predicate = predicate.substitute();
let object = if matches!(predicate, Term::RDF(VRDF::Type)) {
object.substitute()
} else {
object
};
[subject, predicate, object]
}
fn substitute_triple(&self, triple: PosTriple<A>) -> PosTriple<A> {
let PosTriple(term, pos) = triple;
let term = self.substitute_term(term);
PosTriple(term, pos)
}
fn convert_substitute_triple(&self, rio_triple: Triple, pos: u64) -> PosTriple<A> {
self.substitute_triple(self.convert_to_pos_triple(rio_triple, pos))
}
fn to_term(&self, t: &OxTerm) -> Term<A> {
match t {
oxrdf::Term::NamedNode(iri) => self.to_term_nn(iri),
oxrdf::Term::BlankNode(id) => Self::to_term_bn(id),
oxrdf::Term::Literal(l) => self.to_term_lt(l),
}
}
fn to_term_bnn(&self, subj: &NamedOrBlankNode) -> Term<A> {
match subj {
NamedOrBlankNode::NamedNode(nn) => self.to_term_nn(nn),
NamedOrBlankNode::BlankNode(bn) => Self::to_term_bn(bn),
}
}
fn to_term_nn(&self, nn: &NamedNode) -> Term<A> {
Term::Iri(self.iri(nn.as_str()))
}
fn to_term_lt(&self, lt: &oxrdf::Literal) -> Term<A> {
if let Some(lang) = lt.language() {
return Term::Literal(Literal::Language {
literal: lt.value().to_string(),
lang: lang.to_string(),
});
}
if lt.datatype().as_str() == "http://www.w3.org/2001/XMLSchema#string" {
return Term::Literal(Literal::Simple {
literal: lt.value().to_string(),
});
}
Term::Literal(Literal::Datatype {
literal: lt.value().to_string(),
datatype_iri: self.iri(lt.datatype().as_str()),
})
}
}
macro_rules! d {
() => {
Default::default()
};
}
/// The RDFOntology supports logical equality and IRI->type mapping
/// which are the two speeds ups that we need for RDF parsing.
pub trait RDFOntology<A: ForIRI, AA: ForIndex<A>>:
AsRef<LogicallyEqualIndex<A, AA>>
+ AsRef<DeclarationMappedIndex<A, AA>>
+ AsRef<SetIndex<A, AA>>
+ Default
+ Debug
+ MutableOntology<A>
{
}
impl<A: ForIRI, AA: ForIndex<A>, T> RDFOntology<A, AA> for T where
T: AsRef<LogicallyEqualIndex<A, AA>>
+ AsRef<DeclarationMappedIndex<A, AA>>
+ AsRef<SetIndex<A, AA>>
+ Default
+ Debug
+ MutableOntology<A>
{
}
#[derive(Debug)]
#[allow(clippy::type_complexity)]
pub struct ConcreteRDFOntology<A: ForIRI, AA: ForIndex<A>>(
ThreeIndexedOntology<
A,
AA,
SetIndex<A, AA>,
DeclarationMappedIndex<A, AA>,
LogicallyEqualIndex<A, AA>,
>,
);
impl<A: ForIRI, AA: ForIndex<A>> Default for ConcreteRDFOntology<A, AA> {
fn default() -> Self {
Self(Default::default())
}
}
pub type ConcreteRcRDFOntology = ConcreteRDFOntology<RcStr, RcAnnotatedComponent>;
impl<A: ForIRI, AA: ForIndex<A>> ConcreteRDFOntology<A, AA> {
pub fn i(&self) -> &SetIndex<A, AA> {
self.0.i()
}
pub fn j(&self) -> &DeclarationMappedIndex<A, AA> {
self.0.j()
}
pub fn k(&self) -> &LogicallyEqualIndex<A, AA> {
self.0.k()
}
pub fn index(
self,
) -> (
SetIndex<A, AA>,
DeclarationMappedIndex<A, AA>,
LogicallyEqualIndex<A, AA>,
) {
self.0.index()
}
}
impl<A: ForIRI, AA: ForIndex<A>> Ontology<A> for ConcreteRDFOntology<A, AA> {
type ComponentIter<'c>
= SetIndexIter<'c, A, AA>
where
Self: 'c,
A: 'c;
fn iter(&self) -> Self::ComponentIter<'_> {
self.i().into_iter()
}
}
impl<A: ForIRI, AA: ForIndex<A>> IntoIterator for ConcreteRDFOntology<A, AA> {
type Item = AnnotatedComponent<A>;
type IntoIter = <SetIndex<A, AA> as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
let (i, _, _) = self.index();
i.into_iter()
}
}
impl<A: ForIRI, AA: ForIndex<A>> MutableOntology<A> for ConcreteRDFOntology<A, AA> {
fn insert<IAA>(&mut self, cmp: IAA) -> bool
where
IAA: Into<AnnotatedComponent<A>>,
{
self.0.insert(cmp)
}
fn take(&mut self, cmp: &AnnotatedComponent<A>) -> Option<AnnotatedComponent<A>> {
self.0.take(cmp)
}
}
impl<A: ForIRI, AA: ForIndex<A>> From<ConcreteRDFOntology<A, AA>> for SetOntology<A> {
fn from(rdfo: ConcreteRDFOntology<A, AA>) -> SetOntology<A> {
rdfo.index().0.into()
}
}
impl<A: ForIRI, AA: ForIndex<A>> From<ConcreteRDFOntology<A, AA>>
for ComponentMappedOntology<A, AA>
{
fn from(rdfo: ConcreteRDFOntology<A, AA>) -> ComponentMappedOntology<A, AA> {
let so: SetOntology<_> = rdfo.into();
so.into()
}
}
impl<A: ForIRI, AA: ForIndex<A>> AsRef<DeclarationMappedIndex<A, AA>>
for ConcreteRDFOntology<A, AA>
{
fn as_ref(&self) -> &DeclarationMappedIndex<A, AA> {
self.j()
}
}
impl<A: ForIRI, AA: ForIndex<A>> AsRef<LogicallyEqualIndex<A, AA>> for ConcreteRDFOntology<A, AA> {
fn as_ref(&self) -> &LogicallyEqualIndex<A, AA> {
self.k()
}
}
impl<A: ForIRI, AA: ForIndex<A>> AsRef<SetIndex<A, AA>> for ConcreteRDFOntology<A, AA> {
fn as_ref(&self) -> &SetIndex<A, AA> {
self.i()
}
}
#[derive(Debug)]
enum OntologyParserState {
New,
Imports,
Declarations,
Parse,
}
/// Represents all the parts of a set of RDF triples that were not
/// able to be completed parsed to OWL2 structures.
#[derive(Debug, Default)]
pub struct IncompleteParse<A: ForIRI> {
/// Simple Triples are those were subject, object and predicate
/// are all IRIs
pub simple: Vec<PosTriple<A>>,
/// BNode triples are those that start with a BNode, except where
/// they are part of an RDF sequence.
pub bnode: Vec<VPosTriple<A>>,
/// BNode seq are those triples that are part of a sequence.
pub bnode_seq: Vec<Vec<Term<A>>>,
/// ClassExpression's that are otherwise unconnected to
/// other parts of the Ontology.
pub class_expression: Vec<ClassExpression<A>>,
/// ObjectPropertyExpression' that are otherwise unconnected to
/// other parts of the Ontology.
pub object_property_expression: Vec<ObjectPropertyExpression<A>>,
/// DataRange's that are otherwise unconnected to other parts of the
/// Ontology.
pub data_range: Vec<DataRange<A>>,
/// Atom's that are otherwise unconnected to other parts of the
/// Ontology.
pub atom: HashMap<Term<A>, Atom<A>>,
/// Annotations that are otherwise unconnected to other parts of
/// the Ontology
pub ann_map: HashMap<[Term<A>; 3], BTreeSet<Annotation<A>>>,
}
impl<A: ForIRI> IncompleteParse<A> {
pub fn is_complete(&self) -> bool {
self.simple.is_empty()
&& self.bnode.is_empty()
&& self.bnode_seq.is_empty()
&& self.class_expression.is_empty()
&& self.object_property_expression.is_empty()
&& self.data_range.is_empty()
&& self.ann_map.is_empty()
&& self.atom.is_empty()
}
}
/// A triple of terms with a position from the file from which the
/// triple was read.
#[derive(Clone, Debug)]
pub struct PosTriple<A: ForIRI>([Term<A>; 3], u64);
impl<A: ForIRI> From<[Term<A>; 3]> for PosTriple<A> {
fn from(t: [Term<A>; 3]) -> PosTriple<A> {
PosTriple(t, 0)
}
}
impl<A: ForIRI> PosTriple<A> {
pub fn triple(&self) -> &[Term<A>; 3] {
&self.0
}
pub fn as_triple(self) -> [Term<A>; 3] {
self.0
}
pub fn triple_mut(&mut self) -> &mut [Term<A>; 3] {
&mut self.0
}
pub fn position(&self) -> u64 {
self.1
}
}
/// A set of triples with a position in the file from which the
/// triples were loaded.
#[derive(Debug)]
pub struct VPosTriple<A: ForIRI>(Vec<[Term<A>; 3]>, u64);
impl<A: ForIRI> IntoIterator for VPosTriple<A> {
type Item = [Term<A>; 3];
type IntoIter = std::vec::IntoIter<[Term<A>; 3]>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl<A: ForIRI> std::ops::Deref for VPosTriple<A> {
type Target = Vec<[Term<A>; 3]>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<A: ForIRI> std::ops::DerefMut for VPosTriple<A> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<A: ForIRI> VPosTriple<A> {
pub fn vec_triple(&self) -> &Vec<[Term<A>; 3]> {
&self.0
}
pub fn as_triple(self) -> Vec<[Term<A>; 3]> {
self.0
}
pub fn triple_mut(&mut self) -> &mut Vec<[Term<A>; 3]> {
&mut self.0
}
pub fn position(&self) -> u64 {
self.1
}
}
/// An ontology parser which takes a set of RDF triples and turns them
/// into an RDFOntology.
#[derive(Debug)]
pub struct OntologyParser<'a, A: ForIRI, AA: ForIndex<A>, O: RDFOntology<A, AA>> {
/// The ontology being populated
o: O,
b: &'a Build<A>,
config: ParserConfiguration,
// A vector of the triples from which we are parsing
triple: Vec<PosTriple<A>>,
// Triples with an IRI for subject, predicate and object
simple: Vec<PosTriple<A>>,
// Triples that start with a BNode
bnode: HashMap<BNode<A>, VPosTriple<A>>,
// The object of triples that are part of a sequence, keyed on the
// bnode subject of the first known triple that is part of that sequence
bnode_seq: HashMap<BNode<A>, Vec<Term<A>>>,
// Parsed OWL Objects keyed on their bnode
class_expression: HashMap<BNode<A>, ClassExpression<A>>,
object_property_expression: HashMap<BNode<A>, ObjectPropertyExpression<A>>,
data_range: HashMap<BNode<A>, DataRange<A>>,
// Bnodes from the three maps above that have been retrieved at least
// once. Entries there are looked up, not removed, because the same
// bnode can legitimately be referenced from more than one place (e.g.
// a restriction shared by two rdf:List members) -- see #254.
used_bnode: HashSet<BNode<A>>,
// Annotations mapped to Triples
ann_map: HashMap<[Term<A>; 3], BTreeSet<Annotation<A>>>,
atom: HashMap<Term<A>, Atom<A>>,
variable: HashMap<IRI<A>, Variable<A>>,
// How far through the parse have we got?
state: OntologyParserState,
// AA is otherwise unreferenced
p: PhantomData<AA>,
}
impl<'a, A: ForIRI, AA: ForIndex<A>, O: RDFOntology<A, AA>> OntologyParser<'a, A, AA, O> {
/// Return a new empty OntologyParser.
pub fn new(
b: &'a Build<A>,
triple: Vec<PosTriple<A>>,
config: ParserConfiguration,
) -> OntologyParser<'a, A, AA, O> {
OntologyParser {
o: d!(),
b,
config,
triple,
simple: d!(),
bnode: d!(),
bnode_seq: d!(),
class_expression: d!(),
object_property_expression: d!(),
data_range: d!(),
used_bnode: d!(),
ann_map: d!(),
atom: d!(),
variable: d!(),
state: OntologyParserState::New,
p: d!(),
}
}
/// Return a new OntologyParser taking all triples from an BufRead
/// in RDF-XML.
pub fn from_bufread<'b, R: BufRead>(
b: &'a Build<A>,
bufread: &'b mut R,
config: ParserConfiguration,
) -> Result<OntologyParser<'a, A, AA, O>, HornedError> {
let format = config.rdf.format.unwrap_or(oxrdfio::RdfFormat::RdfXml);
Self::from_bufread_with_format(b, bufread, config, format)
}
pub fn from_bufread_with_format<'b, R: BufRead>(
b: &'a Build<A>,
bufread: &'b mut R,
config: ParserConfiguration,
format: oxrdfio::RdfFormat,
) -> Result<OntologyParser<'a, A, AA, O>, HornedError> {
let parser = oxrdfio::RdfParser::from_format(format);
let mut triples = vec![];
let last_pos = std::cell::Cell::new(0);
for ox_quad in parser.for_reader(bufread) {
let ox_triple = ox_quad
.map_err(|e| {
HornedError::ParserError(Box::new(e), crate::error::Location::Unknown)
})?
.into();
triples.push(b.convert_substitute_triple(ox_triple, last_pos.get()));
//last_pos.set(parser.buffer_position().try_into().unwrap());
}
Ok(OntologyParser::new(b, triples, config))
}
/// Return an new OntologyParser taking all triples in RDF-XML from the given IRI.
pub fn from_doc_iri(
b: &'a Build<A>,
iri: &IRI<A>,
config: ParserConfiguration,
) -> Result<OntologyParser<'a, A, AA, O>, HornedError> {
OntologyParser::from_bufread(
b,
&mut Cursor::new(strict_resolve_iri(
iri,
config.remote_body_limit,
config.local_only,
)?),
config,
)
}
/// Groups `triples` into `simple` (those which do not start with a BNode) and those that do.
fn group_triples(
triples: Vec<PosTriple<A>>,
simple: &mut Vec<PosTriple<A>>,
bnode: &mut HashMap<BNode<A>, VPosTriple<A>>,
) {
// Next group together triples on a BNode, so we have
// HashMap<BNodeID, Vec<[SpTerm; 3]> All of which should be
// triples should begin with the BNodeId. We should be able to
// gather these in a single pass.
for t in triples {
match t.triple() {
// These triples define axioms and are pattern matched
// along with the simple triples. This makes much of
// my documentation slightly wrong.
[_, Term::OWL(VOWL::DisjointWith), _]
| [_, Term::OWL(VOWL::EquivalentClass), _]
| [_, Term::OWL(VOWL::InverseOf), _]
| [_, Term::RDFS(VRDFS::SubClassOf), _] => {
simple.push(t);
}
[Term::BNode(id), _, _] => {
// Are there any triples on this bnode already
let v = bnode
.entry(id.clone())
// if there are not store the location of this as it is the first
.or_insert_with(|| VPosTriple(vec![], t.1));
v.push(t.as_triple())
}
_ => {
simple.push(t);
}
}
}
}
/// Find and group all triples on a sequence.
fn stitch_seqs_1(&mut self) {
let mut extended = false;
for (k, v) in std::mem::take(&mut self.bnode) {
match v.as_slice() {
[
[_, Term::RDF(VRDF::First), val],
[_, Term::RDF(VRDF::Rest), Term::BNode(bnode_id)],
// Some sequences have a Type List, some do not,
// so do not use this as part of the lookup
..,
] => {
// Only put sequence triples on bnode_seq if they
// are next in line for a sequence already on
// there, so we grow from the end backward.
let some_seq = self.bnode_seq.remove(bnode_id);
if let Some(mut seq) = some_seq {
seq.push(val.clone());
self.bnode_seq.insert(k.clone(), seq);
extended = true;
} else {
self.bnode.insert(k, v);
}
}
_ => {
self.bnode.insert(k, v);
}
};
}
if extended && !self.bnode.is_empty() {
self.stitch_seqs_1()
}
}
/// Find and group all triples on a sequence.
fn stitch_seqs(&mut self) {
for (k, v) in std::mem::take(&mut self.bnode) {
match v.as_slice() {
// Find the end of the list
[
[_, Term::RDF(VRDF::First), val],
[_, Term::RDF(VRDF::Rest), Term::Iri(iri)],
// Lists may or may not have a "list" RDF type
..,
] if **iri == **VRDF::Nil => {
self.bnode_seq.insert(k.clone(), vec![val.clone()]);
}
_ => {
self.bnode.insert(k, v);
}
};
}
self.stitch_seqs_1();
for v in self.bnode_seq.values_mut() {
v.reverse();
}
}
/// Process all import statements
fn resolve_imports(&mut self) -> Vec<IRI<A>> {
let mut v = vec![];
for t in std::mem::take(&mut self.simple) {
match t.0 {
[Term::Iri(_), Term::OWL(VOWL::Imports), Term::Iri(imp)] => {
v.push(imp.clone());
self.merge(AnnotatedComponent {
component: Import(imp).into(),
ann: BTreeSet::new(),
});
}
_ => self.simple.push(t),
}
}
v
// Section 3.1.2/table 4 of RDF Graphs
}
/// Process the header statement
fn headers(&mut self) {
//Section 3.1.2/table 4
// *:x rdf:type owl:Ontology .
//[ *:x owl:versionIRI *:y .]
let mut iri: Option<IRI<_>> = None;
let mut viri: Option<IRI<_>> = None;
for t in std::mem::take(&mut self.simple) {
match t.triple() {
[Term::Iri(s), Term::RDF(VRDF::Type), Term::OWL(VOWL::Ontology)] => {
iri = Some(s.clone());
}
[Term::Iri(s), Term::OWL(VOWL::VersionIRI), Term::Iri(ob)]
if iri.as_ref() == Some(s) =>
{
viri = Some(ob.clone());
}
_ => self.simple.push(t),
}
}
self.o.insert(OntologyID { iri, viri });
}
/// Table 5 and Table 6 (OWL 2 Mapping to RDF Graphs S3.1.2),
/// backward compatibility with OWL 1 DL, applied in the order the
/// spec prescribes -- Table 5 first, then Table 6.
fn backward_compat(&mut self) {
// Table 5: a redundant `x rdf:type rdf:Property` triple is
// removed when `x` also has one of the seven listed OWL
// property-type triples -- otherwise it survives into
// declaration processing and produces a spurious ClassAssertion.
let has_owl_property_type: HashSet<_> = self
.simple
.iter()
.filter_map(|t| match t.triple() {
[
Term::Iri(s),
Term::RDF(VRDF::Type),
Term::OWL(
VOWL::ObjectProperty
| VOWL::DatatypeProperty
| VOWL::AnnotationProperty
| VOWL::OntologyProperty
| VOWL::FunctionalProperty
| VOWL::InverseFunctionalProperty
| VOWL::TransitiveProperty,
),
] => Some(s.clone()),
_ => None,
})
.collect();
self.simple.retain(|t| {
!matches!(
t.triple(),
[Term::Iri(s), Term::RDF(VRDF::Type), Term::RDF(VRDF::Property)]
if has_owl_property_type.contains(s)
)
});
// Table 6: owl:OntologyProperty is reinterpreted as
// owl:AnnotationProperty; owl:InverseFunctionalProperty,
// owl:TransitiveProperty and owl:SymmetricProperty each
// additionally imply owl:ObjectProperty.
let mut new_triples = vec![];
self.simple.retain(|t| match t.triple() {
[s, Term::RDF(VRDF::Type), Term::OWL(VOWL::OntologyProperty)] => {
new_triples.push(
[s.clone(), Term::RDF(VRDF::Type), Term::OWL(VOWL::AnnotationProperty)].into(),
);
false
}
[
s,
Term::RDF(VRDF::Type),
Term::OWL(
VOWL::InverseFunctionalProperty
| VOWL::TransitiveProperty
| VOWL::SymmetricProperty,
),
] => {
new_triples.push(
[s.clone(), Term::RDF(VRDF::Type), Term::OWL(VOWL::ObjectProperty)].into(),
);
true
}
_ => true,
});
self.simple.extend(new_triples);
}
fn parse_annotations(
&self,
triples: &[[Term<A>; 3]],
) -> Result<BTreeSet<Annotation<A>>, HornedError> {
let mut ann = BTreeSet::default();
for a in triples {
ann.insert(self.annotation(a)?);
}
Ok(ann)
}
// Process annotations
fn annotation(&self, t: &[Term<A>; 3]) -> Result<Annotation<A>, HornedError> {
match t {
// We assume that anything passed to here is an
// annotation built in type
[s, RDFS(rdfs), b] => {
let iri = self.b.iri(rdfs.as_ref());
self.annotation(&[s.clone(), Term::Iri(iri), b.clone()])
}
[s, OWL(owl), b] => {
let iri = self.b.iri(owl.as_ref());
self.annotation(&[s.clone(), Term::Iri(iri), b.clone()])
}
[_, Iri(p), ob @ Term::Literal(_)] => Ok(Annotation {
ap: AnnotationProperty(p.clone()),
av: self.convert_to_literal(ob).unwrap().into(),
ann: Default::default(),
}),
[_, Iri(p), Iri(ob)] => {
// IRI annotation value
Ok(Annotation {
ap: AnnotationProperty(p.clone()),
av: ob.clone().into(),
ann: Default::default(),
})
}
[_, Iri(p), Term::BNode(_)] => Ok(Annotation {
ap: AnnotationProperty(p.clone()),
av: self.b.anon_renumbered().into(),
ann: Default::default(),
}),
all => Err(HornedError::invalid(format!(
"Invalid annotation found {:?}",
all
))),
}
}
fn merge<IAA: Into<AnnotatedComponent<A>>>(&mut self, cmp: IAA) {
let cmp = cmp.into();
update_or_insert_logically_equal_component(&mut self.o, cmp);
}
/// Process axiom annotations.
fn axiom_annotations(&mut self) -> Result<(), HornedError> {
let mut bnode_to_key: HashMap<BNode<A>, [Term<A>; 3]> = HashMap::new();
for (k, v) in std::mem::take(&mut self.bnode) {
match v.as_slice() {
[
[_, Term::OWL(VOWL::AnnotatedProperty), p], //:
[_, Term::OWL(VOWL::AnnotatedSource), sb], //:
[_, Term::OWL(VOWL::AnnotatedTarget), ob], //:
[_, Term::RDF(VRDF::Type), Term::OWL(VOWL::Axiom)],
ann @ ..,
] => {
// The original axiom that this annotation
// sits on will have it's IRIs convert to
// OWL/RDF vocab, so we must do this here or
// they will not match the key of the
// annotation.
let key = self.b.substitute_term([sb.clone(), p.clone(), ob.clone()]);
bnode_to_key.insert(k, key.clone());
let annotations = self.parse_annotations(ann)?;
self.ann_map.insert(key, annotations);
}
_ => {
self.bnode.insert(k, v);
}
}
}
// Second pass: owl:Annotation bnodes attach nested annotations
// to the annotation identified by (annotatedSource bnode,
// annotatedProperty, annotatedTarget).
for (k, v) in std::mem::take(&mut self.bnode) {
match v.as_slice() {
[
[_, Term::OWL(VOWL::AnnotatedProperty), p],
[_, Term::OWL(VOWL::AnnotatedSource), Term::BNode(sb_bnode)],
[_, Term::OWL(VOWL::AnnotatedTarget), ob],
[_, Term::RDF(VRDF::Type), Term::OWL(VOWL::Annotation)],
nested_ann @ ..,
] => {
if let Some(ann_key) = bnode_to_key.get(sb_bnode).cloned() {
let ref_ann =
self.annotation(&[Term::BNode(k.clone()), p.clone(), ob.clone()])?;
let nested = self.parse_annotations(nested_ann)?;
if let Some(ann_set) = self.ann_map.get_mut(&ann_key)
&& let Some(mut target) = ann_set.take(&ref_ann)
{
target.ann = nested;
ann_set.insert(target);
}
} else {
self.bnode.insert(k, v);
}
}
_ => {
self.bnode.insert(k, v);
}
}
}
Ok(())
}
/// Process named entity declaration axioms
fn declarations(&mut self) {
// Table 7
for t in std::mem::take(&mut self.simple) {
let entity = match t.triple() {
[Term::Iri(s), Term::RDF(VRDF::Type), entity] => match entity {
Term::OWL(VOWL::Class) => Some(Class(s.clone()).into()),
Term::OWL(VOWL::ObjectProperty) => Some(ObjectProperty(s.clone()).into()),
Term::OWL(VOWL::AnnotationProperty) => {
Some(AnnotationProperty(s.clone()).into())
}
Term::OWL(VOWL::DatatypeProperty) => Some(DataProperty(s.clone()).into()),
Term::OWL(VOWL::NamedIndividual) => Some(NamedIndividual(s.clone()).into()),
Term::RDFS(VRDFS::Datatype) => Some(Datatype(s.clone()).into()),
_ => None,
},
_ => None,
};