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
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
//! # Horned-OWL
//!
//! Horned-OWL is a library for the reading, manipulation and
//! generation of
//! [OWL](https://www.w3.org/TR/2012/REC-owl2-primer-20121211/)
//! ontologies. As well as a library, it offers a number of
//! command-line tools for performing the same.
//!
//! The focus of this library is on performance, compared to the [OWL
//! API](https://github.com/owlcs/owlapi). Currently, on IO tasks, it
//! is between 1 and 2 orders of magnitude faster.
//!
//! # Author
//!
//! This library is written by Phillip Lord <phillip.lord@newcastle.ac.uk>
//!
//! # Status
//!
//! At the moment, the library is in early stages and it is not a
//! complete implementation of the OWL specification.

use std::cell::RefCell;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::cmp::Ordering;
use std::hash::Hash;
use std::hash::Hasher;
use std::ops::Deref;
use std::rc::Rc;



/// An
/// [IRI](https://en.wikipedia.org/wiki/Internationalized_Resource_Identifier)
/// is an internationalized version of an URI/URL.
///
/// Here, we represent it as a simple string. In Horned-OWL IRIs are
/// created through `Build`; this caches the underlying String meaning
/// that IRIs are light-weight to `clone`.
#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub struct IRI(Rc<String>);

impl Deref for IRI{
    type Target = String;

    fn deref(&self) -> &String{
        &self.0
    }
}

impl From<IRI> for String{
    fn from(i:IRI) -> String {
        // Clone Rc'd value
        (*i.0).clone()
    }
}

impl <'a> From<&'a IRI> for String {
    fn from(i:&'a IRI) -> String {
        (*i.0).clone()
    }
}

/// `Build` creates new `IRI` and `NamedEntity` instances.
///
/// There is caching for performance. An `IRI` or `NamedEntity` with a
/// given IRI will use the same string in memory, if they have been
/// created with the same builder. Equality, ordering and hashing is
/// conserved across different `Build` instances, so entities from
/// different instances can be combined within a single ontology
/// without consequences except for increased memory use.

// Currently `Build` uses Rc/RefCell, as does IRI which limits this
// library to a single thread, as does the use of Rc in IRI. One or
// both could be replaced by traits or enums straight-forwardly
// enough, to enable threading.
#[derive(Debug, Default)]
pub struct Build(Rc<RefCell<BTreeSet<IRI>>>);

impl Build{
    pub fn new() -> Build{
        Build(Rc::new(RefCell::new(BTreeSet::new())))
    }

    /// Constructs a new `IRI`
    ///
    /// # Examples
    ///
    /// ```
    /// # use horned_owl::model::*;
    /// let b = Build::new();
    /// let iri = b.iri("http://www.example.com");
    /// assert_eq!("http://www.example.com", String::from(iri));
    /// ```
    pub fn iri<S>(&self, s: S) -> IRI
        where S: Into<String>
    {
        let iri = IRI(Rc::new(s.into()));

        let mut cache = self.0.borrow_mut();
        if cache.contains(&iri){
            return cache.get(&iri).unwrap().clone()
        }

        cache.insert(iri.clone());
        iri
    }

    /// Constructs a new `Class`.

    ///
    /// # Examples
    ///
    /// ```
    /// # use horned_owl::model::*;
    /// let b = Build::new();
    /// let c1 = b.class("http://www.example.com".to_string());
    /// let c2 = b.class("http://www.example.com");
    ///
    /// assert_eq!(c1, c2);
    /// ```
    ///
    pub fn class<S>(&self, s:S) -> Class
        where S: Into<String>
    {
        Class(self.iri(s))
    }

    /// Constructs a new `ObjectProperty`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use horned_owl::model::*;
    /// let b = Build::new();
    /// let obp1 = b.object_property("http://www.example.com".to_string());
    /// let obp2 = b.object_property("http://www.example.com");
    ///
    /// assert_eq!(obp1, obp2);
    /// ```
    pub fn object_property<S>(&self, s:S) -> ObjectProperty
        where S: Into<String>
    {
        ObjectProperty(self.iri(s))
    }

    /// Constructs a new `AnnotationProperty`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use horned_owl::model::*;
    /// let b = Build::new();
    /// let anp1 = b.annotation_property("http://www.example.com".to_string());
    /// let anp2 = b.annotation_property("http://www.example.com");
    ///
    /// assert_eq!(anp1, anp2);
    /// ```
    pub fn annotation_property<S>(&self, s:S)-> AnnotationProperty
        where S: Into<String>
    {
        AnnotationProperty(self.iri(s))
    }

    /// Constructs a new `DataProperty`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use horned_owl::model::*;
    /// let b = Build::new();
    /// let dp1 = b.data_property("http://www.example.com".to_string());
    /// let dp2 = b.data_property("http://www.example.com");
    ///
    /// assert_eq!(dp1, dp2);
    /// ```
    pub fn data_property<S>(&self, s:S) -> DataProperty
        where S: Into<String>
    {
        DataProperty(self.iri(s))
    }

    /// Constructs a new `NamedIndividual`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use horned_owl::model::*;
    /// let b = Build::new();
    /// let ni1 = b.named_individual("http://www.example.com".to_string());
    /// let ni2 = b.named_individual("http://www.example.com");
    ///
    /// assert_eq!(ni1, ni2);
    /// ```
    pub fn named_individual<S>(&self, s:S) -> NamedIndividual
        where S: Into<String>
    {
        NamedIndividual(self.iri(s))
    }

    /// Constructs a new `Datatype`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use horned_owl::model::*;
    /// let b = Build::new();
    /// let ni1 = b.datatype("http://www.example.com".to_string());
    /// let ni2 = b.datatype("http://www.example.com");
    ///
    /// assert_eq!(ni1, ni2);
    /// ```
    pub fn datatype<S>(&self, s:S) -> Datatype
        where S: Into<String>
    {
        Datatype(self.iri(s))
    }
}

