ion-schema 0.15.0

Implementation of Amazon Ion Schema
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
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
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
use crate::ion_extension::ElementExtensions;
use crate::ion_path::{IonPath, IonPathElement};
use crate::isl::isl_constraint::{
    IslAnnotationsConstraint, IslConstraintValue, IslRegexConstraint,
};
use crate::isl::isl_type_reference::{
    IslTypeRef, IslVariablyOccurringTypeRef, NullabilityModifier,
};
use crate::isl::ranges::{I64Range, Limit, TimestampPrecisionRange, U64Range, UsizeRange};
use crate::isl::util::{
    Annotation, Ieee754InterchangeFormat, TimestampOffset, TimestampPrecision, ValidValue,
};
use crate::isl::IslVersion;
use crate::isl_require;
use crate::ordered_elements_nfa::OrderedElementsNfa;
use crate::result::{
    invalid_schema_error, invalid_schema_error_raw, IonSchemaResult, ValidationResult,
};
use crate::system::{PendingTypes, TypeId, TypeStore};
use crate::type_reference::{TypeReference, VariablyOccurringTypeRef};
use crate::types::TypeValidator;
use crate::violation::{Violation, ViolationCode};
use crate::IonSchemaElement;
use ion_rs::Element;
use ion_rs::IonData;
use ion_rs::IonType;
use ion_rs::Value;
use num_traits::ToPrimitive;
use regex::{Regex, RegexBuilder};
use std::collections::{HashMap, HashSet};
use std::fmt::{Display, Formatter};
use std::iter::Peekable;
use std::ops::Neg;
use std::str::Chars;

/// Provides validation for schema Constraint
pub trait ConstraintValidator {
    /// Checks this constraint against the provided value,
    /// adding [Violation]s and/or [ViolationChild]ren to `Err(violation)`
    /// if the constraint is violated.
    /// Otherwise, if the value passes the validation against the constraint then returns `Ok(())`.
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult;
}

/// Defines schema Constraints
#[derive(Debug, Clone, PartialEq)]
// TODO: add other constraints
pub enum Constraint {
    AllOf(AllOfConstraint),
    Annotations(AnnotationsConstraint),
    Annotations2_0(AnnotationsConstraint2_0),
    AnyOf(AnyOfConstraint),
    ByteLength(ByteLengthConstraint),
    CodepointLength(CodepointLengthConstraint),
    Contains(ContainsConstraint),
    ContentClosed,
    ContainerLength(ContainerLengthConstraint),
    Element(ElementConstraint),
    Exponent(ExponentConstraint),
    FieldNames(FieldNamesConstraint),
    Fields(FieldsConstraint),
    Ieee754Float(Ieee754FloatConstraint),
    Not(NotConstraint),
    OneOf(OneOfConstraint),
    OrderedElements(OrderedElementsConstraint),
    Precision(PrecisionConstraint),
    Regex(RegexConstraint),
    Scale(ScaleConstraint),
    TimestampOffset(TimestampOffsetConstraint),
    TimestampPrecision(TimestampPrecisionConstraint),
    Type(TypeConstraint),
    Unknown(String, Element),
    Utf8ByteLength(Utf8ByteLengthConstraint),
    ValidValues(ValidValuesConstraint),
}

impl Constraint {
    /// Creates a [Constraint::Type] referring to the type represented by the provided [TypeId].
    pub fn type_constraint(type_id: TypeId) -> Constraint {
        Constraint::Type(TypeConstraint::new(TypeReference::new(
            type_id,
            NullabilityModifier::Nothing,
        )))
    }

    /// Creates a [Constraint::AllOf] referring to the types represented by the provided [TypeId]s.
    pub fn all_of<A: Into<Vec<TypeId>>>(type_ids: A) -> Constraint {
        let type_references = type_ids
            .into()
            .iter()
            .map(|id| TypeReference::new(*id, NullabilityModifier::Nothing))
            .collect();
        Constraint::AllOf(AllOfConstraint::new(type_references))
    }

    /// Creates a [Constraint::AnyOf] referring to the types represented by the provided [TypeId]s.
    pub fn any_of<A: Into<Vec<TypeId>>>(type_ids: A) -> Constraint {
        let type_references = type_ids
            .into()
            .iter()
            .map(|id| TypeReference::new(*id, NullabilityModifier::Nothing))
            .collect();
        Constraint::AnyOf(AnyOfConstraint::new(type_references))
    }

    /// Creates a [Constraint::OneOf] referring to the types represented by the provided [TypeId]s.
    pub fn one_of<A: Into<Vec<TypeId>>>(type_ids: A) -> Constraint {
        let type_references = type_ids
            .into()
            .iter()
            .map(|id| TypeReference::new(*id, NullabilityModifier::Nothing))
            .collect();
        Constraint::OneOf(OneOfConstraint::new(type_references))
    }

    /// Creates a [Constraint::Not] referring to the type represented by the provided [TypeId].
    pub fn not(type_id: TypeId) -> Constraint {
        Constraint::Not(NotConstraint::new(TypeReference::new(
            type_id,
            NullabilityModifier::Nothing,
        )))
    }

    /// Creates a [Constraint::OrderedElements] referring to the types represented by the provided [TypeId]s.
    pub fn ordered_elements<A: Into<Vec<TypeId>>>(type_ids: A) -> Constraint {
        let type_references = type_ids
            .into()
            .iter()
            .map(|id| {
                VariablyOccurringTypeRef::new(
                    TypeReference::new(*id, NullabilityModifier::Nothing),
                    UsizeRange::new_single_value(1),
                )
            })
            .collect();
        Constraint::OrderedElements(OrderedElementsConstraint::new(type_references))
    }

    /// Creates a [Constraint::Contains] referring to [Elements] specified inside it
    pub fn contains<A: Into<Vec<Element>>>(values: A) -> Constraint {
        Constraint::Contains(ContainsConstraint::new(values.into()))
    }

    /// Creates a [Constraint::ContainerLength] from a [UsizeRange] specifying a length range.
    pub fn container_length(length: UsizeRange) -> Constraint {
        Constraint::ContainerLength(ContainerLengthConstraint::new(length))
    }

    /// Creates a [Constraint::ByteLength] from a [UsizeRange] specifying a length range.
    pub fn byte_length(length: UsizeRange) -> Constraint {
        Constraint::ByteLength(ByteLengthConstraint::new(length))
    }

    /// Creates a [Constraint::CodePointLength] from a [UsizeRange] specifying a length range.
    pub fn codepoint_length(length: UsizeRange) -> Constraint {
        Constraint::CodepointLength(CodepointLengthConstraint::new(length))
    }

    /// Creates a [Constraint::Element] referring to the type represented by the provided [TypeId] and the boolean represents whether distinct elements are required or not.
    pub fn element(type_id: TypeId, requires_distinct: bool) -> Constraint {
        Constraint::Element(ElementConstraint::new(
            TypeReference::new(type_id, NullabilityModifier::Nothing),
            requires_distinct,
        ))
    }

    /// Creates a [Constraint::Annotations] using [str]s and [Element]s specified inside it
    pub fn annotations<'a, A: IntoIterator<Item = &'a str>, B: IntoIterator<Item = Element>>(
        annotations_modifiers: A,
        annotations: B,
    ) -> Constraint {
        let annotations_modifiers: Vec<&str> = annotations_modifiers.into_iter().collect();
        let annotations: Vec<Annotation> = annotations
            .into_iter()
            .map(|a| {
                Annotation::new(
                    a.as_text().unwrap().to_owned(),
                    Annotation::is_annotation_required(
                        &a,
                        annotations_modifiers.contains(&"required"),
                    ),
                    IslVersion::V1_0,
                )
            })
            .collect();
        Constraint::Annotations(AnnotationsConstraint::new(
            annotations_modifiers.contains(&"closed"),
            annotations_modifiers.contains(&"ordered"),
            annotations,
        ))
    }

    /// Creates a [Constraint::Annotations] using [TypeId] specified inside it
    pub fn annotations_v2_0(id: TypeId) -> Constraint {
        Constraint::Annotations2_0(AnnotationsConstraint2_0::new(TypeReference::new(
            id,
            NullabilityModifier::Nothing,
        )))
    }

    /// Creates a [Constraint::Precision] from a [Range] specifying a precision range.
    pub fn precision(precision: U64Range) -> Constraint {
        Constraint::Precision(PrecisionConstraint::new(precision))
    }

    /// Creates a [Constraint::Scale] from a [Range] specifying a precision range.
    pub fn scale(scale: I64Range) -> Constraint {
        Constraint::Scale(ScaleConstraint::new(scale))
    }
    /// Creates a [Constraint::Exponent] from a [Range] specifying an exponent range.
    pub fn exponent(exponent: I64Range) -> Constraint {
        Constraint::Exponent(ExponentConstraint::new(exponent))
    }

    /// Creates a [Constraint::TimestampPrecision] from a [Range] specifying a precision range.
    pub fn timestamp_precision(precision: TimestampPrecisionRange) -> Constraint {
        Constraint::TimestampPrecision(TimestampPrecisionConstraint::new(precision))
    }

    /// Creates an [Constraint::TimestampOffset] using the offset list specified in it
    pub fn timestamp_offset(offsets: Vec<TimestampOffset>) -> Constraint {
        Constraint::TimestampOffset(TimestampOffsetConstraint::new(offsets))
    }

    /// Creates a [Constraint::Utf8ByteLength] from a [Range] specifying a length range.
    pub fn utf8_byte_length(length: UsizeRange) -> Constraint {
        Constraint::Utf8ByteLength(Utf8ByteLengthConstraint::new(length))
    }

    /// Creates a [Constraint::Fields] referring to the fields represented by the provided field name and [TypeId]s.
    /// By default, fields created using this method will allow open content
    pub fn fields<I>(fields: I) -> Constraint
    where
        I: Iterator<Item = (String, TypeId)>,
    {
        let fields = fields
            .map(|(field_name, type_id)| {
                (
                    field_name,
                    VariablyOccurringTypeRef::new(
                        TypeReference::new(type_id, NullabilityModifier::Nothing),
                        UsizeRange::zero_or_one(),
                    ),
                )
            })
            .collect();
        Constraint::Fields(FieldsConstraint::new(fields, true))
    }

    /// Creates a [Constraint::FieldNames] referring to the type represented by the provided [TypeId] and the boolean represents whether each field name should be distinct or not.
    pub fn field_names(type_id: TypeId, requires_distinct: bool) -> Constraint {
        Constraint::FieldNames(FieldNamesConstraint::new(
            TypeReference::new(type_id, NullabilityModifier::Nothing),
            requires_distinct,
        ))
    }

    /// Creates a [Constraint::ValidValues] using the [Element]s specified inside it
    /// Returns an IonSchemaError if any of the Elements have an annotation other than `range`
    pub fn valid_values(
        valid_values: Vec<ValidValue>,
        isl_version: IslVersion,
    ) -> IonSchemaResult<Constraint> {
        Ok(Constraint::ValidValues(ValidValuesConstraint::new(
            valid_values,
            isl_version,
        )?))
    }

    /// Creates a [Constraint::Regex] from the expression and flags (case_insensitive, multi_line) and also specify the ISL version
    pub fn regex(
        case_insensitive: bool,
        multi_line: bool,
        expression: String,
        isl_version: IslVersion,
    ) -> IonSchemaResult<Constraint> {
        let regex = IslRegexConstraint::new(case_insensitive, multi_line, expression);
        Ok(Constraint::Regex(RegexConstraint::from_isl(
            &regex,
            isl_version,
        )?))
    }

    /// Creates a [Constraint::Ieee754Float] from [Ieee754InterchangeFormat] specified inside it
    pub fn ieee754_float(interchange_format: Ieee754InterchangeFormat) -> Constraint {
        Constraint::Ieee754Float(Ieee754FloatConstraint::new(interchange_format))
    }

    /// Resolves all ISL type references to corresponding [TypeReference]s
    fn resolve_type_references(
        isl_version: IslVersion,
        type_references: &[IslTypeRef],
        type_store: &mut TypeStore,
        pending_types: &mut PendingTypes,
    ) -> IonSchemaResult<Vec<TypeReference>> {
        type_references
            .iter()
            .map(|t| IslTypeRef::resolve_type_reference(isl_version, t, type_store, pending_types))
            .collect::<IonSchemaResult<Vec<TypeReference>>>()
    }

    /// Parse an [IslConstraint] to a [Constraint]
    pub(crate) fn resolve_from_isl_constraint(
        isl_version: IslVersion,
        isl_constraint: &IslConstraintValue,
        type_store: &mut TypeStore,
        pending_types: &mut PendingTypes,
        open_content: bool, // this will be used by Fields constraint to verify if open content is allowed or not
    ) -> IonSchemaResult<Constraint> {
        // TODO: add more constraints below
        match isl_constraint {
            IslConstraintValue::AllOf(isl_type_references) => {
                let type_references = Constraint::resolve_type_references(
                    isl_version,
                    isl_type_references,
                    type_store,
                    pending_types,
                )?;
                Ok(Constraint::AllOf(AllOfConstraint::new(type_references)))
            }
            IslConstraintValue::Annotations(isl_annotations) => match isl_annotations {
                IslAnnotationsConstraint::SimpleAnnotations(simple_annotations) => {
                    match isl_version {
                        IslVersion::V1_0 => {
                            Ok(Constraint::Annotations(AnnotationsConstraint::new(
                                simple_annotations.is_closed,
                                simple_annotations.is_ordered,
                                simple_annotations.annotations.to_owned(),
                            )))
                        }
                        IslVersion::V2_0 => {
                            let type_ref = IslTypeRef::resolve_type_reference(
                                IslVersion::V2_0,
                                &simple_annotations.convert_to_type_reference()?,
                                type_store,
                                pending_types,
                            )?;

                            Ok(Constraint::Annotations2_0(AnnotationsConstraint2_0::new(
                                type_ref,
                            )))
                        }
                    }
                }
                IslAnnotationsConstraint::StandardAnnotations(isl_type_ref) => {
                    let type_ref = IslTypeRef::resolve_type_reference(
                        isl_version,
                        isl_type_ref,
                        type_store,
                        pending_types,
                    )?;
                    Ok(Constraint::Annotations2_0(AnnotationsConstraint2_0::new(
                        type_ref,
                    )))
                }
            },
            IslConstraintValue::AnyOf(isl_type_references) => {
                let type_references = Constraint::resolve_type_references(
                    isl_version,
                    isl_type_references,
                    type_store,
                    pending_types,
                )?;
                Ok(Constraint::AnyOf(AnyOfConstraint::new(type_references)))
            }
            IslConstraintValue::ByteLength(byte_length) => Ok(Constraint::ByteLength(
                ByteLengthConstraint::new(byte_length.to_owned()),
            )),
            IslConstraintValue::CodepointLength(codepoint_length) => {
                Ok(Constraint::CodepointLength(CodepointLengthConstraint::new(
                    codepoint_length.to_owned(),
                )))
            }
            IslConstraintValue::Contains(values) => {
                let contains_constraint: ContainsConstraint =
                    ContainsConstraint::new(values.to_owned());
                Ok(Constraint::Contains(contains_constraint))
            }
            IslConstraintValue::ContentClosed => Ok(Constraint::ContentClosed),
            IslConstraintValue::ContainerLength(isl_length) => Ok(Constraint::ContainerLength(
                ContainerLengthConstraint::new(isl_length.to_owned()),
            )),
            IslConstraintValue::Element(type_reference, require_distinct_elements) => {
                let type_id = IslTypeRef::resolve_type_reference(
                    isl_version,
                    type_reference,
                    type_store,
                    pending_types,
                )?;
                Ok(Constraint::Element(ElementConstraint::new(
                    type_id,
                    *require_distinct_elements,
                )))
            }
            IslConstraintValue::FieldNames(isl_type_reference, distinct) => {
                let type_reference = IslTypeRef::resolve_type_reference(
                    isl_version,
                    isl_type_reference,
                    type_store,
                    pending_types,
                )?;
                Ok(Constraint::FieldNames(FieldNamesConstraint::new(
                    type_reference,
                    *distinct,
                )))
            }
            IslConstraintValue::Fields(fields, content_closed) => {
                let open_content = match isl_version {
                    IslVersion::V1_0 => open_content,
                    IslVersion::V2_0 => !content_closed, // for ISL 2.0 whether open content is allowed or not depends on `fields` constraint
                };
                let fields_constraint: FieldsConstraint =
                    FieldsConstraint::resolve_from_isl_constraint(
                        isl_version,
                        fields,
                        type_store,
                        pending_types,
                        open_content,
                    )?;
                Ok(Constraint::Fields(fields_constraint))
            }
            IslConstraintValue::Ieee754Float(iee754_interchange_format) => Ok(
                Constraint::Ieee754Float(Ieee754FloatConstraint::new(*iee754_interchange_format)),
            ),
            IslConstraintValue::OneOf(isl_type_references) => {
                let type_references = Constraint::resolve_type_references(
                    isl_version,
                    isl_type_references,
                    type_store,
                    pending_types,
                )?;
                Ok(Constraint::OneOf(OneOfConstraint::new(type_references)))
            }
            IslConstraintValue::Not(type_reference) => {
                let type_id = IslTypeRef::resolve_type_reference(
                    isl_version,
                    type_reference,
                    type_store,
                    pending_types,
                )?;
                Ok(Constraint::Not(NotConstraint::new(type_id)))
            }
            IslConstraintValue::Type(type_reference) => {
                let type_id = IslTypeRef::resolve_type_reference(
                    isl_version,
                    type_reference,
                    type_store,
                    pending_types,
                )?;
                Ok(Constraint::Type(TypeConstraint::new(type_id)))
            }
            IslConstraintValue::OrderedElements(isl_type_references) => {
                Ok(Constraint::OrderedElements(
                    OrderedElementsConstraint::resolve_from_isl_constraint(
                        isl_version,
                        isl_type_references,
                        type_store,
                        pending_types,
                    )?,
                ))
            }
            IslConstraintValue::Precision(precision_range) => {
                isl_require!(precision_range.lower() != &Limit::Inclusive(0) => "precision range must have non-zero values")?;
                Ok(Constraint::Precision(PrecisionConstraint::new(
                    precision_range.to_owned(),
                )))
            }
            IslConstraintValue::Regex(regex) => Ok(Constraint::Regex(RegexConstraint::from_isl(
                regex,
                isl_version,
            )?)),
            IslConstraintValue::Scale(scale_range) => Ok(Constraint::Scale(ScaleConstraint::new(
                scale_range.to_owned(),
            ))),
            IslConstraintValue::TimestampOffset(timestamp_offset) => {
                Ok(Constraint::TimestampOffset(TimestampOffsetConstraint::new(
                    timestamp_offset.valid_offsets().to_vec(),
                )))
            }
            IslConstraintValue::Exponent(exponent_range) => Ok(Constraint::Exponent(
                ExponentConstraint::new(exponent_range.to_owned()),
            )),
            IslConstraintValue::TimestampPrecision(timestamp_precision_range) => {
                Ok(Constraint::TimestampPrecision(
                    TimestampPrecisionConstraint::new(timestamp_precision_range.to_owned()),
                ))
            }
            IslConstraintValue::Utf8ByteLength(utf8_byte_length) => Ok(Constraint::Utf8ByteLength(
                Utf8ByteLengthConstraint::new(utf8_byte_length.to_owned()),
            )),
            IslConstraintValue::ValidValues(valid_values) => {
                Ok(Constraint::ValidValues(ValidValuesConstraint {
                    valid_values: valid_values.values().to_owned(),
                }))
            }
            IslConstraintValue::Unknown(constraint_name, element) => Ok(Constraint::Unknown(
                constraint_name.to_owned(),
                element.to_owned(),
            )),
        }
    }