macro_rules! named {
    ($($(#[$attr:meta])* $name:ident),*)  => {

        /// An OWL entity that is directly resolvable to an IRI
        ///
        /// All variants in this enum are named after the struct
        /// equivalent form. The individual structs for each variant
        /// provide us types for use elsewhere in the library.
        #[derive(Debug, Eq, PartialEq, Hash)]
        pub enum NamedEntity{
            $($name($name)),*
        }

        $(
            $(#[$attr]) *
            #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
            pub struct $name(pub IRI);

            impl From<IRI> for $name {
                fn from(iri: IRI) -> $name {
                    Self::from(&iri)
                }
            }

            impl <'a> From<&'a IRI> for $name {
                fn from(iri: &IRI) -> $name {
                    $name(iri.clone())
                }
            }

            impl From<$name> for String {
                fn from(n: $name) -> String {
                    String::from(n.0)
                }
            }

            impl <'a> From<&'a $name> for String {
                fn from(n: &$name) -> String {
                    String::from(&n.0)
                }
            }

            impl From<$name> for IRI {
                fn from(n: $name) -> IRI {
                    Self::from(&n)
                }
            }

            impl <'a> From<&'a $name> for IRI {
                fn from(n: &$name) -> IRI {
                    (n.0).clone()
                }
            }

            impl From<$name> for NamedEntity {
                fn from(n:$name) -> NamedEntity {
                    NamedEntity::$name(n)
                }
            }

            impl $name {
                pub fn is<I>(&self, iri: I) -> bool
                    where I:Into<IRI>
                {
                    self.0 == iri.into()
                }

                pub fn is_s<S>(&self, iri:S) -> bool
                    where S:Into<String>
                {
                    *(self.0).0 == iri.into()
                }

            }
        ) *
    }
}

named!{
    /// An OWL
    /// [Class](https://www.w3.org/TR/2012/REC-owl2-primer-20121211/#Classes_and_Instances)
    /// is a group of individuals.
    ///
    /// Usually these individuals have something in common with
    /// each other.
    Class,

        /// An OWL
    /// [Datatype](https://www.w3.org/TR/owl2-primer/#Datatypes) is a
    /// specific kind of data, such as an integer, string or so forth.
    Datatype,

    /// An OWL
    /// [ObjectProperty](https://www.w3.org/TR/2012/REC-owl2-primer-20121211/#Object_Properties)
    /// is a relationship between two individuals.
    ///
    /// Although the relationship is between individuals, it is most
    /// often expressed as a relationship between two classes. See
    /// `ClassExpression` for more information.
    ObjectProperty,

    /// An OWL
    /// [DataProperty](https://www.w3.org/TR/2012/REC-owl2-primer-20121211/#Datatypes)
    /// is a relationship between part of an ontology and some
    /// concrete information.
    DataProperty,

    /// An OWL
    /// [AnnotationProperty](https://www.w3.org/TR/2012/REC-owl2-primer-20121211/#Document_Information_and_Annotations)
    /// is a relationship between a part of an ontology and an
    /// `Annotation`.
    ///
    /// The `Annotation` describes that part of the ontology. It is
    /// not part of the description of the world, but a description of
    /// the ontology itself.
    AnnotationProperty,

    /// An OWL
    /// [NamedIndividual](https://www.w3.org/TR/2012/REC-owl2-primer-20121211/#Classes_and_Instances)
    /// is an individual in the ontology which is specifically known
    /// about and can be identified by name.
    NamedIndividual
}

pub fn declaration(ne: NamedEntity) -> Axiom {
    match ne {
        NamedEntity::Class(c) =>
            Axiom::DeclareClass(DeclareClass(c)),
        NamedEntity::ObjectProperty(obp) =>
            Axiom::DeclareObjectProperty(DeclareObjectProperty(obp)),
        NamedEntity::AnnotationProperty(anp) =>
            Axiom::DeclareAnnotationProperty
            (DeclareAnnotationProperty(anp)),
        NamedEntity::DataProperty(dp) =>
            Axiom::DeclareDataProperty
            (DeclareDataProperty(dp)),
        NamedEntity::NamedIndividual(ni) =>
            Axiom::DeclareNamedIndividual(DeclareNamedIndividual(ni)),
        NamedEntity::Datatype(dt) =>
            Axiom::DeclareDatatype(DeclareDatatype(dt))
    }
}

/// An interface providing access to any `Annotation` attached to an
/// entity.
trait Annotated {
    /// Return the annotation
    ///
    /// The returned `BTreeSet` may be empty.
    fn annotation(&self) -> &BTreeSet<Annotation>;
}

/// An interface providing access to the `AxiomKind`
///
/// An OWL ontology consists of a set of axioms of one of many
/// different kinds. These axioms all return an variant instance of
/// the `AxiomKind` enum. This is used in the API mostly to retrieve
/// instances of a certain kind.
pub trait Kinded {
    fn kind(&self) -> AxiomKind;
}

/// An `AnnotatedAxiom` is an `Axiom` with one or more `Annotation`.
#[derive(Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct AnnotatedAxiom{
    pub axiom: Axiom,
    pub annotation: BTreeSet<Annotation>
}

impl AnnotatedAxiom {
    pub fn new<I>(axiom: I, annotation: BTreeSet<Annotation>)
                  -> AnnotatedAxiom
        where I: Into<Axiom>
    {
        AnnotatedAxiom{axiom:axiom.into(), annotation}
    }

    pub fn logical_cmp(&self, other: &AnnotatedAxiom) -> Ordering {
        self.axiom.cmp(&other.axiom)
    }

    pub fn logical_partial_cmp(&self, other: &AnnotatedAxiom) -> Option<Ordering> {
        Some(self.cmp(other))
    }

    pub fn logical_eq(&self, other: &AnnotatedAxiom) -> bool {
        self.axiom == other.axiom
    }

    pub fn logical_hash<H: Hasher>(&self, state: &mut H) -> () {
        self.axiom.hash(state)
    }
}

impl From<Axiom> for AnnotatedAxiom {
    fn from(axiom: Axiom) -> AnnotatedAxiom {
        AnnotatedAxiom {
            axiom,
            annotation: BTreeSet::new()
        }
    }
}

impl Kinded for AnnotatedAxiom {
    fn kind(&self) -> AxiomKind {
        self.axiom.kind()
    }
}

// Macro implementations. The core data model of horned is fairly
// duplicative -- an axiom, for instance, has three different Rust
// entities: a struct representing the data, an enum variant which can
// contain the struct, and a empty enum variant that can be used to
// describe one or the other of these types and operate as a key for
// the kind.

/// Return all axioms of a specific `AxiomKind`
#[allow(unused_macros)]
macro_rules! on {
    ($ont:ident, $kind:ident)
        => {
            $ont.axiom(AxiomKind::$kind)
                .map(|ax|
                     {
                         match ax {
                             Axiom::$kind(n) => n,
                             _ => panic!()
                         }
                     })
        }
}

/// Add a method to `Ontology` which returns axioms of a specific
/// `AxiomKind`.
#[allow(unused_macros)]
macro_rules! onimpl {
    ($kind:ident, $method:ident)
        =>
    {
        onimpl!($kind, $method, stringify!($kind));
    };
    ($kind:ident, $method:ident, $skind:expr)
        =>
    {
        impl Ontology {

            #[doc = "Return all instances of"]
            #[doc = $skind]
            #[doc = "in the ontology."]
            pub fn $method(&self)
                       -> impl Iterator<Item=&$kind> {
                on!(self, $kind)
            }
        }
    }
}

/// Add `Kinded` and `From` for each axiom.
macro_rules! axiomimpl {
    ($name:ident) => {
        impl From<$name> for Axiom {
                fn from(ax: $name) -> Axiom {
                    Axiom::$name(ax)
                }
        }

        impl From<$name> for AnnotatedAxiom {
            fn from(ax: $name) -> AnnotatedAxiom {
                AnnotatedAxiom::from(
                    Axiom::from(ax))
            }
        }

        impl Kinded for $name {
            fn kind(&self) -> AxiomKind {
                AxiomKind::$name
            }
        }
    }
}

/// Define a new axiom
///
/// Axioms can be either a tuple-like or normal struct. Documentation
/// is attached as a doc attribute after.
//
// I tried extensively to pass the attribute in the more normal
// location in front of the entity, but couldn't get it too match. I
// noticed that the quick_error crate passes afterwards and it's easy
// to get to work this way. As it's an internal macro, I think this is fine.
macro_rules! axiom {
    ($name:ident ($($tt:ty),*) $(#[$attr:meta])*) =>
    {
        $(#[$attr]) *
        #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
        pub struct $name($(pub $tt),*);
        axiomimpl!($name);
    };
    ($name:ident {
        $($field_name:ident: $field_type:ty),*
    }
    $(#[$attr:meta])*
    ) => {
        $(#[$attr]) *
        #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
        pub struct $name
        {
            $(pub $field_name: $field_type),*,
        }

        impl $name {
            pub fn new($($field_name: $field_type),*)
                -> $name
            {
                $name {
                    $($field_name),*
                }
            }

        }
        axiomimpl!($name);
    }
}

/// Generate all the axiom data structures
//
// This macro generates all of the axioms at once (delegated to the
// axiom macro). We have to do this in one go, although it makes
// the pattern matching a pain, because we need to know all the axiom
// names at once so we can generate the AxiomKind and Axiom
// enums.
macro_rules! axioms {
    ($($(#[$attr:meta])* $name:ident $tt:tt),*)
        =>
    {
        /// Contains all different kinds of axiom
        ///
        /// Variants of this C-style enum represent all of the
        /// different axioms that can exist in the ontology. Instances
        /// of this enum are returned by all `Axiom` and other
        /// entities as part of the `Kinded` trait.
        /// See also `Axiom` which is a Enum whose variants take
        /// instances of the `Axiom`
        #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
        pub enum AxiomKind {
            $($name),*
        }

        impl AxiomKind {
            pub fn all_kinds() -> Vec<AxiomKind> {
                vec![$(AxiomKind::$name),*]
            }
        }

        /// An axiom
        ///
        /// This enum has variants representing the various kinds of
        /// Axiom that can be found in an OWL Ontology. An OWL axiom
        /// maps to three different entities in Horned-OWL. First is a
        /// struct (for example, `SubClassOf`) which contains the data
        /// which defines the axiom (i.e. super and sub class for
        /// `SubClassOf`). Second, is a variant of the `AxiomKind`,
        /// which is used to identify all instances of a particular
        /// kind of axiom (i.e. any `SubClassOf` axiom will return an
        /// instance of AxiomKind::SubClassOf). Finally, we have a
        /// variant of this enum, which contains one of the structs
        /// (i.e. Axiom::SubClassOf(SubClassOf)), which is used as a union
        /// type for all structs. The struct and enum variants all
        /// share identical names.
        #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
        pub enum Axiom{
            $($name($name)),*
        }

        impl Kinded for Axiom
        {
            fn kind(&self) -> AxiomKind
            {
                match self
                {
                    $(
                        Axiom::$name(n) => n.kind()
                    ),*

                }
            }
        }

        $(
            axiom!(
                $name $tt $(#[$attr]) *
            );
        ) *
    }
}

axioms!{
    /// An annotation associated with this Ontology
    OntologyAnnotation (Annotation),

    /// Declares that an IRI is an import of this ontology
    Import(IRI),

    // Declaration Axioms

    /// Declares that an IRI represents a Class in the Ontology
    ///
    /// In OWL, entities must be declared to be of a particular
    /// type. While, OWL (and Horned-OWL) allows the use of Class in
    /// an ontology where there is no declaration, the end ontology
    /// will change profile to OWL Full.  See also the [OWL
    /// Primer](https://www.w3.org/TR/2012/REC-owl2-primer-20121211/#Entity_Declarations)
    DeclareClass(Class),

    /// Declares that an IRI represents an ObjectProperty in the
    /// Ontology.
    ///
    /// See also [`DeclareClass`](struct.DeclareClass.html)
    DeclareObjectProperty(ObjectProperty),

    /// Declares that an IRI represents an AnnotationProperty in the
    /// Ontology.
    ///
    /// See also [`DeclareClass`](struct.DeclareClass.html)
    DeclareAnnotationProperty (AnnotationProperty),

    /// Declares that an IRI represents a DataProperty in the
    /// ontology.
    ///
    /// See also [`DeclareClass`](struct.DeclareClass.html)
    DeclareDataProperty (DataProperty),

    /// Declare that an IRI represents a NamedIndividual in the
    /// ontology.
    ///
    /// See also [`DeclareClass`](struct.DeclareClass.html)
    DeclareNamedIndividual (NamedIndividual),

    /// Declare that an IRI represents a Datatype in the ontology.
    ///
    DeclareDatatype(Datatype),

    // Class Axioms

    /// A subclass relationship between two `ClassExpression`.
    ///
    /// All instances of `sub_class` are also instances of
    /// `super_class`.
    SubClassOf{
        super_class: ClassExpression,
        sub_class: ClassExpression
    },

    /// An equivalance relationship between two `ClassExpression`.
    ///
    /// All instances of `ClassExpression` are also instances
    /// of other other.
    EquivalentClasses(Vec<ClassExpression>),

    /// A disjoint relationship between two `ClassExpression`
    ///
    /// No instance of one `ClassExpression` can also be an instance
    /// of any of the others.
    DisjointClasses(Vec<ClassExpression>),

    // ObjectProperty axioms

    /// A sub property relationship between two object properties.
    ///
    /// The existance of the sub property relationship between two
    /// individuals also implies the super property relationship
    /// also. The super property can also be a property chain.
    /// So, if `s` is a super property of `r` then `a r b` implies `a
    /// s b`.
    ///
    /// See also: [Property Hierarchies](https://www.w3.org/TR/2012/REC-owl2-primer-20121211/#Property_Hierarchies)
    /// See also: [Property Chains](https://www.w3.org/TR/2012/REC-owl2-primer-20121211/#Property_Chains)
    SubObjectPropertyOf{
        super_property:SubObjectPropertyExpression,
        sub_property:ObjectProperty
    },

    /// An equivalent object properties relationship.
    ///
    /// States that two object properties are semantically identical
    /// to each other.
    EquivalentObjectProperties(Vec<ObjectPropertyExpression>),

    /// A disjoint object property relationship.
    ///
    /// This states that is an individual is connected by one of these
    /// object properties, it cannot be connected by any of the others.
    DisjointObjectProperties(Vec<ObjectPropertyExpression>),

    /// An inverse relationship between two object properties.
    ///
    /// If two individuals are related by one relationship, they are
    /// related by the other in the opposite direction. So, if `r` and
    /// `s` are transitive, then `a r b` implies `b r a`.
    ///
    /// See also: [Property Characteristics](https://www.w3.org/TR/2012/REC-owl2-primer-20121211/#Property_Characteristics)
    InverseObjectProperties(ObjectProperty,ObjectProperty),

    /// The domain of the object property.
    ///
    /// This states that if an individual `i` has an relationship,
    /// `ope` to any other individual, then the individual `i` is an
    /// instances of `ce`
    ///
    /// See also: [Domain](https://www.w3.org/TR/owl2-syntax/#Object_Property_Domain)
    ObjectPropertyDomain{ope:ObjectPropertyExpression, ce:ClassExpression},

    /// The range of the object property.
    ///
    /// This states that if an individual `i` is connected to be the
    /// relationship `ope`, then it is an individual of `ce`.1
    ///
    /// See also: [Domain](https://www.w3.org/TR/owl2-syntax/#Object_Property_Range)
    ObjectPropertyRange{ope:ObjectPropertyExpression, ce:ClassExpression},

    /// The functional characteristic.
    ///
    /// This states that if for a given individual `i`, there can be
    /// only one individual `j` connected to `i` by this object
    /// property expression.
    ///
    /// See also: [Functional](https://www.w3.org/TR/owl2-syntax/#Functional_Object_Properties)
    FunctionalObjectProperty(ObjectPropertyExpression),

    /// The inverse functional characteristic
    ///
    /// This states that for each individual `i`, there can be at most
    /// one individual `j` connected to `i` via this object property
    /// expression.
    ///
    /// See also: [Inverse Functional](https://www.w3.org/TR/owl2-syntax/#Inverse-Functional_Object_Properties)
    InverseFunctionalObjectProperty(ObjectPropertyExpression),

    /// The reflexive characteristic
    ///
    /// Every individual that is connected via the
    /// ObjectPropertyExpression is connected to itself.
    ///
    /// See also: [Reflexive](https://www.w3.org/TR/owl2-syntax/#Reflexive_Object_Properties)
    ReflexiveObjectProperty(ObjectPropertyExpression),

    /// The irreflexive characteristic
    ///
    /// No individual can be connected to itself by this property.
    ///
    /// See also: [Irreflexive](https://www.w3.org/TR/owl2-syntax/#Irreflexive_Object_Properties)
    IrreflexiveObjectProperty(ObjectPropertyExpression),

    /// The symmetric characteristic
    ///
    /// If an individual `i` is connected to `j` by this
    /// ObjectPropertyExpression, then `j` is also connected by `i`
    /// See also: [Symmetric](https://www.w3.org/TR/owl2-syntax/#Symmetric_Object_Properties)
    SymmetricObjectProperty(ObjectPropertyExpression),

    /// The asymmetric characteristic.
    ///
    /// if an individual `i` is connected to `j` by this
    /// ObjectPropertyExpression, then `j` cannot be connected to `i`
    /// by the ObjectPropertyExpression.
    ///
    /// See also: [Asymmetric](https://www.w3.org/TR/owl2-syntax/#Asymmetric_Object_Properties)
    AsymmetricObjectProperty(ObjectPropertyExpression),

    /// A transitive relationship between two object properties.
    ///
    /// When `r` is transitive, then `a r b`, and `b r c` implies `a r
    /// c` also.
    ///
    /// See also: [TransitiveObjectProperty](https://www.w3.org/TR/owl2-syntax/#Transitive_Object_Properties)
    TransitiveObjectProperty(ObjectProperty),

    /// A sub data property relationship.
    ///
    /// The existence of the `sub_property` relationship also implies
    /// the existence of the `super_property`.
    ///
    /// See also: [Data Subproperties](https://www.w3.org/TR/owl2-syntax/#Data_Subproperties)
    SubDataPropertyOf {
        super_property:DataProperty,
        sub_property:DataProperty
    },

    /// An equivalent data property relationship.
    ///
    /// All these DataProperties are semantically identical.
    ///
    /// See also: [EquivalentDataproperties](https://www.w3.org/TR/owl2-syntax/#Equivalent_Data_Properties)
    EquivalentDataProperties(Vec<DataProperty>),

    /// A disjoint data property relationship.
    ///
    /// No individual can be connected to a data property expression
    /// by more than one of these DataProperty relations.
    ///
    /// See also: [DisjointDataProperties](https://www.w3.org/TR/owl2-syntax/#Disjoint_Data_Properties)
    DisjointDataProperties(Vec<DataProperty>),

    /// The domain of a DataProperty.
    ///
    /// If an individual `i` has a relationship `dp` then `i` must be
    /// of type `ce`.
    ///
    /// See also: [Data Property Domain](https://www.w3.org/TR/owl2-syntax/#Disjoint_Data_Properties)
    DataPropertyDomain{dp:DataProperty,ce:ClassExpression},

    /// The range of a DataProperty.
    ///
    /// If in individual `i` has a relationship `dp` with some literal
    /// `l`, then `l` must by in `dr`.
    ///
    /// See also: [Data Property Range](https://www.w3.org/TR/owl2-syntax/#Data_Property_Range)
    DataPropertyRange{dp:DataProperty,dr:DataRange},

    /// The functional DataProperty characteristic.
    ///
    /// Any individual `i` can only be connected to a single literal
    /// by this DataProperty.
    ///
    /// See also: [Functional Data Property]:(https://www.w3.org/TR/owl2-syntax/#Functional_Data_Properties)
    FunctionalDataProperty(DataProperty),

    /// Defintion of a datatype.
    ///
    /// See also: [Datatype Definitions](https://www.w3.org/TR/owl2-syntax/#Datatype_Definitions)
    DatatypeDefinition {
        kind: Datatype,
        range: DataRange
    },

    /// A key
    ///
    /// An individual `i` which is of type `ce` can be uniquely
    /// identified by `pe`. Keys can only be applied to individuals
    /// which are explicitly named in the ontology, not those that are
    /// inferred.
    ///
    /// See also: [Keys](https://www.w3.org/TR/owl2-syntax/#Keys)
    HasKey{ce:ClassExpression, pe:PropertyExpression},

    // Assertions
    /// A same individual expression.
    ///
    /// See also: [Individual Equality](https://www.w3.org/TR/owl2-syntax/#Individual_Equality)
    SameIndividual (
        Vec<NamedIndividual>
    ),

    /// A different individuals expression.
    ///
    /// See also: [Individual Inequality](https://www.w3.org/TR/owl2-syntax/#Individual_Inequality)
    DifferentIndividuals (
        Vec<NamedIndividual>
    ),

    /// A class assertion expression.
    ///
    /// States that `i` is in class `ce`.
    ///
    /// See also: [Class Assertions](https://www.w3.org/TR/owl2-syntax/#Class_Assertions)   
    ClassAssertion {
        ce: ClassExpression,
        i: NamedIndividual
    },

    /// An object property assertion.
    ///
    /// Individual `from` is connected `to` by `ope`.
    ///
    /// See also: [Positive Object Property Assertions](https://www.w3.org/TR/owl2-syntax/#Positive_Object_Property_Assertions)
    ObjectPropertyAssertion {
        ope: ObjectPropertyExpression,
        from: NamedIndividual,
        to: NamedIndividual
    },

    /// A negative object property assertion.
    ///
    /// Individual `from` is not connected `to` by `ope`
    ///
    /// See also: [Negative Object Property Assertions](https://www.w3.org/TR/owl2-syntax/#Negative_Object_Property_Assertions)
    NegativeObjectPropertyAssertion {
        ope: ObjectPropertyExpression,
        from: NamedIndividual,
        to: NamedIndividual
    },

    /// A data property assertion.
    ///
    /// Individual `from` is connected `to`` literal by `dp`.
    ///
    /// See also: [Data Property Assertion](https://www.w3.org/TR/owl2-syntax/#Positive_Data_Property_Assertions)
    DataPropertyAssertion {
        dp: DataProperty,
        from: NamedIndividual,
        to: Literal
    },

    /// A negative data property assertion.
    ///
    /// Individual `from` is not connected `to` literal by `dp`.
    ///
    /// See also [Negative Data Property Assertions](https://www.w3.org/TR/owl2-syntax/#Negative_Data_Property_Assertions)
    NegativeDataPropertyAssertion {
        dp: DataProperty,
        from: NamedIndividual,
        to: Literal
    },

    // Annotation Axioms
    /// An annotation assertion axiom
    ///
    /// States that `annotation` applies to the
    /// `annotation_subject`. Annotations refer to an `IRI` rather
    /// than the `NamedEntity` identified by that `IRI`.
    AnnotationAssertion {
        annotation_subject:IRI,
        annotation: Annotation
    },

    /// An sub-property assertion for annotation properties.
    ///
    /// Implies that any annotation of the type `sub_property` is also
    /// an annotation of the type `super_property`.
    SubAnnotationPropertyOf {
        super_property:AnnotationProperty,
        sub_property: AnnotationProperty
    }
}

// In the ideal world, we would have generated these onimpl! calls as
// part of the axiom macro. This should be possible, as their is a
// fixed relationship between the struct name and the method name.
// But rust won't let us generate new identifiers or make string like
// manipulations on the them. So we can't.
//
// "Whoever does not understand LISP is doomed to reinvent it" (badly)
onimpl!{Import, import}
onimpl!{OntologyAnnotation, ontology_annotation}

onimpl!{DeclareClass, declare_class}
onimpl!{DeclareObjectProperty, declare_object_property}
onimpl!{DeclareAnnotationProperty, declare_annotation_property}
onimpl!{DeclareDataProperty, declare_data_property}
onimpl!{DeclareNamedIndividual, declare_named_individual}
onimpl!{DeclareDatatype, declare_datatype}
onimpl!{SubClassOf, sub_class}
onimpl!{EquivalentClasses, equivalent_class}
onimpl!{DisjointClasses, disjoint_class}
onimpl!{SubObjectPropertyOf, sub_object_property}
onimpl!{EquivalentObjectProperties, equivalent_object_properties}
onimpl!{DisjointObjectProperties, disjoint_object_properties}
onimpl!{InverseObjectProperties, inverse_object_properties}
onimpl!{ObjectPropertyDomain, object_property_domain}
onimpl!{ObjectPropertyRange, object_property_range}
onimpl!{FunctionalObjectProperty, functional_object_property}
onimpl!{InverseFunctionalObjectProperty, inverse_functional_object_property}
onimpl!{ReflexiveObjectProperty, reflexive_object_property}
onimpl!{IrreflexiveObjectProperty, irreflexive_object_property}
onimpl!{SymmetricObjectProperty, symmetric_object_property}
onimpl!{AsymmetricObjectProperty, assymmetric_object_property}
onimpl!{TransitiveObjectProperty, transitive_object_property}
onimpl!{SubDataPropertyOf, sub_data_property_of}
onimpl!{EquivalentDataProperties, equivalent_data_properties}
onimpl!{DisjointDataProperties, disjoint_data_properties}
onimpl!{DataPropertyDomain, data_property_domain}
onimpl!{DataPropertyRange, data_property_range}
onimpl!{FunctionalDataProperty, functional_data_property}
onimpl!{DatatypeDefinition, datatype_definition}
onimpl!{HasKey, has_key}
onimpl!{SameIndividual, same_individual}
onimpl!{DifferentIndividuals, different_individuals}
onimpl!{ClassAssertion, class_assertion}
onimpl!{ObjectPropertyAssertion, object_property_assertion}
onimpl!{NegativeObjectPropertyAssertion, negative_object_property_assertion}
onimpl!{DataPropertyAssertion, data_property_assertion}
onimpl!{NegativeDataPropertyAssertion, negative_data_property_assertion}
onimpl!{AnnotationAssertion, annotation_assertion}
onimpl!{SubAnnotationPropertyOf, sub_annotation_property_of}

// Non-axiom data structures associated with OWL
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Literal
{
    pub datatype_iri:Option<IRI>,
    pub lang: Option<String>,
    pub literal: Option<String>
}

/// Data associated with a part of the ontology.
///
/// Annotations are associated an IRI and describe that IRI in a
/// particular way, defined by the property.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Annotation {
    pub annotation_property: AnnotationProperty,
    pub annotation_value: AnnotationValue
}

/// The value of an annotation
///
/// This Enum is currently not complete.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum AnnotationValue {
    Literal(Literal),
    IRI(IRI)
}

impl From<Literal> for AnnotationValue {
    fn from(literal: Literal) -> AnnotationValue {
        AnnotationValue::Literal(literal)
    }
}

impl From<IRI> for AnnotationValue {
    fn from(iri:IRI) -> AnnotationValue {
        AnnotationValue::IRI(iri)
    }
}

/// A object property expression
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum ObjectPropertyExpression {
    ObjectProperty(ObjectProperty),
    InverseObjectProperty(ObjectProperty)
}

/// A sub-object property expression
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum SubObjectPropertyExpression {
    // We use Vec here rather than BTreeSet because, perhaps
    // surprisingly, BTreeSet is not itself hashable.
    ObjectPropertyChain(Vec<ObjectProperty>),
    ObjectPropertyExpression(ObjectPropertyExpression)
}

#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum PropertyExpression {
    ObjectPropertyExpression(ObjectPropertyExpression),
    DataProperty(DataProperty)
}

// Data!!!
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct FacetRestriction{
    pub f: Facet,
    pub l: Literal,
}

#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum Facet{
    Length,
    MinLength,
    MaxLength,
    Pattern,
    MinInclusive,
    MinExclusive,
    MaxInclusive,
    MaxExclusive,
    TotalDigits,
    FractionDigits,
    LangRange
}

#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum DataRange {
    Datatype(Datatype),
    DataIntersectionOf(Vec<DataRange>),
    DataUnionOf(Vec<DataRange>),
    DataComplementOf(Box<DataRange>),
    DataOneOf(Vec<Literal>),
    DatatypeRestriction(Datatype, Vec<FacetRestriction>),
}

impl From<Datatype> for DataRange {
    fn from(dr: Datatype) -> DataRange {
        DataRange::Datatype(dr)
    }
}


/// A class expression
///
/// As well as a named class, it is possible to define classes of
/// individuals based on these class constructors.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum ClassExpression
{
    /// A named class
    Class(Class),

    /// The boolean and
    ///
    /// The class of individuals which are individuals of all these
    /// classes.
    ObjectIntersectionOf{o:Vec<ClassExpression>},

    /// The boolean or
    ///
    /// The class of individuals which are individuals of any of these
    /// classes.
    ObjectUnionOf{o:Vec<ClassExpression>},

    /// The boolean not
    ///
    /// The class of individuals which are not individuals of any of
    /// these classes.
    ObjectComplementOf{ce:Box<ClassExpression>},

    /// An enumeration of individuals
    ///
    /// This is the class containing exactly the given set of
    /// individuals.
    ObjectOneOf{o:Vec<NamedIndividual>},

    /// An existential relationship
    ///
    /// This is the anonymous class of individuals `i`, which have the
    /// relationship `o` to a class expression `ce`. Every individual
    /// in `i` must have this relationship to one individual in `ce`.
    ObjectSomeValuesFrom{o:ObjectPropertyExpression, ce:Box<ClassExpression>},

    /// A universal relationship
    ///
    /// This is the anonymous class of individuals `i` where all
    /// individuals which are related by `o` are instances of
    /// `ce`. This does not imply that the `i` necessarily has any
    /// relation `r`.
    ObjectAllValuesFrom{o:ObjectPropertyExpression, ce:Box<ClassExpression>},

    /// An existential relationship to an individual
    ///
    /// This is the class of individuals `c` which have the
    /// relationship `o` to another individual `i`. Every individual
    /// in `c` must have this relationship to the individual `i`
    ObjectHasValue{o:ObjectPropertyExpression, i:NamedIndividual},

    /// The class of individuals which have a relation to themselves
    ///
    /// Given a object property `r`, this class defines all the
    /// individuals where `i r i`.
    ObjectHasSelf(ObjectProperty),

    /// A min cardinality relationship between individuals
    ///
    /// Given an object property `o` and a class `ce`, this describes
    /// the class of individuals which have the `o` relationship to at
    /// least `n` other individuals.
    ObjectMinCardinality{n:i32, o:ObjectPropertyExpression,
                         ce:Box<ClassExpression>},

    /// A max cardinality relationship between individuals
    ///
    /// Given an object property `o` and a class `ce`, this describes
    /// the class of individuals which have the `o` relationship to at
    /// most `n` other individuals.
    ObjectMaxCardinality{n:i32, o:ObjectPropertyExpression,
                         ce:Box<ClassExpression>},

    /// An exact cardinality relationship between individuals
    ///
    /// Given an object property `o` and a class `ce`, this describes
    /// the class of individuals which have the `o` relationship to exactly
    /// `n` other individuals.
    ObjectExactCardinality{n:i32, o:ObjectPropertyExpression,
                           ce:Box<ClassExpression>},

    /// An exististential relationship.
    ///
    /// This is the anonymous class of individuals `i` which have the
    /// relationship `dp` to the data range, `dr`. Every individual
    /// `i` must have this relationship to data constrainted by `dr`.
    ///
    /// See also: [Existential Quantification](https://www.w3.org/TR/owl2-syntax/#Existential_Quantification_2)
    DataSomeValuesFrom{dp:DataProperty, dr:DataRange},

    /// A universal relationship.
    ///
    /// This is the anonymous class of individuals `i` which if they
    /// have a relationship `dp` to some data, then that must be of
    /// type `dr`.
    ///
    /// See also [Universal Quantification](https://www.w3.org/TR/owl2-syntax/#Universal_Quantification_2)
    DataAllValuesFrom{dp:DataProperty, dr:DataRange},

    /// A has-value relationship.

    /// This is the class of individuals, `i`, which have the
    /// relationship `dp` to exactly the literal `l`.

    /// See also [Value Restriction](https://www.w3.org/TR/owl2-syntax/#Literal_Value_Restriction)
    DataHasValue{dp:DataProperty, l:Literal},

    /// A minimum cardinality restriction

    /// The class of individuals have at least `n` relationships of
    /// the kind `dp` to a given data range `dr`.

    /// See also [Min Cardinality](https://www.w3.org/TR/owl2-syntax/#Minimum_Cardinality_2)
    DataMinCardinality{n:i32, dp:DataProperty, dr:DataRange},

    /// A max cardinality restriction

    /// The class of individuals have at most `n` relationships of
    /// the kind `dp` to a given data range `dr`.

    /// See also [Max Cardinality](https://www.w3.org/TR/owl2-syntax/#Maximum_Cardinality_2)
    DataMaxCardinality{n:i32, dp:DataProperty, dr:DataRange},

    /// An exact cardinality restriction

    /// The class of individuals have exactly `n` relationships of
    /// the kind `dp` to a given data range `dr`.

    /// See also [Exactly Cardinality](https://www.w3.org/TR/owl2-syntax/#Exact_Cardinality_2)
    DataExactCardinality{n:i32, dp:DataProperty, dr:DataRange}
}

impl From<Class> for ClassExpression {
    fn from(c:Class) -> ClassExpression {
        ClassExpression::Class(c)
    }
}

impl <'a> From<&'a Class> for ClassExpression {
    fn from(c:&'a Class) -> ClassExpression {
        ClassExpression::Class(c.clone())
    }
}

/// An ontology identifier
///
/// An ontology is identified by an IRI which is expected to remain
/// stable over the lifetime of the ontology, and a version IRI which
/// is expected to change between versions.
#[derive(Debug, Default, Eq, PartialEq)]
pub struct OntologyID{
    pub iri: Option<IRI>,
    pub viri: Option<IRI>,
}

/// An ontology
///
/// An ontology consists of a identifier and set of axiom
#[derive(Debug, Default, Eq, PartialEq)]
pub struct Ontology
{
    pub id: OntologyID,
    // The use an BTreeMap keyed on AxiomKind allows efficient
    // retrieval of axioms. Otherwise, we'd have to iterate through
    // the lot every time.
    axiom: RefCell<BTreeMap<AxiomKind,BTreeSet<AnnotatedAxiom>>>,
}

impl Ontology {

    /// Fetch the axioms hashmap as a raw pointer.
    ///
    /// This method also ensures that the BTreeSet for `axk` is
    /// instantiated, which means that it effects equality of the
    /// ontology. It should only be used where the intention is to
    /// update the ontology.
    fn axioms_as_ptr(&self, axk: AxiomKind)
        -> *mut BTreeMap<AxiomKind,BTreeSet<AnnotatedAxiom>>
    {
        self.axiom.borrow_mut().entry(axk)
            .or_insert_with(BTreeSet::new);
        self.axiom.as_ptr()
    }

    /// Fetch the axioms for the given kind.
    fn set_for_kind(&self, axk: AxiomKind)
                     -> Option<&BTreeSet<AnnotatedAxiom>>
    {
        unsafe{
            (*self.axiom.as_ptr())
                .get(&axk)
        }
    }

    /// Fetch the axioms for given kind as a mutable ref.
    fn mut_set_for_kind(&mut self, axk: AxiomKind)
                        -> &mut BTreeSet<AnnotatedAxiom>
    {
        unsafe {
            (*self.axioms_as_ptr(axk))
                .get_mut(&axk).unwrap()
        }
    }

    /// Create a new ontology.
    ///
    /// # Examples
    /// ```
    /// # use horned_owl::model::*;
    /// let o = Ontology::new();
    /// let o2 = Ontology::new();
    ///
    /// assert_eq!(o, o2);
    /// ```
    pub fn new() -> Ontology{
        Ontology::default()
    }

    /// Insert an axiom into the ontology.
    ///
    /// # Examples
    /// ```
    /// # use horned_owl::model::*;
    /// let mut o = Ontology::new();
    /// let b = Build::new();
    /// o.insert(DeclareClass(b.class("http://www.example.com/a")));
    /// o.insert(DeclareObjectProperty(b.object_property("http://www.example.com/r")));
    /// ```
    ///
    /// See `declare` for an easier way to declare named entities.
    pub fn insert<A>(&mut self, ax:A) -> bool
        where A: Into<AnnotatedAxiom>
    {
        let ax:AnnotatedAxiom = ax.into();

        self.mut_set_for_kind(ax.kind()).insert(ax)
    }

    /// Declare an NamedEntity for the ontology.
    ///
    /// # Examples
    /// ```
    /// # use horned_owl::model::*;
    /// let mut o = Ontology::new();
    /// let b = Build::new();
    /// o.declare(b.class("http://www.example.com/a"));
    /// o.declare(b.object_property("http://www.example.com/r"));
    /// ```
    pub fn declare<N>(&mut self, ne: N) -> bool
        where N: Into<NamedEntity>
    {
        self.insert(
            declaration(ne.into())
        )
    }

    /// Fetch the AnnotatedAxiom for a given kind
    ///
    /// # Examples
    /// ```
    /// # use horned_owl::model::*;
    /// let mut o = Ontology::new();
    /// let b = Build::new();
    /// o.declare(b.class("http://www.example.com/a"));
    /// o.declare(b.object_property("http://www.example.com/r"));
    ///
    /// assert_eq!(o.annotated_axiom(AxiomKind::DeclareClass).count(), 1);
    /// ```
    ///
    /// See also `axiom` for access to the `Axiom` without annotations.
    pub fn annotated_axiom(&self, axk: AxiomKind)
        -> impl Iterator<Item=&AnnotatedAxiom>
    {
        self.set_for_kind(axk).
            into_iter().flat_map(|hs| hs.iter())
    }

    /// Fetch the Axiom for a given kind
    ///
    /// # Examples
    /// ```
    /// # use horned_owl::model::*;
    /// let mut o = Ontology::new();
    /// let b = Build::new();
    /// o.declare(b.class("http://www.example.com/a"));
    /// o.declare(b.object_property("http://www.example.com/r"));
    ///
    /// assert_eq!(o.axiom(AxiomKind::DeclareClass).count(), 1);
    /// ```
    ///
    /// See methods such as `declare_class` for access to the Axiom
    /// struct directly.
    pub fn axiom(&self, axk: AxiomKind)
             -> impl Iterator<Item=&Axiom>
    {
        self.annotated_axiom(axk)
            .map(|ann| &ann.axiom)
    }
}



impl Ontology {

    /// Returns all direct subclasses
    ///
    /// # Examples
    ///
    /// ```
    /// # use horned_owl::model::*;
    /// let mut o = Ontology::new();
    /// let b = Build::new();
    ///
    /// let sup = b.class("http://www.example.com/super");
    /// let sub = b.class("http://www.example.com/sub");
    /// let subsub = b.class("http://www.example.com/subsub");
    ///
    /// o.insert(SubClassOf::new((&sup).into(), (&sub).into()));
    /// o.insert(SubClassOf::new((&sub).into(), (&subsub).into()));
    ///
    /// let subs:Vec<&ClassExpression> = o.direct_subclass(&sup).collect();
    ///
    /// assert_eq!(vec![&ClassExpression::Class(sub)],subs);
    /// ```
    pub fn direct_subclass<C>(&self, c: C)
                              ->impl Iterator<Item=&ClassExpression>
        where C:Into<ClassExpression>
    {
        let c = c.into();
        self.sub_class()
            .filter(move |sc| sc.super_class == c )
            .map(|sc| &sc.sub_class )
    }

    /// Returns true is `subclass` is a subclass of `superclass`
    ///
    /// # Examples
    ///
    /// ```
    /// # use horned_owl::model::*;
    /// let mut o = Ontology::new();
    /// let b = Build::new();
    ///
    /// let sup = b.class("http://www.example.com/super");
    /// let sub = b.class("http://www.example.com/sub");
    /// let subsub = b.class("http://www.example.com/subsub");
    ///
    /// o.insert(SubClassOf::new((&sup).into(), (&sub).into()));
    /// o.insert(SubClassOf::new((&sub).into(), (&subsub).into()));
    ///
    /// assert!(o.is_subclass(&sup, &sub));
    /// assert!(!o.is_subclass(&sub, &sup));
    /// assert!(!o.is_subclass(&sup, &subsub));
    /// ```
    pub fn is_subclass<C>(&self, super_class:C,
                       sub_class:C) -> bool
        where C: Into<ClassExpression>
    {
        let super_class = super_class.into();
        let sub_class = sub_class.into();
        self.sub_class()
            .any(|sc|
                 sc.super_class == super_class &&
                 sc.sub_class == sub_class)
    }
}

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

    #[test]
    fn test_iri_from_string() {
        let build = Build::new();
        let iri = build.iri("http://www.example.com");

        assert_eq!(String::from(iri), "http://www.example.com");
    }

    #[test]
    fn test_iri_creation(){
        let build = Build::new();

        let iri1 = build.iri("http://example.com".to_string());

        let iri2 = build.iri("http://example.com".to_string());

        // these are equal to each other
        assert_eq!(iri1, iri2);

        // these are the same object in memory
        assert!(Rc::ptr_eq(&iri1.0, &iri2.0));

        // iri1, iri2 and one in the cache == 3
        assert_eq!(Rc::strong_count(&iri1.0), 3);
    }

    #[test]
    fn test_iri_string_creation(){
        let build = Build::new();

        let iri_string = build.iri("http://www.example.com".to_string());
        let iri_static = build.iri("http://www.example.com");
        let iri_from_iri = build.iri(iri_static.clone());

        let s = "http://www.example.com";
        let iri_str = build.iri(&s[..]);

        assert_eq!(iri_string, iri_static);
        assert_eq!(iri_string, iri_str);
        assert_eq!(iri_static, iri_str);
        assert_eq!(iri_from_iri, iri_str);
    }

    #[test]
    fn test_ontology_cons(){
        let _ = Ontology::new();
        assert!(true);
    }

    #[test]
    fn test_class(){
        let mut o = Ontology::new();
        let c = Build::new().class("http://www.example.com");
        o.insert(DeclareClass(c));

        assert_eq!(o.declare_class().count(), 1);
    }

    #[test]
    fn test_class_declare() {
        let c = Build::new().class("http://www.example.com");

        let mut o = Ontology::new();
        o.declare(c);

        assert_eq!(o.declare_class().count(), 1);
    }

    #[test]
    fn test_class_convertors() {
        let c = Build::new().class("http://www.example.com");
        let i = Build::new().iri("http://www.example.com");

        let i1:IRI = c.clone().into();
        assert_eq!(i, i1);

        let c1:Class = Class::from(i);
        assert_eq!(c, c1);

        let ne:NamedEntity = c.clone().into();
        assert_eq!(ne, NamedEntity::Class(c));
    }

    #[test]
    fn test_class_string_ref() {
        let s = String::from("http://www.example.com");
        let c = Build::new().class(s.clone());

        assert!(c.is_s(s));
    }

    #[test]
    fn test_is() {
        let c = Build::new().class("http://www.example.com");
        let i = Build::new().named_individual("http://www.example.com");
        let iri = Build::new().iri("http://www.example.com");

        assert!(c.is(iri));
        assert!(c.is(i.clone()));
        assert!(i.is(c));
    }

    #[test]
    fn test_axiom_convertors() {
        let c = Build::new().class("http://www.example.com");

        let dc = DisjointClasses(vec![c.clone().into(), c.clone().into()]);
        let _aa:Axiom = dc.into();

    }
}