    pub fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        match self {
            Constraint::AllOf(all_of) => all_of.validate(value, type_store, ion_path),
            Constraint::Annotations(annotations) => {
                annotations.validate(value, type_store, ion_path)
            }
            Constraint::Annotations2_0(annotations) => {
                annotations.validate(value, type_store, ion_path)
            }
            Constraint::AnyOf(any_of) => any_of.validate(value, type_store, ion_path),
            Constraint::ByteLength(byte_length) => {
                byte_length.validate(value, type_store, ion_path)
            }
            Constraint::CodepointLength(codepoint_length) => {
                codepoint_length.validate(value, type_store, ion_path)
            }
            Constraint::Contains(contains) => contains.validate(value, type_store, ion_path),
            Constraint::ContentClosed => {
                // No op
                // `content: closed` does not work as a constraint by its own, it needs to be used with other container constraints
                // e.g. `fields`
                // the validation for `content: closed` is done within these other constraints
                Ok(())
            }
            Constraint::ContainerLength(container_length) => {
                container_length.validate(value, type_store, ion_path)
            }
            Constraint::Element(element) => element.validate(value, type_store, ion_path),
            Constraint::FieldNames(field_names) => {
                field_names.validate(value, type_store, ion_path)
            }
            Constraint::Fields(fields) => fields.validate(value, type_store, ion_path),
            Constraint::Ieee754Float(ieee754_float) => {
                ieee754_float.validate(value, type_store, ion_path)
            }
            Constraint::Not(not) => not.validate(value, type_store, ion_path),
            Constraint::OneOf(one_of) => one_of.validate(value, type_store, ion_path),
            Constraint::Type(type_constraint) => {
                type_constraint.validate(value, type_store, ion_path)
            }
            Constraint::OrderedElements(ordered_elements) => {
                ordered_elements.validate(value, type_store, ion_path)
            }
            Constraint::Precision(precision) => precision.validate(value, type_store, ion_path),
            Constraint::Regex(regex) => regex.validate(value, type_store, ion_path),
            Constraint::Scale(scale) => scale.validate(value, type_store, ion_path),
            Constraint::Exponent(exponent) => exponent.validate(value, type_store, ion_path),
            Constraint::TimestampOffset(timestamp_offset) => {
                timestamp_offset.validate(value, type_store, ion_path)
            }
            Constraint::TimestampPrecision(timestamp_precision) => {
                timestamp_precision.validate(value, type_store, ion_path)
            }
            Constraint::Utf8ByteLength(utf8_byte_length) => {
                utf8_byte_length.validate(value, type_store, ion_path)
            }
            Constraint::ValidValues(valid_values) => {
                valid_values.validate(value, type_store, ion_path)
            }
            Constraint::Unknown(_, _) => {
                // No op
                // `Unknown` represents open content which can be ignored for validation
                Ok(())
            }
        }
    }
}

/// Implements an `all_of` constraint of Ion Schema
/// [all_of]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#all_of
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AllOfConstraint {
    type_references: Vec<TypeReference>,
}

impl AllOfConstraint {
    pub fn new(type_references: Vec<TypeReference>) -> Self {
        Self { type_references }
    }
}

impl ConstraintValidator for AllOfConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        let mut violations: Vec<Violation> = vec![];
        let mut valid_types = vec![];
        for type_reference in &self.type_references {
            match type_reference.validate(value, type_store, ion_path) {
                Ok(_) => valid_types.push(type_reference.type_id()),
                Err(violation) => violations.push(violation),
            }
        }
        if !violations.is_empty() {
            return Err(Violation::with_violations(
                "all_of",
                ViolationCode::AllTypesNotMatched,
                format!(
                    "value matches {} types, expected {}",
                    valid_types.len(),
                    self.type_references.len()
                ),
                ion_path,
                violations,
            ));
        }
        Ok(())
    }
}

/// Implements an `any_of` constraint of Ion Schema
/// [any_of]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#any_of
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnyOfConstraint {
    type_references: Vec<TypeReference>,
}

impl AnyOfConstraint {
    pub fn new(type_references: Vec<TypeReference>) -> Self {
        Self { type_references }
    }
}

impl ConstraintValidator for AnyOfConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        let mut violations: Vec<Violation> = vec![];
        let mut valid_types = vec![];
        for type_reference in &self.type_references {
            match type_reference.validate(value, type_store, ion_path) {
                Ok(_) => valid_types.push(type_reference.type_id()),
                Err(violation) => violations.push(violation),
            }
        }
        let total_valid_types = valid_types.len();
        if total_valid_types == 0 {
            return Err(Violation::with_violations(
                "any_of",
                ViolationCode::NoTypesMatched,
                "value matches none of the types",
                ion_path,
                violations,
            ));
        }
        Ok(())
    }
}

/// Implements an `one_of` constraint of Ion Schema
/// [one_of]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#one_of
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OneOfConstraint {
    type_references: Vec<TypeReference>,
}

impl OneOfConstraint {
    pub fn new(type_references: Vec<TypeReference>) -> Self {
        Self { type_references }
    }
}

impl ConstraintValidator for OneOfConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        let mut violations: Vec<Violation> = vec![];
        let mut valid_types = vec![];
        for type_reference in &self.type_references {
            match type_reference.validate(value, type_store, ion_path) {
                Ok(_) => valid_types.push(type_reference.type_id()),
                Err(violation) => violations.push(violation),
            }
        }
        let total_valid_types = valid_types.len();
        match total_valid_types {
            0 => Err(Violation::with_violations(
                "one_of",
                ViolationCode::NoTypesMatched,
                "value matches none of the types",
                ion_path,
                violations,
            )),
            1 => Ok(()),
            _ => Err(Violation::with_violations(
                "one_of",
                ViolationCode::MoreThanOneTypeMatched,
                format!("value matches {total_valid_types} types, expected 1"),
                ion_path,
                violations,
            )),
        }
    }
}

/// Implements a `not` constraint
/// [type]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#not
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NotConstraint {
    type_reference: TypeReference,
}

impl NotConstraint {
    pub fn new(type_reference: TypeReference) -> Self {
        Self { type_reference }
    }
}

impl ConstraintValidator for NotConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        let violation = self.type_reference.validate(value, type_store, ion_path);
        match violation {
            Err(violation) => Ok(()),
            Ok(_) => {
                // if there were no violations for the types then not constraint was unsatisfied
                Err(Violation::new(
                    "not",
                    ViolationCode::TypeMatched,
                    "value unexpectedly matches type",
                    ion_path,
                ))
            }
        }
    }
}

/// Implements a `type` constraint
/// [type]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#type
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TypeConstraint {
    pub(crate) type_reference: TypeReference,
}

impl TypeConstraint {
    pub fn new(type_reference: TypeReference) -> Self {
        Self { type_reference }
    }
}

impl ConstraintValidator for TypeConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        self.type_reference.validate(value, type_store, ion_path)
    }
}

/// Implements an `ordered_elements` constraint of Ion Schema
/// [ordered_elements]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#ordered_elements
#[derive(Debug, Clone, PartialEq)]
pub struct OrderedElementsConstraint {
    nfa: OrderedElementsNfa,
}

impl OrderedElementsConstraint {
    pub fn new(type_references: Vec<VariablyOccurringTypeRef>) -> Self {
        let states: Vec<_> = type_references
            .into_iter()
            // TODO: See if we can potentially add a more informative description.
            .map(|ty| (ty, None))
            .collect();
        OrderedElementsConstraint {
            nfa: OrderedElementsNfa::new(states),
        }
    }

    fn resolve_from_isl_constraint(
        isl_version: IslVersion,
        type_references: &[IslVariablyOccurringTypeRef],
        type_store: &mut TypeStore,
        pending_types: &mut PendingTypes,
    ) -> IonSchemaResult<Self> {
        let resolved_types = type_references
            .iter()
            .map(|t| {
                // resolve type references and create variably occurring type reference with occurs range
                let var_type_ref = t.resolve_type_reference(isl_version, type_store, pending_types);
                // TODO: See if we can potentially add a more informative description.
                var_type_ref.map(|it| (it, None))
            })
            .collect::<IonSchemaResult<Vec<_>>>()?;

        Ok(OrderedElementsConstraint {
            nfa: OrderedElementsNfa::new(resolved_types),
        })
    }
}

impl ConstraintValidator for OrderedElementsConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        let violations: Vec<Violation> = vec![];

        let element_iter = match value.as_sequence_iter() {
            Some(iter) => iter,
            None => {
                return Err(Violation::with_violations(
                    "ordered_elements",
                    ViolationCode::TypeMismatched,
                    format!(
                        "expected list, sexp, or document; found {}",
                        if value.is_null() {
                            format!("{value}")
                        } else {
                            format!("{}", value.ion_schema_type())
                        }
                    ),
                    ion_path,
                    violations,
                ));
            }
        };

        self.nfa.matches(element_iter, type_store, ion_path)
    }
}

/// Implements an `fields` constraint of Ion Schema
/// [fields]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#fields
#[derive(Debug, Clone, PartialEq)]
pub struct FieldsConstraint {
    fields: HashMap<String, VariablyOccurringTypeRef>,
    open_content: bool,
}

impl FieldsConstraint {
    pub fn new(fields: HashMap<String, VariablyOccurringTypeRef>, open_content: bool) -> Self {
        Self {
            fields,
            open_content,
        }
    }

    /// Provides boolean value indicating whether open content is allowed or not for the fields
    pub fn open_content(&self) -> bool {
        self.open_content
    }

    /// Tries to create an [Fields] constraint from the given Element
    fn resolve_from_isl_constraint(
        isl_version: IslVersion,
        fields: &HashMap<String, IslVariablyOccurringTypeRef>,
        type_store: &mut TypeStore,
        pending_types: &mut PendingTypes,
        open_content: bool, // Indicates if open content is allowed or not for the fields in the container
    ) -> IonSchemaResult<Self> {
        let resolved_fields: HashMap<String, VariablyOccurringTypeRef> = fields
            .iter()
            .map(|(f, t)| {
                // resolve type references and create variably occurring type reference with occurs range
                // default `occurs` field value for `fields` constraint is `occurs: optional` or `occurs: range::[0, 1]`
                t.resolve_type_reference(isl_version, type_store, pending_types)
                    .map(|variably_occurring_type_ref| (f.to_owned(), variably_occurring_type_ref))
            })
            .collect::<IonSchemaResult<HashMap<String, VariablyOccurringTypeRef>>>()?;
        Ok(FieldsConstraint::new(resolved_fields, open_content))
    }
}

impl ConstraintValidator for FieldsConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        let mut violations: Vec<Violation> = vec![];

        // get struct value
        let ion_struct = value
            .expect_element_of_type(&[IonType::Struct], "fields", ion_path)?
            .as_struct()
            .unwrap();

        // Verify if open content exists in the struct fields
        if !self.open_content() {
            for (field_name, value) in ion_struct.iter() {
                if !self.fields.contains_key(field_name.text().unwrap()) {
                    violations.push(Violation::new(
                        "fields",
                        ViolationCode::InvalidOpenContent,
                        format!("Found open content in the struct: {field_name}: {value}"),
                        ion_path,
                    ));
                }
            }
        }

        // get the values corresponding to the field_name and perform occurs_validation based on the type_def
        for (field_name, variably_occurring_type_ref) in &self.fields {
            let type_reference = variably_occurring_type_ref.type_ref();
            let values: Vec<&Element> = ion_struct.get_all(field_name).collect();

            // add parent value for current field in ion path
            ion_path.push(IonPathElement::Field(field_name.to_owned()));

            // perform occurs validation for type_def for all values of the given field_name
            let occurs_range: &UsizeRange = variably_occurring_type_ref.occurs_range();

            // verify if values follow occurs_range constraint
            if !occurs_range.contains(&values.len()) {
                violations.push(Violation::new(
                    "fields",
                    ViolationCode::TypeMismatched,
                    format!(
                        "Expected {} of field {}: found {}",
                        occurs_range,
                        field_name,
                        values.len()
                    ),
                    ion_path,
                ));
            }

            // verify if all the values for this field name are valid according to type_def
            for value in values {
                let schema_element: IonSchemaElement = value.into();
                if let Err(violation) =
                    type_reference.validate(&schema_element, type_store, ion_path)
                {
                    violations.push(violation);
                }
            }

            // remove current field from list of parents
            ion_path.pop();
        }

        // return error if there were any violation found during validation
        if !violations.is_empty() {
            return Err(Violation::with_violations(
                "fields",
                ViolationCode::FieldsNotMatched,
                "value didn't satisfy fields constraint",
                ion_path,
                violations,
            ));
        }
        Ok(())
    }
}

/// Implements an `field_names` constraint of Ion Schema
/// [field_names]: https://amazon-ion.github.io/ion-schema/docs/isl-2-0/spec#field_names
#[derive(Debug, Clone, PartialEq)]
pub struct FieldNamesConstraint {
    type_reference: TypeReference,
    requires_distinct: bool,
}

impl FieldNamesConstraint {
    pub fn new(type_reference: TypeReference, requires_distinct: bool) -> Self {
        Self {
            type_reference,
            requires_distinct,
        }
    }
}

impl ConstraintValidator for FieldNamesConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        let mut violations: Vec<Violation> = vec![];

        // create a set for checking duplicate field names
        let mut field_name_set = HashSet::new();

        let ion_struct = value
            .expect_element_of_type(&[IonType::Struct], "field_names", ion_path)?
            .as_struct()
            .unwrap();

        for (field_name, _) in ion_struct.iter() {
            ion_path.push(IonPathElement::Field(field_name.text().unwrap().to_owned()));
            let field_name_symbol_as_element = Element::symbol(field_name);
            let schema_element: IonSchemaElement = (&field_name_symbol_as_element).into();

            if let Err(violation) =
                self.type_reference
                    .validate(&schema_element, type_store, ion_path)
            {
                violations.push(violation);
            }
            if self.requires_distinct && !field_name_set.insert(field_name.text().unwrap()) {
                violations.push(Violation::new(
                    "field_names",
                    ViolationCode::FieldNamesNotDistinct,
                    format!(
                        "expected distinct field names but found duplicate field name {field_name}",
                    ),
                    ion_path,
                ))
            }
            ion_path.pop();
        }

        if !violations.is_empty() {
            return Err(Violation::with_violations(
                "field_names",
                ViolationCode::FieldNamesMismatched,
                "one or more field names don't satisfy field_names constraint",
                ion_path,
                violations,
            ));
        }
        Ok(())
    }
}

/// Implements Ion Schema's `contains` constraint
/// [contains]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#contains
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContainsConstraint {
    // TODO: convert this into a HashSet once we have an implementation of Hash for Element in ion-rust
    // Reference ion-rust issue: https://github.com/amazon-ion/ion-rust/issues/220
    values: Vec<Element>,
}

impl ContainsConstraint {
    pub fn new(values: Vec<Element>) -> Self {
        Self { values }
    }
}

impl ConstraintValidator for ContainsConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        let values: Vec<IonData<&Element>> = if let Some(element_iter) = value.as_sequence_iter() {
            element_iter.map(IonData::from).collect()
        } else if let Some(strukt) = value.as_struct() {
            strukt.fields().map(|(k, v)| v).map(IonData::from).collect()
        } else {
            return Err(Violation::new(
                "contains",
                ViolationCode::TypeMismatched,
                format!(
                    "expected list/sexp/struct/document found {}",
                    if value.is_null() {
                        format!("{value}")
                    } else {
                        format!("{}", value.ion_schema_type())
                    }
                ),
                ion_path,
            ));
        };

        // add all the missing values found during validation
        let mut missing_values = vec![];

        // for each value in expected values if it does not exist in ion sequence
        // then add it to missing_values to keep track of missing values
        for expected_value in self.values.iter() {
            let expected = expected_value.into();
            if !values.contains(&expected) {
                missing_values.push(expected_value);
            }
        }

        // return Violation if there were any values added to the missing values vector
        if !missing_values.is_empty() {
            return Err(Violation::new(
                "contains",
                ViolationCode::MissingValue,
                format!("{value} has missing value(s): {missing_values:?}"),
                ion_path,
            ));
        }

        Ok(())
    }
}

/// Implements an `container_length` constraint of Ion Schema
/// [container_length]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#container_length
#[derive(Debug, Clone, PartialEq)]
pub struct ContainerLengthConstraint {
    length_range: UsizeRange,
}

impl ContainerLengthConstraint {
    pub fn new(length_range: UsizeRange) -> Self {
        Self { length_range }
    }

    pub fn length(&self) -> &UsizeRange {
        &self.length_range
    }
}

impl ConstraintValidator for ContainerLengthConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        // get the size of given value container
        let size = if let Some(element_iter) = value.as_sequence_iter() {
            element_iter.count()
        } else if let Some(strukt) = value.as_struct() {
            strukt.fields().map(|(k, v)| v).count()
        } else {
            return Err(Violation::new(
                "container_length",
                ViolationCode::TypeMismatched,
                if value.is_null() {
                    format!("expected a container found {value}")
                } else {
                    format!(
                        "expected a container (a list/sexp/struct) but found {}",
                        value.ion_schema_type()
                    )
                },
                ion_path,
            ));
        };

        // get isl length as a range
        let length_range: &UsizeRange = self.length();

        // return a Violation if the container size didn't follow container_length constraint
        if !length_range.contains(&size) {
            return Err(Violation::new(
                "container_length",
                ViolationCode::InvalidLength,
                format!("expected container length {length_range} found {size}"),
                ion_path,
            ));
        }

        Ok(())
    }
}

/// Implements Ion Schema's `byte_length` constraint
/// [byte_length]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#byte_length
#[derive(Debug, Clone, PartialEq)]
pub struct ByteLengthConstraint {
    length_range: UsizeRange,
}

impl ByteLengthConstraint {
    pub fn new(length_range: UsizeRange) -> Self {
        Self { length_range }
    }

    pub fn length(&self) -> &UsizeRange {
        &self.length_range
    }
}

impl ConstraintValidator for ByteLengthConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        // get the size of given bytes
        let size = value
            .expect_element_of_type(&[IonType::Blob, IonType::Clob], "byte_length", ion_path)?
            .as_lob()
            .unwrap()
            .len();

        // get isl length as a range
        let length_range: &UsizeRange = self.length();

        // return a Violation if the clob/blob size didn't follow byte_length constraint
        if !length_range.contains(&size) {
            return Err(Violation::new(
                "byte_length",
                ViolationCode::InvalidLength,
                format!("expected byte length {length_range} found {size}"),
                ion_path,
            ));
        }

        Ok(())
    }
}

/// Implements an `codepoint_length` constraint of Ion Schema
/// [codepoint_length]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#codepoint_length
#[derive(Debug, Clone, PartialEq)]
pub struct CodepointLengthConstraint {
    length_range: UsizeRange,
}

impl CodepointLengthConstraint {
    pub fn new(length_range: UsizeRange) -> Self {
        Self { length_range }
    }

    pub fn length(&self) -> &UsizeRange {
        &self.length_range
    }
}

impl ConstraintValidator for CodepointLengthConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        // get the size of given string/symbol Unicode codepoints
        let size = value
            .expect_element_of_type(
                &[IonType::String, IonType::Symbol],
                "codepoint_length",
                ion_path,
            )?
            .as_text()
            .unwrap()
            .chars()
            .count();

        // get isl length as a range
        let length_range: &UsizeRange = self.length();

        // return a Violation if the string/symbol codepoint size didn't follow codepoint_length constraint
        if !length_range.contains(&size) {
            return Err(Violation::new(
                "codepoint_length",
                ViolationCode::InvalidLength,
                format!("expected codepoint length {length_range} found {size}"),
                ion_path,
            ));
        }

        Ok(())
    }
}

/// Implements the `element` constraint
/// [element]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#element
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ElementConstraint {
    type_reference: TypeReference,
    /// This field is used for ISL 2.0 and it represents whether validation for distinct elements is required or not.
    /// For ISL 1.0 this is always false as it doesn't support distinct elements validation.
    required_distinct_elements: bool,
}

impl ElementConstraint {
    pub fn new(type_reference: TypeReference, required_distinct_elements: bool) -> Self {
        Self {
            type_reference,
            required_distinct_elements,
        }
    }
}

impl ConstraintValidator for ElementConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        let mut violations: Vec<Violation> = vec![];

        // create a set for checking duplicate elements
        let mut element_set = vec![];

        // get elements for given container in the form (ion_path_element, element_value)
        let elements: Vec<(IonPathElement, &Element)> =
            if let Some(element_iter) = value.as_sequence_iter() {
                element_iter
                    .enumerate()
                    .map(|(index, val)| (IonPathElement::Index(index), val))
                    .collect()
            } else if let Some(strukt) = value.as_struct() {
                strukt
                    .fields()
                    .map(|(name, val)| (IonPathElement::Field(name.to_string()), val))
                    .collect()
            } else {
                // Check for null container
                if value.is_null() {
                    return Err(Violation::new(
                        "element",
                        ViolationCode::TypeMismatched,
                        format!("expected a container but found {value}"),
                        ion_path,
                    ));
                }
                // return Violation if value is not an Ion container
                return Err(Violation::new(
                    "element",
                    ViolationCode::TypeMismatched,
                    format!(
                        "expected a container (a list/sexp/struct) but found {}",
                        value.ion_schema_type()
                    ),
                    ion_path,
                ));
            };

        // validate element constraint
        for (ion_path_element, val) in elements {
            ion_path.push(ion_path_element);
            let schema_element: IonSchemaElement = val.into();

            if let Err(violation) =
                self.type_reference
                    .validate(&schema_element, type_store, ion_path)
            {
                violations.push(violation);
            }
            if self.required_distinct_elements && element_set.contains(&val) {
                violations.push(Violation::new(
                    "element",
                    ViolationCode::ElementNotDistinct,
                    format!("expected distinct elements but found duplicate element {val}",),
                    ion_path,
                ))
            }
            element_set.push(val);
            ion_path.pop();
        }

        if !violations.is_empty() {
            return Err(Violation::with_violations(
                "element",
                ViolationCode::ElementMismatched,
                "one or more elements don't satisfy element constraint",
                ion_path,
                violations,
            ));
        }
        Ok(())
    }
}

/// Implements the `annotations` constraint
/// [annotations]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#annotations
// This is used for both simple and standard syntax of annotations constraint.
// The simple syntax will be converted to a standard syntax for removing complexity in the validation logic.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnnotationsConstraint2_0 {
    type_ref: TypeReference,
}

impl AnnotationsConstraint2_0 {
    pub fn new(type_ref: TypeReference) -> Self {
        Self { type_ref }
    }
}

impl ConstraintValidator for AnnotationsConstraint2_0 {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        if let Some(element) = value.as_element() {
            let annotations: Vec<Element> =
                element.annotations().iter().map(Element::symbol).collect();
            let annotations_element: Element = ion_rs::Value::List(annotations.into()).into();
            let annotations_ion_schema_element = IonSchemaElement::from(&annotations_element);

            self.type_ref
                .validate(&annotations_ion_schema_element, type_store, ion_path)
                .map_err(|v| {
                    Violation::with_violations(
                        "annotations",
                        ViolationCode::AnnotationMismatched,
                        "one or more annotations don't satisfy annotations constraint",
                        ion_path,
                        vec![v],
                    )
                })
        } else {
            // document type can not have annotations
            Err(Violation::new(
                "annotations",
                ViolationCode::AnnotationMismatched,
                "annotations constraint is not applicable for document type",
                ion_path,
            ))
        }
    }
}

/// Implements the `annotations` constraint
/// [annotations]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#annotations
// The `required` annotation provided on the list of annotations is not represented here,
// requirement of an annotation is represented in the annotation itself by the field `is_required` of `Annotation` struct.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnnotationsConstraint {
    is_closed: bool,
    is_ordered: bool,
    annotations: Vec<Annotation>,
}

impl AnnotationsConstraint {
    pub fn new(is_closed: bool, is_ordered: bool, annotations: Vec<Annotation>) -> Self {
        Self {
            is_closed,
            is_ordered,
            annotations,
        }
    }

    // Find the required expected annotation from value annotations
    // This is a helper method used by validate_ordered_annotations
    pub fn find_expected_annotation<'a, I: Iterator<Item = &'a str>>(
        &self,
        value_annotations: &mut Peekable<I>,
        expected_annotation: &Annotation,
    ) -> bool {
        // As there are open content possible for annotations that doesn't have list-level `closed` annotation
        // traverse through the next annotations to find this expected, ordered and required annotation
        while Option::is_some(&value_annotations.peek()) && !self.is_closed {
            if expected_annotation.value() == value_annotations.next().unwrap() {
                return true;
            }
        }

        // if we didn't find the expected annotation return false
        false
    }

    pub fn validate_ordered_annotations(
        &self,
        value: &Element,
        type_store: &TypeStore,
        violations: Vec<Violation>,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        let mut value_annotations = value
            .annotations()
            .iter()
            .map(|sym| sym.text().unwrap())
            .peekable();

        // iterate over the expected annotations and see if there are any unexpected value annotations found
        for expected_annotation in &self.annotations {
            if let Some(actual_annotation) = value_annotations.peek() {
                if expected_annotation.is_required()
                    && expected_annotation.value() != actual_annotation
                {
                    // iterate over the actual value annotations to find the required expected annotation
                    if !self.find_expected_annotation(&mut value_annotations, expected_annotation) {
                        // missing required expected annotation
                        return Err(Violation::new(
                            "annotations",
                            ViolationCode::AnnotationMismatched,
                            "annotations don't match expectations",
                            ion_path,
                        ));
                    }
                } else if expected_annotation.value() == actual_annotation {
                    let _ = value_annotations.next(); // consume the annotation if its equal to the expected annotation
                }
            } else if expected_annotation.is_required() {
                // we already exhausted value annotations and didn't find the required expected annotation
                return Err(Violation::new(
                    "annotations",
                    ViolationCode::AnnotationMismatched,
                    "annotations don't match expectations",
                    ion_path,
                ));
            }
        }

        if self.is_closed && Option::is_some(&value_annotations.peek()) {
            // check if there are still annotations left at the end of the list
            return Err(Violation::with_violations(
                "annotations",
                ViolationCode::AnnotationMismatched,
                // unwrap as we already verified with peek that there is a value
                format!(
                    "Unexpected annotations found {}",
                    value_annotations.next().unwrap()
                ),
                ion_path,
                violations,
            ));
        }

        Ok(())
    }

    pub fn validate_unordered_annotations(
        &self,
        value: &Element,
        type_store: &TypeStore,
        violations: Vec<Violation>,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        // This will be used by a violation to to return all the missing annotations
        let mut missing_annotations: Vec<&Annotation> = vec![];

        let value_annotations: Vec<&str> = value
            .annotations()
            .iter()
            .map(|sym| sym.text().unwrap())
            .collect();

        for expected_annotation in &self.annotations {
            // verify if the expected_annotation is required and if it matches with value annotation
            if expected_annotation.is_required()
                && !value.annotations().contains(expected_annotation.value())
            {
                missing_annotations.push(expected_annotation);
            }
        }

        // if missing_annotations is not empty return violation
        if !missing_annotations.is_empty() {
            return Err(Violation::with_violations(
                "annotations",
                ViolationCode::MissingAnnotation,
                format!("missing annotation(s): {missing_annotations:?}"),
                ion_path,
                violations,
            ));
        }

        // if the annotations is annotated with `closed` at list-level then verify
        // there are no unexpected annotations in the value annotations
        if self.is_closed
            && !value_annotations.iter().all(|v| {
                self.annotations
                    .iter()
                    .any(|expected_ann| v == expected_ann.value())
            })
        {
            return Err(Violation::with_violations(
                "annotations",
                ViolationCode::UnexpectedAnnotation,
                "found one or more unexpected annotations",
                ion_path,
                violations,
            ));
        }

        Ok(())
    }
}

impl ConstraintValidator for AnnotationsConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        let violations: Vec<Violation> = vec![];

        if let Some(element) = value.as_element() {
            // validate annotations that have list-level `ordered` annotation
            if self.is_ordered {
                return self
                    .validate_ordered_annotations(element, type_store, violations, ion_path);
            }

            // validate annotations that does not have list-level `ordered` annotation
            self.validate_unordered_annotations(element, type_store, violations, ion_path)
        } else {
            // document type can not have annotations
            Err(Violation::new(
                "annotations",
                ViolationCode::AnnotationMismatched,
                "annotations constraint is not applicable for document type",
                ion_path,
            ))
        }
    }
}

/// Implements Ion Schema's `precision` constraint
/// [precision]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#precision
#[derive(Debug, Clone, PartialEq)]
pub struct PrecisionConstraint {
    precision_range: U64Range,
}

impl PrecisionConstraint {
    pub fn new(precision_range: U64Range) -> Self {
        Self { precision_range }
    }

    pub fn precision(&self) -> &U64Range {
        &self.precision_range
    }
}

impl ConstraintValidator for PrecisionConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        // get precision of decimal value
        let value_precision = value
            .expect_element_of_type(&[IonType::Decimal], "precision", ion_path)?
            .as_decimal()
            .unwrap()
            .precision();

        // get isl decimal precision as a range
        let precision_range: &U64Range = self.precision();

        // return a Violation if the value didn't follow precision constraint
        if !precision_range.contains(&value_precision) {
            return Err(Violation::new(
                "precision",
                ViolationCode::InvalidLength,
                format!("expected precision {precision_range} found {value_precision}"),
                ion_path,
            ));
        }

        Ok(())
    }
}

/// Implements Ion Schema's `scale` constraint
/// [scale]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#scale
#[derive(Debug, Clone, PartialEq)]
pub struct ScaleConstraint {
    scale_range: I64Range,
}

impl ScaleConstraint {
    pub fn new(scale_range: I64Range) -> Self {
        Self { scale_range }
    }

    pub fn scale(&self) -> &I64Range {
        &self.scale_range
    }
}

impl ConstraintValidator for ScaleConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        // get scale of decimal value
        let value_scale = value
            .expect_element_of_type(&[IonType::Decimal], "scale", ion_path)?
            .as_decimal()
            .unwrap()
            .scale();

        // get isl decimal scale as a range
        let scale_range: &I64Range = self.scale();

        // return a Violation if the value didn't follow scale constraint
        if !scale_range.contains(&value_scale) {
            return Err(Violation::new(
                "scale",
                ViolationCode::InvalidLength,
                format!("expected scale {scale_range} found {value_scale}"),
                ion_path,
            ));
        }

        Ok(())
    }
}

/// Implements Ion Schema's `exponent` constraint
/// [exponent]: https://amazon-ion.github.io/ion-schema/docs/isl-2-0/spec#exponent
#[derive(Debug, Clone, PartialEq)]
pub struct ExponentConstraint {
    exponent_range: I64Range,
}

impl ExponentConstraint {
    pub fn new(exponent_range: I64Range) -> Self {
        Self { exponent_range }
    }

    pub fn exponent(&self) -> &I64Range {
        &self.exponent_range
    }
}

impl ConstraintValidator for ExponentConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        // get exponent of decimal value
        let value_exponent = value
            .expect_element_of_type(&[IonType::Decimal], "exponent", ion_path)?
            .as_decimal()
            .unwrap()
            .scale()
            .neg();

        // get isl decimal exponent as a range
        let exponent_range: &I64Range = self.exponent();

        // return a Violation if the value didn't follow exponent constraint
        if !exponent_range.contains(&value_exponent) {
            return Err(Violation::new(
                "exponent",
                ViolationCode::InvalidLength,
                format!("expected exponent {exponent_range} found {value_exponent}"),
                ion_path,
            ));
        }

        Ok(())
    }
}

/// Implements Ion Schema's `timestamp_precision` constraint
/// [timestamp_precision]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#timestamp_precision
#[derive(Debug, Clone, PartialEq)]
pub struct TimestampPrecisionConstraint {
    timestamp_precision_range: TimestampPrecisionRange,
}

impl TimestampPrecisionConstraint {
    pub fn new(scale_range: TimestampPrecisionRange) -> Self {
        Self {
            timestamp_precision_range: scale_range,
        }
    }

    pub fn timestamp_precision(&self) -> &TimestampPrecisionRange {
        &self.timestamp_precision_range
    }
}

impl ConstraintValidator for TimestampPrecisionConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        // get timestamp value
        let timestamp_value = value
            .expect_element_of_type(&[IonType::Timestamp], "timestamp_precision", ion_path)?
            .as_timestamp()
            .unwrap();

        // get isl timestamp precision as a range
        let precision_range: &TimestampPrecisionRange = self.timestamp_precision();
        let precision = &TimestampPrecision::from_timestamp(&timestamp_value);
        // return a Violation if the value didn't follow timestamp precision constraint
        if !precision_range.contains(precision) {
            return Err(Violation::new(
                "precision",
                ViolationCode::InvalidLength,
                format!("expected precision {precision_range} found {precision:?}"),
                ion_path,
            ));
        }

        Ok(())
    }
}

/// Implements Ion Schema's `valid_values` constraint
/// [valid_values]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#valid_values
#[derive(Debug, Clone, PartialEq)]
pub struct ValidValuesConstraint {
    valid_values: Vec<ValidValue>,
}

impl ValidValuesConstraint {
    pub fn new(valid_values: Vec<ValidValue>, isl_version: IslVersion) -> IonSchemaResult<Self> {
        Ok(Self { valid_values })
    }
}

impl Display for ValidValuesConstraint {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(f, "[ ")?;
        let mut itr = self.valid_values.iter();
        if let Some(item) = itr.next() {
            write!(f, "{item}")?;
        }
        for item in itr {
            write!(f, ", {item}")?;
        }
        write!(f, " ]")
    }
}

impl ConstraintValidator for ValidValuesConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        match value.as_element() {
            Some(element) => {
                for valid_value in &self.valid_values {
                    let does_match = match valid_value {
                        ValidValue::Element(valid_value) => {
                            // this comparison uses the Ion equivalence based on Ion specification
                            IonData::eq(valid_value, element.value())
                        }
                        ValidValue::NumberRange(range) => match element.any_number_as_decimal() {
                            Some(d) => range.contains(&d),
                            _ => false,
                        },
                        ValidValue::TimestampRange(range) => {
                            if let Value::Timestamp(t) = element.value() {
                                range.contains(t)
                            } else {
                                false
                            }
                        }
                    };
                    if does_match {
                        return Ok(());
                    }
                }
                Err(Violation::new(
                    "valid_values",
                    ViolationCode::InvalidValue,
                    format!(
                        "expected valid_values to be from {}, found {}",
                        &self, element
                    ),
                    ion_path,
                ))
            }
            _ => Err(Violation::new(
                "valid_values",
                ViolationCode::InvalidValue,
                format!(
                    "expected valid_values to be from {}, found {}",
                    &self, value
                ),
                ion_path,
            )),
        }
    }
}

/// Implements Ion Schema's `regex` constraint
/// [regex]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#regex
#[derive(Debug, Clone)]
pub struct RegexConstraint {
    expression: Regex,
    case_insensitive: bool,
    multiline: bool,
}

impl RegexConstraint {
    fn new(expression: Regex, case_insensitive: bool, multiline: bool) -> Self {
        Self {
            expression,
            case_insensitive,
            multiline,
        }
    }

    fn from_isl(isl_regex: &IslRegexConstraint, isl_version: IslVersion) -> IonSchemaResult<Self> {
        let pattern =
            RegexConstraint::convert_to_pattern(isl_regex.expression().to_owned(), isl_version)?;

        let regex = RegexBuilder::new(pattern.as_str())
            .case_insensitive(isl_regex.case_insensitive())
            .multi_line(isl_regex.multi_line())
            .build()
            .map_err(|e| {
                invalid_schema_error_raw(format!("Invalid regex {}", isl_regex.expression()))
            })?;

        Ok(RegexConstraint::new(
            regex,
            isl_regex.case_insensitive(),
            isl_regex.multi_line(),
        ))
    }

    /// Converts given string to a pattern based on regex features supported by Ion Schema Specification
    /// For more information: `<https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#regex>`
    fn convert_to_pattern(expression: String, isl_version: IslVersion) -> IonSchemaResult<String> {
        let mut sb = String::new();
        let mut si = expression.as_str().chars().peekable();

        while let Some(ch) = si.next() {
            match ch {
                '[' => {
                    // push the starting bracket `[` to the result string
                    // and then parse the next characters using parse_char_class
                    sb.push(ch);
                    RegexConstraint::parse_char_class(&mut sb, &mut si, isl_version)?;
                }
                '(' => {
                    sb.push(ch);
                    if let Some(ch) = si.next() {
                        if ch == '?' {
                            return invalid_schema_error(format!("invalid character {ch}"));
                        }
                        sb.push(ch)
                    }
                }
                '\\' => {
                    if let Some(ch) = si.next() {
                        match ch {
                            // Note: Ion text a backslash must itself be escaped, so correct escaping
                            // of below characters requires two backslashes, e.g.: \\.
                            '.' | '^' | '$' | '|' | '?' | '*' | '+' | '\\' | '[' | ']' | '('
                            | ')' | '{' | '}' | 'w' | 'W' | 'd' | 'D' => {
                                sb.push('\\');
                                sb.push(ch)
                            }
                            's' => sb.push_str("[ \\f\\n\\r\\t]"),
                            'S' => sb.push_str("[^ \\f\\n\\r\\t]"),
                            _ => {
                                return invalid_schema_error(format!(
                                    "invalid escape character {ch}",
                                ))
                            }
                        }
                    }
                }
                // TODO: remove below match statement once we have fixed issue: https://github.com/amazon-ion/ion-rust/issues/399
                '\r' => sb.push('\n'), // Replace '\r' with '\n'
                _ => sb.push(ch),
            }
            RegexConstraint::parse_quantifier(&mut sb, &mut si)?;
        }

        Ok(sb)
    }

    fn parse_char_class(
        sb: &mut String,
        si: &mut Peekable<Chars<'_>>,
        isl_version: IslVersion,
    ) -> IonSchemaResult<()> {
        while let Some(ch) = si.next() {
            sb.push(ch);
            match ch {
                '&' => {
                    if si.peek() == Some(&'&') {
                        return invalid_schema_error("'&&' is not supported in a character class");
                    }
                }
                '[' => return invalid_schema_error("'[' must be escaped within a character class"),
                '\\' => {
                    if let Some(ch2) = si.next() {
                        match ch2 {
                            // escaped `[` or ']' are allowed within character class
                            '[' | ']' | '\\' => sb.push(ch2),
                            'd' | 's' | 'w' | 'D' | 'S' | 'W' => {
                                match isl_version {
                                    IslVersion::V1_0 => {
                                        // returns an error for ISL 1.0 as it does not support pre-defined char classes (i.e., \d, \s, \w)
                                        return invalid_schema_error(format!(
                                            "invalid sequence '{:?}' in character class",
                                            si
                                        ));
                                    }
                                    IslVersion::V2_0 => {
                                        // Change \w and \W to be [a-zA-Z0-9_] and [^a-zA-Z0-9_] respectively
                                        // Since `regex` supports unicode perl style character classes,
                                        // i.e. \w is represented as (\p{Alphabetic} + \p{M} + \d + \p{Pc} + \p{Join_Control})
                                        if ch2 == 'w' {
                                            sb.pop();
                                            sb.push_str(r"[a-zA-Z0-9_]");
                                        } else if ch2 == 'W' {
                                            sb.pop();
                                            sb.push_str(r"[^a-zA-Z0-9_]");
                                        } else {
                                            sb.push(ch2);
                                        }
                                    }
                                }
                            }
                            _ => {
                                return invalid_schema_error(format!(
                                    "invalid sequence '\\{ch2}' in character class"
                                ))
                            }
                        }
                    }
                }
                ']' => return Ok(()),
                _ => {}
            }
        }

        invalid_schema_error("character class missing ']'")
    }

    fn parse_quantifier(sb: &mut String, si: &mut Peekable<Chars<'_>>) -> IonSchemaResult<()> {
        let initial_length = sb.len();
        if let Some(ch) = si.peek().cloned() {
            match ch {
                '?' | '*' | '+' => {
                    if let Some(ch) = si.next() {
                        sb.push(ch);
                    }
                }
                '{' => {
                    // we know next is `{` so unwrap it and add it to the result string
                    let ch = si.next().unwrap();
                    sb.push(ch);
                    // process occurrences specified within `{` and `}`
                    let mut complete = false;
                    for ch in si.by_ref() {
                        match ch {
                            '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | ',' => {
                                sb.push(ch)
                            }
                            '}' => {
                                sb.push(ch);
                                // at this point occurrences are completely specified
                                complete = true;
                                break;
                            }
                            _ => return invalid_schema_error(format!("invalid character {ch}")),
                        }
                    }

                    if !complete {
                        return invalid_schema_error("range quantifier missing '}'");
                    }
                }
                _ => {}
            }
            if sb.len() > initial_length {
                if let Some(ch) = si.peek().cloned() {
                    match ch {
                        '?' => return invalid_schema_error(format!("invalid character {ch}")),

                        '+' => return invalid_schema_error(format!("invalid character {ch}")),
                        _ => {}
                    }
                }
            }
        }

        Ok(())
    }
}

impl ConstraintValidator for RegexConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        // get string value and return violation if its not a string or symbol type
        let string_value = value
            .expect_element_of_type(&[IonType::String, IonType::Symbol], "regex", ion_path)?
            .as_text()
            .unwrap();

        // create regular expression
        let re = Regex::new(r"\r").unwrap();
        let result = re.replace_all(string_value, "\n");
        let value = result.to_string();

        // verify if given value matches regular expression
        if !self.expression.is_match(value.as_str()) {
            return Err(Violation::new(
                "regex",
                ViolationCode::RegexMismatched,
                format!("{} doesn't match regex {}", value, self.expression),
                ion_path,
            ));
        }

        Ok(())
    }
}

impl PartialEq for RegexConstraint {
    fn eq(&self, other: &Self) -> bool {
        self.expression.as_str().eq(other.expression.as_str())
            && self.case_insensitive == other.case_insensitive
            && self.multiline == other.multiline
    }
}

/// Implements Ion Schema's `utf8_byte_length` constraint
/// [utf8_byte_length]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#utf8_byte_length
#[derive(Debug, Clone, PartialEq)]
pub struct Utf8ByteLengthConstraint {
    length_range: UsizeRange,
}

impl Utf8ByteLengthConstraint {
    pub fn new(length_range: UsizeRange) -> Self {
        Self { length_range }
    }

    pub fn length(&self) -> &UsizeRange {
        &self.length_range
    }
}

impl ConstraintValidator for Utf8ByteLengthConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        // get the size of given bytes
        let size = value
            .expect_element_of_type(
                &[IonType::String, IonType::Symbol],
                "utf8_byte_length",
                ion_path,
            )?
            .as_text()
            .unwrap()
            .len();

        // get isl length as a range
        let length_range: &UsizeRange = self.length();

        // return a Violation if the string/symbol size didn't follow utf8_byte_length constraint
        if !length_range.contains(&size) {
            return Err(Violation::new(
                "utf8_byte_length",
                ViolationCode::InvalidLength,
                format!("expected utf8 byte length {length_range} found {size}"),
                ion_path,
            ));
        }

        Ok(())
    }
}

/// Implements Ion Schema's `timestamp_offset` constraint
/// [timestamp_offset]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#timestamp_offset
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimestampOffsetConstraint {
    valid_offsets: Vec<TimestampOffset>,
}

impl TimestampOffsetConstraint {
    pub fn new(valid_offsets: Vec<TimestampOffset>) -> Self {
        Self { valid_offsets }
    }

    pub fn valid_offsets(&self) -> &Vec<TimestampOffset> {
        &self.valid_offsets
    }
}

impl ConstraintValidator for TimestampOffsetConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        // get timestamp value
        let timestamp_value = value
            .expect_element_of_type(&[IonType::Timestamp], "timestamp_offset", ion_path)?
            .as_timestamp()
            .unwrap();

        // get isl timestamp precision as a range
        let valid_offsets: &Vec<TimestampOffset> = self.valid_offsets();

        // return a Violation if the value didn't follow timestamp precision constraint
        if !valid_offsets.contains(&timestamp_value.offset().into()) {
            let formatted_valid_offsets: Vec<String> =
                valid_offsets.iter().map(|t| format!("{t}")).collect();

            return Err(Violation::new(
                "timestamp_offset",
                ViolationCode::InvalidLength,
                format!(
                    "expected timestamp offset from {:?} found {}",
                    formatted_valid_offsets,
                    <Option<i32> as Into<TimestampOffset>>::into(timestamp_value.offset())
                ),
                ion_path,
            ));
        }

        Ok(())
    }
}

/// Implements Ion Schema's `ieee754_float` constraint
/// [ieee754_float]: https://amazon-ion.github.io/ion-schema/docs/isl-2-0/spec#ieee754_float
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Ieee754FloatConstraint {
    interchange_format: Ieee754InterchangeFormat,
}

impl Ieee754FloatConstraint {
    pub fn new(interchange_format: Ieee754InterchangeFormat) -> Self {
        Self { interchange_format }
    }

    pub fn interchange_format(&self) -> Ieee754InterchangeFormat {
        self.interchange_format
    }
}

impl ConstraintValidator for Ieee754FloatConstraint {
    fn validate(
        &self,
        value: &IonSchemaElement,
        type_store: &TypeStore,
        ion_path: &mut IonPath,
    ) -> ValidationResult {
        // get ieee interchange format value
        let float_value = value
            .expect_element_of_type(&[IonType::Float], "ieee754_float", ion_path)?
            .as_float()
            .unwrap();

        if !float_value.is_finite() {
            return Ok(());
        }

        let is_valid = match self.interchange_format {
            Ieee754InterchangeFormat::Binary16 => {
                half::f16::from_f64(float_value).to_f64() == float_value
            }
            Ieee754InterchangeFormat::Binary32 => float_value
                .to_f32()
                .and_then(|f32_value| f32_value.to_f64().map(|f64_value| f64_value == float_value))
                .unwrap_or(false),
            Ieee754InterchangeFormat::Binary64 => true,
        };

        if is_valid {
            Ok(())
        } else {
            Err(Violation::new(
                "ieee754_float",
                ViolationCode::InvalidIeee754Float,
                format!(
                    "value cannot be losslessly represented by the IEEE-754 {} interchange format.",
                    self.interchange_format
                ),
                ion_path,
            ))
        }
    }
}