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 2301 2302 2303 2304 2305 2306 2307
//! Provides functions for getting instances of [`Schema`] using [`SchemaSystem`].
//!
//! ## Example:
//! In general, users will create one or more authorities and use them to build the [`SchemaSystem`].
//! Then this [`SchemaSystem`] is used to create instances of [`Schema`].
//!
//! ```
//! use ion_schema::authority::{MapDocumentAuthority, FileSystemDocumentAuthority, DocumentAuthority};
//! use ion_schema::system::SchemaSystem;
//! use std::path::Path;
//!
//! // create a vector of authorities and construct schema system
//! let authorities: Vec<Box<dyn DocumentAuthority>> = vec![Box::new(
//! FileSystemDocumentAuthority::new(Path::new("schemas")),
//! )];
//! let mut schema_system = SchemaSystem::new(authorities);
//!
//! // use this schema_system to load a schema as following
//! let schema = schema_system.load_schema("sample.isl");
//! ```
use crate::authority::DocumentAuthority;
use crate::isl::isl_import::{IslImport, IslImportType};
use crate::isl::isl_type::IslType;
use crate::isl::{IslSchema, IslVersion};
use crate::result::{
invalid_schema_error, invalid_schema_error_raw, unresolvable_schema_error,
unresolvable_schema_error_raw, IonSchemaError, IonSchemaResult,
};
use crate::schema::Schema;
use crate::types::{BuiltInTypeDefinition, Nullability, TypeDefinitionImpl, TypeDefinitionKind};
use crate::{is_isl_version_marker, is_reserved_word, UserReservedFields};
use ion_rs::element::{Annotations, Element};
use ion_rs::IonType;
use std::collections::{HashMap, HashSet};
use std::io::ErrorKind;
use std::sync::Arc;
// TODO: Shift PendingTypes and TypeStore implementations to a separate module
/// Stores information about types that are in the process of being defined.
///
/// An ISL type definition can include types that are not yet fully defined.
/// For example, an ISL type definition might include:
/// * A reference to itself. This could happen in a recursive structure like a
/// linked list or binary tree.
/// * A nested anonymous type definition.
/// * A reference to type definition that is followed by current type definition. These type references
/// will be deferred to later check if a type definition with that name exists in the schema.
/// Because the [`SchemaSystem`] does not yet know the complete definition
/// of these types, it cannot find them in the [`TypeStore`].
/// An instance of [`PendingTypes`] is used to track information about types
/// that we do not have a complete definition for yet. When the
/// [`SchemaSystem`] finishes loading these types, the type definitions in
/// [`PendingTypes`] can be promoted the [`TypeStore`].
///
/// Deferred type definition:
/// A deferred type definition is added to [`PendingTypes`] whenever encountered type reference whose definition
/// is outside the scope of current type definition that is being resolved.
/// e.g.
/// type:: {
/// name: foo,
/// type: bar,
/// }
/// type:: {
/// name: bar,
/// type: int
/// }
///
/// For above example, `bar` will be saved as deferred type definition until we resolve the definition of `bar`.
/// When the [`SchemaSystem`] finishes loading the type `foo`, the type definitions in
/// [`PendingTypes`] including deferred type definitions will be promoted to the [`TypeStore`].
/// Once we resolve type definition for `bar` it will be updated in the [`TypeStore`].
#[derive(Debug, Clone, Default)]
pub struct PendingTypes {
builtin_type_ids_by_name: HashMap<String, TypeId>,
ids_by_name: HashMap<String, TypeId>,
parent: Option<(String, TypeId)>,
types_by_id: Vec<Option<TypeDefinitionKind>>, // a None in this vector represents a not-yet-resolved type
}
impl PendingTypes {
/// Adds all the types from PendingTypes into given [`TypeStore`] including adding all the imported types into imports of [`TypeStore`].
/// It also clears [`PendingTypes`] types for loading next set of types.
/// This method is used after a schema named type/root type is loaded entirely into [`PendingTypes`]
/// * `type_store` - The TypeStore which will be updated with the types within this PendingType
/// * `load_isl_import` - If this argument is Some(isl_import), then we are not within an import process of schema.
/// Based on given enum variant isl_import we will add the types to type_store.
/// Otherwise we will add all the types from this PendingTypes to TypeStore.
/// * `isl_type_names` - The isl type names defined within the schema. This will be used to determine
/// if a type definition actually exists within the schema. If a type definition from this list
/// exists in [`PendingTypes`] it would have been added as a deferred type definition.
/// This deferred type will be loaded into [`TypeStore`] as it is and will be replaced with a type definition
/// once it is resolved.
/// Returns true, if this update is not for an isl import type or it is for an isl import type but it is added to the type_store
/// Otherwise, returns false if this update is for an isl import type and it is not yet added to the type_store.
pub fn update_type_store(
&mut self,
type_store: &mut TypeStore,
load_isl_import: Option<&IslImport>,
isl_type_names: &HashSet<&str>,
) -> IonSchemaResult<bool> {
// if load_isl_import is not None, then match the enum variant and update type store with import types accordingly
if let Some(import) = load_isl_import {
match import {
IslImport::Schema(_) => {
self.update_type_store_with_all_isl_imported_types(
None,
type_store,
isl_type_names,
)?;
}
IslImport::Type(isl_import) => {
// if import has a specified type to import then only add that type
if let Some(named_type_def) =
self.get_type_by_name_for_import(isl_import.type_name(), type_store)
{
type_store
.add_isl_imported_type(isl_import.alias().as_ref(), named_type_def?);
self.update_type_store_with_all_isl_imported_types(
Some(isl_import.type_name()),
type_store,
isl_type_names,
)?;
} else {
// if the named_type_def appears as None then it means we haven't reached
// the named type to be imported yet hence we return with false pointing
// we haven't yet resolved this import.
return Ok(false);
}
}
IslImport::TypeAlias(isl_import) => {
// if import has a specified type with an alias then renamed that type to the given alias and add it
if type_store
.imported_type_ids_by_name
.contains_key(isl_import.alias().as_ref().unwrap())
{
// if the type_store already has the import in it then return true (i.e. TypeAlias has already been imported)
return Ok(true);
} else if let Some(named_type_def) =
self.get_type_by_name_for_import(isl_import.type_name(), type_store)
{
let aliased_type_def = named_type_def?
.with_name(isl_import.alias().as_ref().unwrap().to_owned());
type_store
.add_isl_imported_type(isl_import.alias().as_ref(), aliased_type_def);
self.update_type_store_with_all_isl_imported_types(
Some(isl_import.type_name()),
type_store,
isl_type_names,
)?;
} else {
// if the named_type_def appears as None then it means we haven't reached
// the named type to be imported yet hence we return with false pointing
// we haven't yet resolved this import.
return Ok(false);
}
}
}
} else {
// if load_isl_import is None i.e. it is the root schema, then update type_store with all the types inside this PendingTypes
self.update_type_store_with_all_types(type_store, isl_type_names)?;
}
self.types_by_id.clear();
self.ids_by_name.clear();
Ok(true)
}
// helper method get named type for given import_type_name from this PendingTypes
// this return type will be used by update_type_store method to then update type_store with this named type as import
fn get_type_by_name_for_import(
&self,
import_type_name: &str,
type_store: &mut TypeStore,
) -> Option<IonSchemaResult<TypeDefinitionImpl>> {
return match self.ids_by_name.get(import_type_name) {
Some(id) => self.types_by_id[*id]
.to_owned()
.map(|type_def| match type_def {
TypeDefinitionKind::Named(named_type_def) => Ok(named_type_def),
TypeDefinitionKind::Anonymous(_) => {
unreachable!(
"The TypeDefinition for the imported type '{}' was Anonymous.",
import_type_name
)
}
TypeDefinitionKind::BuiltIn(_) => {
unreachable!(
"The TypeDefinition for the imported type '{}' was a builtin type.",
import_type_name
)
}
}),
None => {
match type_store.get_defined_type_id_or_imported_type_id_by_name(import_type_name) {
Some(id) => match type_store.types_by_id[*id].to_owned() {
TypeDefinitionKind::Named(named_type_def) => Some(Ok(named_type_def)),
TypeDefinitionKind::Anonymous(_) => {
unreachable!(
"The TypeDefinition for the imported type '{}' was Anonymous.",
import_type_name
)
}
TypeDefinitionKind::BuiltIn(_) => {
unreachable!(
"The TypeDefinition for the imported type '{}' was a builtin type.",
import_type_name
)
}
},
None => None,
}
}
};
}
// helper method to update type store with all the types from this PendingTypes
fn update_type_store_with_all_types(
&self,
type_store: &mut TypeStore,
isl_type_names: &HashSet<&str>,
) -> IonSchemaResult<()> {
for optional_type in &self.types_by_id {
// return an error if any of the type in types_by_id vector is None/Unresolved
let type_def = optional_type.to_owned().ok_or_else(|| {
unresolvable_schema_error_raw("Unable to load schema due to unresolvable type")
})?;
match type_def {
TypeDefinitionKind::Named(named_type_def) => {
// check if the type definitions that are not yet resolved actually exists within the schema
// we can use the isl_type_names to make sure if they exists, otherwise return error.
if named_type_def.is_deferred_type_def()
&& !isl_type_names
.contains(named_type_def.name().as_ref().unwrap().as_str())
{
return unresolvable_schema_error(format!(
"Unable to load schema due to unresolvable type {}",
named_type_def.name().as_ref().unwrap()
));
}
type_store.add_named_type(named_type_def)
}
TypeDefinitionKind::Anonymous(anonymous_type_def) => {
type_store.add_anonymous_type(anonymous_type_def)
}
TypeDefinitionKind::BuiltIn(builtin_type) => {
type_store.add_builtin_type(&builtin_type)
}
};
}
Ok(())
}
// helper method to update type store with all the types from this PendingTypes
// import_type_name: this argument represents whether the import type is SchemaImport or a TypeImport (includes both TypeImport and TypeAliasImport)
// None - represents its a schema import which imports all types into imported_type_ids_by_name section of type_store
// Some(_) - represents a type import which import all types into types_by_id of type_store,
// except specified import type as it will be already loaded by parent method that uses this helper method
fn update_type_store_with_all_isl_imported_types(
&self,
isl_imported_type_name: Option<&str>,
type_store: &mut TypeStore,
isl_type_names: &HashSet<&str>,
) -> IonSchemaResult<()> {
for optional_type in &self.types_by_id {
// return an error if any of the type in types_by_id vector is None/Unresolved
let type_def = optional_type.to_owned().ok_or_else(|| {
unresolvable_schema_error_raw("Unable to load schema due to unresolvable type")
})?;
match type_def.to_owned() {
TypeDefinitionKind::Named(named_type_def) => {
match isl_imported_type_name {
None => {
// check if the type definitions that are not yet resolved actually exists within the schema
// we can use the isl_type_names to make sure if they exists, otherwise return error.
if named_type_def.is_deferred_type_def()
&& !isl_type_names
.contains(named_type_def.name().as_ref().unwrap().as_str())
{
return unresolvable_schema_error(format!(
"Unable to load schema due to unresolvable type {}",
named_type_def.name().as_ref().unwrap()
));
}
// imports all types into imported_type_ids_by_name section of type_store
type_store.add_isl_imported_type(None, named_type_def);
}
Some(import_type_name) => {
// check if the type definitions that are not yet resolved actually exists within the schema
// we can use the isl_type_names to make sure if they exists, otherwise return error.
if named_type_def.is_deferred_type_def()
&& !isl_type_names
.contains(named_type_def.name().as_ref().unwrap().as_str())
{
return unresolvable_schema_error(format!(
"Unable to load schema due to unresolvable type {}",
named_type_def.name().as_ref().unwrap()
));
}
// skip the specified import type as it will be already loaded by parent method that uses this helper method
if named_type_def.name().as_ref().unwrap().eq(import_type_name) {
continue;
}
// import all types into types_by_id of type_store which will help resolving the given import type
type_store
.types_by_id
.push(TypeDefinitionKind::Named(named_type_def));
}
}
}
TypeDefinitionKind::Anonymous(anonymous_type_def) => {
type_store.add_anonymous_type(anonymous_type_def);
}
TypeDefinitionKind::BuiltIn(builtin_type) => {
type_store.add_builtin_type(&builtin_type);
}
};
}
Ok(())
}
/// Returns total number of types stored in the [`TypeStore`]
pub(crate) fn get_total_types(&self, type_store: &mut TypeStore) -> usize {
self.types_by_id.len() + type_store.types_by_id.len()
}
/// Provides the [`TypeId`] associated with given name if it exists in the [`TypeStore`] or [`PendingTypes`]
/// Otherwise returns None
pub(crate) fn get_type_id_by_name(
&self,
name: &str,
type_store: &mut TypeStore,
) -> Option<TypeId> {
match self.ids_by_name.get(name) {
Some(id) => Some(*id + type_store.types_by_id.len()),
None => type_store
.get_defined_type_id_or_imported_type_id_by_name(name)
.copied(),
}
}
/// Updates the unresolved named type that was added as None while loading types in a schema
/// with a resolved type definition
pub(crate) fn update_named_type(
&mut self,
type_id: TypeId,
name: &str,
type_def: TypeDefinitionImpl,
type_store: &mut TypeStore,
) -> TypeId {
if let Some(exists) = self.ids_by_name.get(name) {
return exists.to_owned() + type_store.types_by_id.len();
}
if let Some(exists) = type_store.imported_type_ids_by_name.get(name) {
return exists.to_owned();
}
match type_store.update_deferred_type_def(type_def.to_owned(), name) {
None => {
let type_id = type_id - type_store.types_by_id.len();
self.ids_by_name.insert(name.to_owned(), type_id);
self.types_by_id[type_id] = Some(TypeDefinitionKind::Named(type_def));
type_id + type_store.types_by_id.len()
}
Some(exists) => exists,
}
}
/// Updates the unresolved anonymous type that was added as None while loading types in a schema
/// with a resolved type definition
pub(crate) fn update_anonymous_type(
&mut self,
type_id: TypeId,
type_def: TypeDefinitionImpl,
type_store: &mut TypeStore,
) -> TypeId {
self.types_by_id[type_id - type_store.types_by_id.len()] =
Some(TypeDefinitionKind::Anonymous(type_def));
type_id
}
/// Adds parent information storing the name and possible TypeId of the parent
pub(crate) fn add_parent(&mut self, name: String, type_store: &mut TypeStore) {
// Parent information is used when resolving a self referencing type
// while we resolve a type using the PendingTypes (a temporary type store used while we resolve a type definition)
// the type id for any type definition should be the PendingType's types_by_id length in + TypeStore's types_by_id length
// This gives a correct type id when all the types within PendingTypes are shifted to TypeStore
self.parent = Some((name, self.types_by_id.len() + type_store.types_by_id.len()))
}
/// Provides parent information: (parent name, type id)
pub(crate) fn get_parent(&self) -> &Option<(String, TypeId)> {
&self.parent
}
/// Clears parent information once that tree of types is traversed
pub(crate) fn clear_parent(&mut self) {
self.parent = None
}
/// Adds the unresolved type as None before it gets resolved and gets the associated [`TypeId`]
pub(crate) fn add_type(
&mut self,
type_store: &mut TypeStore,
type_name: Option<String>,
) -> TypeId {
if let Some(name) = type_name {
if let Some(exists) = self.ids_by_name.get(&name) {
return exists.to_owned() + type_store.types_by_id.len();
}
if let Some(exists) = type_store.get_defined_type_id_or_imported_type_id_by_name(&name)
{
return exists.to_owned();
}
}
let type_id = self.types_by_id.len();
self.types_by_id.push(None);
type_id + type_store.types_by_id.len()
}
/// Adds the unresolved type as None before it gets resolved and gets the associated [`TypeId`]
pub(crate) fn add_deferred_type_with_name(
&mut self,
alias: &str,
type_store: &mut TypeStore,
) -> TypeId {
let type_id = self.types_by_id.len();
self.ids_by_name.insert(alias.to_owned(), type_id);
self.types_by_id.push(Some(TypeDefinitionKind::Named(
TypeDefinitionImpl::new_deferred_type_def(alias.to_owned()),
)));
type_id + type_store.types_by_id.len()
}
}
/// Represents an array of BuiltIn derived ISL types
/// for more information: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#type-system
static DERIVED_ISL_TYPES: [&str; 10] = [
"type::{ name: lob, one_of: [ blob, clob ] }",
"type::{ name: number, one_of: [ decimal, float, int ] }",
"type::{ name: text, one_of: [ string, symbol ] }",
"type::{ name: $lob, one_of: [ $blob, $clob ] }",
"type::{ name: $number, one_of: [ $decimal, $float, $int ] }",
"type::{ name: $text, one_of: [ $string, $symbol ] }",
// this is just a place holder for document type,
// IonSchemaElement::Document(_) type is used to verify the correctness on the validation side
"type::{ name: document }",
"type::{ name: $any, one_of: [ $blob, $bool, $clob, $decimal,
$float, $int, $string, $symbol, $timestamp,
$list, $sexp, $struct, $null, document ] }",
"type::{ name: nothing, not: $any }",
"type::{ name: any, one_of: [ blob, bool, clob, decimal,
float, int, string, symbol, timestamp,
list, sexp, struct, document ] }",
];
pub type TypeId = usize;
/// Defines a cache that can be used to store resolved type definitions of a [`Schema`]
#[derive(Debug, Clone)]
pub struct TypeStore {
builtin_type_ids_by_name: HashMap<String, TypeId>, // stores all the builtin types used within this schema
imported_type_ids_by_name: HashMap<String, TypeId>, // stores all the imported types of a schema
ids_by_name: HashMap<String, TypeId>, // stores named types defined within the schema
types_by_id: Vec<TypeDefinitionKind>,
}
impl Default for TypeStore {
fn default() -> Self {
let mut type_store = Self {
builtin_type_ids_by_name: HashMap::new(),
imported_type_ids_by_name: HashMap::new(),
ids_by_name: HashMap::new(),
types_by_id: Vec::new(),
};
type_store
.preload()
.expect("The type store didn't preload with built-in types correctly");
type_store
}
}
impl TypeStore {
/// Preloads all [builtin isl types] into the TypeStore
/// [builtin isl types]: https://amazon-ion.github.io/ion-schema/docs/isl-1-0/spec#type-system
/// TODO: add document builtin type
pub(crate) fn preload(&mut self) -> IonSchemaResult<()> {
let isl_version = IslVersion::V1_0;
// add all ion types to the type store
// TODO: this array can be turned into an iterator implementation in ion-rust for IonType
use IonType::*;
let built_in_atomic_types: [IonType; 12] = [
Int, Float, Decimal, Timestamp, String, Symbol, Bool, Blob, Clob, SExp, List, Struct,
];
// add all the atomic ion types that doesn't allow nulls [type_ids: 0 - 11]
for atomic_type in built_in_atomic_types {
self.add_builtin_type(&BuiltInTypeDefinition::Atomic(
atomic_type.to_owned(),
Nullability::NotNullable,
));
}
// add all the atomic ion types that allows nulls [type_ids: 12 - 23]
for atomic_type in built_in_atomic_types {
self.add_builtin_type(&BuiltInTypeDefinition::Atomic(
atomic_type.to_owned(),
Nullability::Nullable,
));
}
// add $null to the built-in types [type_id: 24]
self.add_builtin_type(&BuiltInTypeDefinition::Atomic(Null, Nullability::Nullable));
// get the derived built in types map and related text value for given type_name [type_ids: 25 - 33]
let pending_types = &mut PendingTypes::default();
for text in DERIVED_ISL_TYPES {
let isl_type = IslType::from_owned_element(
isl_version,
&Element::read_one(text.as_bytes()).expect("parsing failed unexpectedly"),
&mut vec![],
)
.unwrap();
let type_def = BuiltInTypeDefinition::parse_from_isl_type(
isl_version,
&isl_type,
self,
pending_types,
)?;
self.add_builtin_type(&type_def);
}
Ok(())
}
/// Returns [`TypeId`]s stored in the [`TypeStore`] to be used by [`SchemaTypeIterator`]
pub(crate) fn get_types(&self) -> Vec<TypeId> {
self.ids_by_name.values().cloned().collect()
}
/// Returns import [`TypeId`]s stored in the [`TypeStore`] to be used by [`SchemaTypeIterator`]
pub(crate) fn get_imports(&self) -> Vec<TypeId> {
self.imported_type_ids_by_name.values().cloned().collect()
}
/// Provides the [`Type`] associated with given name if it exists in the [`TypeStore`]
/// Otherwise returns None
pub(crate) fn get_type_by_name(&self, name: &str) -> Option<&TypeDefinitionKind> {
self.ids_by_name
.get(name)
.and_then(|id| self.types_by_id.get(*id))
.or_else(|| {
self.imported_type_ids_by_name
.get(name)
.and_then(|id| self.types_by_id.get(*id))
})
}
/// Provides the [`TypeId`] associated with given name if it exists in the [`TypeStore`] either as
/// a built-in type or a type defined within schema; Otherwise returns None
pub(crate) fn get_built_in_type_id_or_defined_type_id_by_name(
&self,
name: &str,
) -> Option<&TypeId> {
self.ids_by_name
.get(name)
.or_else(|| self.builtin_type_ids_by_name.get(name))
}
/// Provides the [`TypeId`] associated with given name if it exists in the [`TypeStore`] as a type
/// defined within schema (This doesn't include built-in types); Otherwise returns None
pub(crate) fn get_defined_type_id_or_imported_type_id_by_name(
&self,
name: &str,
) -> Option<&TypeId> {
self.ids_by_name
.get(name)
.or_else(|| self.imported_type_ids_by_name.get(name))
}
/// Provides the [`Type`] associated with given name if it exists in the [`TypeStore`] as a type
/// defined within schema (This doesn't include built-in types and imported types); Otherwise returns None
pub(crate) fn get_type_def_by_name(&self, name: &str) -> Option<&TypeDefinitionKind> {
self.ids_by_name
.get(name)
.and_then(|id| self.types_by_id.get(*id))
}
/// Provides the [`TypeId`] associated with given type name if it exists in the [`TypeStore`]
/// Otherwise returns None
pub(crate) fn get_builtin_type_id(&self, type_name: &str) -> Option<TypeId> {
self.builtin_type_ids_by_name
.get(type_name)
.map(|t| t.to_owned())
}
/// Provides the [`Type`] associated with given [`TypeId`] if it exists in the [`TypeStore`]
/// Otherwise returns None
pub(crate) fn get_type_by_id(&self, id: TypeId) -> Option<&TypeDefinitionKind> {
self.types_by_id.get(id)
}
/// Adds the [`NamedTypeDefinition`] and the associated name in the [`TypeStore`] and returns the [`TypeId`] for it
/// If the name already exists in the [`TypeStore`] it returns the associated [`TypeId`]
pub(crate) fn add_named_type(&mut self, type_def: TypeDefinitionImpl) -> TypeId {
let name = type_def.name().as_ref().unwrap();
if let Some(exists) = self.ids_by_name.get(name) {
return exists.to_owned();
}
let type_id = self.types_by_id.len();
self.ids_by_name.insert(name.to_owned(), type_id);
self.types_by_id.push(TypeDefinitionKind::Named(type_def));
type_id
}
/// Updates the deferred [`NamedTypeDefinition`] for given type definition name
/// If the name already exists in the [`TypeStore`] it returns the associated [`TypeId`]
/// otherwise return [`None`]
pub(crate) fn update_deferred_type_def(
&mut self,
type_def: TypeDefinitionImpl,
name: &str,
) -> Option<TypeId> {
if let Some(exists) = self.ids_by_name.get(name) {
if let Some(TypeDefinitionKind::Named(existing_type_def)) = self.get_type_by_id(*exists)
{
// if existing_type_def is a deferred type def then this is the definition for it,
// resolve the deferred type definition here by replacing with given type definition
if existing_type_def.is_deferred_type_def() {
self.types_by_id[*exists] = TypeDefinitionKind::Named(type_def);
}
}
return Some(*exists);
}
None
}
/// Adds the [BuiltInTypeDefinition] in the [TypeStore] and returns the [TypeId] for it
/// If the name already exists in the [TypeStore] it returns the associated [TypeId]
pub(crate) fn add_builtin_type(
&mut self,
builtin_type_definition: &BuiltInTypeDefinition,
) -> TypeId {
let builtin_type_name = match builtin_type_definition {
BuiltInTypeDefinition::Atomic(ion_type, is_nullable) => match is_nullable {
Nullability::Nullable => format!("${ion_type}"),
Nullability::NotNullable => format!("{ion_type}"),
},
BuiltInTypeDefinition::Derived(other_type) => other_type.name().to_owned().unwrap(),
};
if let Some(exists) = self.builtin_type_ids_by_name.get(&builtin_type_name) {
return exists.to_owned();
}
let type_id = self.types_by_id.len();
self.builtin_type_ids_by_name
.insert(builtin_type_name, type_id);
self.types_by_id.push(TypeDefinitionKind::BuiltIn(
builtin_type_definition.to_owned(),
));
type_id
}
/// Adds the [`NamedTypeDefinition`] and the associated name as the imports of [`TypeStore`]
/// and returns the [`TypeId`] for it. If the name already exists in the [`TypeStore`] it returns the associated [`TypeId`]
pub(crate) fn add_isl_imported_type(
&mut self,
alias: Option<&String>,
type_def: TypeDefinitionImpl,
) -> TypeId {
let name = match alias {
None => type_def.name().as_ref().unwrap(),
Some(name) => name,
};
if let Some(exists) = self.imported_type_ids_by_name.get(name) {
return exists.to_owned();
}
let type_id = self.types_by_id.len();
self.imported_type_ids_by_name
.insert(name.to_owned(), type_id);
self.types_by_id.push(TypeDefinitionKind::Named(type_def));
type_id
}
/// Adds the [`Type`] in the [`TypeStore`] and returns the [`TypeId`] for it
pub(crate) fn add_anonymous_type(&mut self, type_def: TypeDefinitionImpl) -> TypeId {
let type_id = self.types_by_id.len();
self.types_by_id
.push(TypeDefinitionKind::Anonymous(type_def));
type_id
}
}
/// Provides functions to load [`Schema`] with type definitions using authorities for [`SchemaSystem`]
pub struct Resolver {
authorities: Vec<Box<dyn DocumentAuthority>>,
resolved_schema_cache: HashMap<String, Arc<Schema>>,
}
impl Resolver {
pub fn new(authorities: Vec<Box<dyn DocumentAuthority>>) -> Self {
Self {
authorities,
resolved_schema_cache: HashMap::new(),
}
}
pub fn schema_from_isl_types<A: AsRef<str>, B: Into<Vec<IslType>>>(
&self,
isl_version: IslVersion,
id: A,
isl_types: B,
) -> IonSchemaResult<Schema> {
let isl_types = isl_types.into();
// create type_store and pending types which will be used to create type definition
let mut type_store = TypeStore::default();
let pending_types = &mut PendingTypes::default();
// get all isl type names from given isl types
// this will be used to resolve type references which might not have yet resolved while loading a type definition
let isl_type_names: HashSet<&str> = HashSet::from_iter(
isl_types
.iter()
.filter(|t| t.name().is_some())
.map(|t| t.name().as_ref().unwrap().as_str()),
);
for isl_type in &isl_types {
// convert [IslType] into [TypeDefinitionKind]
match &isl_type.name() {
Some(isl_type_name) => {
// verify that the ISL type doesn't contain constraints from another ISL version
let has_other_isl_constraints = isl_type
.constraints()
.iter()
.any(|c| c.version != isl_version);
if has_other_isl_constraints {
return invalid_schema_error(format!("ISL type: {isl_type_name} contains constraints from another ISL version. Only use {isl_version} constraints for this method."));
}
TypeDefinitionImpl::parse_from_isl_type_and_update_pending_types(
isl_version,
isl_type,
&mut type_store,
pending_types,
)?
}
None => {
// top level schema types can not be anonymous
return invalid_schema_error("Top level types must be named type definitions");
}
};
}
// add all types from pending_types to type_store
pending_types.update_type_store(&mut type_store, None, &isl_type_names)?;
Ok(Schema::new(id, Arc::new(type_store)))
}
/// Converts given owned elements into ISL v2.0 representation
pub fn isl_schema_from_elements<I: Iterator<Item = Element>>(
&mut self,
elements: I,
id: &str,
) -> IonSchemaResult<IslSchema> {
// properties that will be stored in the ISL representation
let mut isl_imports: Vec<IslImport> = vec![];
let mut isl_types: Vec<IslType> = vec![];
let mut isl_inline_imports: Vec<IslImportType> = vec![];
let mut open_content = vec![];
let mut isl_user_reserved_fields = UserReservedFields::default();
let mut isl_version = IslVersion::V1_0;
let mut found_header = false;
let mut found_footer = false;
let mut found_type_definition = false;
let mut found_isl_version_marker = false;
for value in elements {
let annotations: &Annotations = value.annotations();
// load header for schema
if !found_isl_version_marker
&& value.ion_type() == IonType::Symbol
&& is_isl_version_marker(value.as_text().unwrap())
{
// This implementation supports Ion Schema 1.0 and Ion Schema 2.0
isl_version = match value.as_text().unwrap() {
"$ion_schema_1_0" => IslVersion::V1_0,
"$ion_schema_2_0" => IslVersion::V2_0,
_ => {
return invalid_schema_error(format!(
"Unsupported Ion Schema Language version: {value}"
))
}
};
found_isl_version_marker = true;
} else if annotations.contains("schema_header") {
if isl_version == IslVersion::V2_0 {
if found_type_definition {
return invalid_schema_error(
"The schema header must come before top level type definitions",
);
}
if found_header {
return invalid_schema_error(
"Schema must only contain a single schema header",
);
}
if annotations.len() > 1 {
return invalid_schema_error(
"schema header must not have any other annotations then `schema_header`",
);
}
}
found_header = true;
// if we didn't find an isl version marker before finding a schema header
// then isl version will be defaulted to be ISL 1.0
if !found_isl_version_marker {
found_isl_version_marker = true;
}
let schema_header = try_to!(value.as_struct());
if let Some(imports) = schema_header.get("imports").and_then(|it| it.as_sequence())
{
for import in imports.elements() {
let isl_import = IslImport::from_ion_element(import)?;
isl_imports.push(isl_import);
}
}
if isl_version == IslVersion::V2_0 {
if let Some(user_reserved_fields_element) =
schema_header.get("user_reserved_fields")
{
if !user_reserved_fields_element.annotations().is_empty() {
return invalid_schema_error(
"User reserved field must be an unannotated struct",
)?;
}
let user_reserved_fields_struct = user_reserved_fields_element
.as_struct()
.ok_or(invalid_schema_error_raw(
"User reserved field must be a non-null struct",
))?;
isl_user_reserved_fields =
UserReservedFields::from_ion_elements(user_reserved_fields_struct)?;
}
isl_user_reserved_fields.validate_field_names_in_header(schema_header)?;
}
}
// load types for schema
else if annotations.contains("type") {
found_type_definition = true;
if isl_version == IslVersion::V2_0 && annotations.len() > 1 {
return invalid_schema_error(
"Top level types definitions must not have any other annotations then `type`",
);
}
// if we didn't find an isl version marker before finding a type definition
// then isl version will be defaulted to be ISL 1.0
if !found_isl_version_marker {
found_isl_version_marker = true;
}
// convert Element to IslType
let isl_type: IslType =
IslType::from_owned_element(isl_version, &value, &mut isl_inline_imports)?;
if isl_type.name().is_none() {
// if a top level type definition doesn't contain `name` field return an error
return invalid_schema_error(
"Top level types must contain field `name` in their definition",
);
}
if isl_version == IslVersion::V2_0 {
isl_user_reserved_fields.validate_field_names_in_type(&isl_type)?;
}
// top level named type definition can not contain `occurs` field as per ISL specification
if value.as_struct().unwrap().get("occurs").is_some() {
return invalid_schema_error(
"Top level types must not contain `occurs` field in their definition",
);
}
isl_types.push(isl_type);
}
// load footer for schema
else if annotations.contains("schema_footer") {
found_footer = true;
if isl_version == IslVersion::V2_0 {
if annotations.len() > 1 {
return invalid_schema_error(
"schema footer must not have any other annotations then `schema_footer`",
);
}
let schema_footer = try_to!(value.as_struct());
isl_user_reserved_fields.validate_field_names_in_footer(schema_footer)?;
}
} else {
// open content
if value.ion_type() == IonType::Symbol
&& !value.is_null()
&& is_isl_version_marker(value.as_text().unwrap())
{
return invalid_schema_error(
"top level open content can not be an Ion Schema version marker",
);
}
if isl_version == IslVersion::V2_0
&& value
.annotations()
.iter()
.any(|a| is_reserved_word(a.text().unwrap()))
{
return invalid_schema_error(
"top level open content may not be annotated with any reserved keyword",
);
}
open_content.push(value);
continue;
}
}
if found_footer ^ found_header {
return invalid_schema_error("For any schema while a header and footer are both optional, a footer is required if a header is present (and vice-versa).");
}
match isl_version {
IslVersion::V1_0 => Ok(IslSchema::schema_v_1_0(
id,
isl_imports,
isl_types,
isl_inline_imports,
open_content,
)),
IslVersion::V2_0 => Ok(IslSchema::schema_v_2_0(
id,
isl_user_reserved_fields,
isl_imports,
isl_types,
isl_inline_imports,
open_content,
)),
}
}
/// Converts given ISL representation into a [`Schema`] based on given ISL version
pub fn schema_from_isl_schema(
&mut self,
isl_version: IslVersion,
isl: IslSchema,
type_store: &mut TypeStore,
load_isl_import: Option<&IslImport>,
) -> IonSchemaResult<Arc<Schema>> {
// This is used while resolving an import, it is initialized as `false` to indicate that
// the type to be imported is not yet added to the type_store.
// This will be changed to `true` as soon as the type to be imported is resolved and is added to the type_store
let mut added_imported_type_to_type_store = false;
if isl_version != isl.version() {
return invalid_schema_error(format!(
"Expected {isl_version} schema but found {}",
isl.version()
));
}
let isl_types = isl.types();
// Resolve all inline import types if there are any
// this will help resolve all inline imports before they are used as a reference to another type
for isl_inline_imported_type in isl.inline_imported_types() {
let import_id = isl_inline_imported_type.id();
let inline_imported_type = self.load_schema(
import_id,
type_store,
Some(&IslImport::Type(isl_inline_imported_type.to_owned())),
)?;
}
// Resolve all ISL imports
for isl_import in isl.imports() {
let import_id = isl_import.id();
let imported_schema = self.load_schema(import_id, type_store, Some(isl_import))?;
}
// get all isl type names that are defined within the schema
// this will be used to resolve type references which might not have yet resolved while loading a type definition
let isl_type_names: HashSet<&str> = HashSet::from_iter(
isl_types
.iter()
.filter(|t| t.name().is_some())
.map(|t| t.name().as_ref().unwrap().as_str()),
);
// Resolve all ISL types and constraints
for isl_type in isl_types {
let pending_types = &mut PendingTypes::default();
if let Some(isl_type_name) = &isl_type.name() {
// verify if there are any constraints with ISL 2.0 for this isl_type
let has_other_isl_constraints = isl_type
.constraints()
.iter()
.any(|c| c.version != isl_version);
if has_other_isl_constraints {
return invalid_schema_error(format!("ISL type: {isl_type_name} contains constraints from other ISL version. Only use {isl_version} constraints for this method."));
}
// convert IslType to TypeDefinitionKind
let type_id: TypeId =
TypeDefinitionImpl::parse_from_isl_type_and_update_pending_types(
isl_version,
isl_type,
type_store,
pending_types,
)?;
}
// add all types from pending types to type_store
added_imported_type_to_type_store =
pending_types.update_type_store(type_store, load_isl_import, &isl_type_names)?;
}
// if currently loading an ISL import (i.e. load_isl_import != None)
// then check if the type to be imported is added to the type_store or not
if load_isl_import.is_some() && !added_imported_type_to_type_store {
unreachable!(
"Unable to load import: {} as the type/types were not added to the type_store correctly",
isl.id()
);
}
let schema = Arc::new(Schema::new(isl.id(), Arc::new(type_store.clone())));
// add schema to schema cache
// if we are loading an import of the schema then we can only add this schema to cache if its a full schema import
// and can not add it to cache if we are loading specific type imports from the schema.
match load_isl_import {
None => {
self.resolved_schema_cache
.insert(isl.id(), Arc::clone(&schema));
}
Some(IslImport::Schema(_)) => {
self.resolved_schema_cache
.insert(isl.id(), Arc::clone(&schema));
}
_ => {
// No op for type imports
}
}
Ok(schema)
}
/// Loads a [`Schema`] with resolved [`Type`]s using authorities and type_store
// If we are loading the root schema then this will be set to `None` ( i.e. in the beginning when
// this method is called from the load_schema method of schema_system it is set to `None`)
// Otherwise if we are loading an import of the schema then this will be set to `Some(isl_import)`
// to be loaded (i.e. Inside schema_from_elements while loading imports this will be set to
// `Some(isl_import)`)
fn load_schema<A: AsRef<str>>(
&mut self,
id: A,
type_store: &mut TypeStore,
load_isl_import: Option<&IslImport>,
) -> IonSchemaResult<Arc<Schema>> {
let id: &str = id.as_ref();
if let Some(schema) = self.resolved_schema_cache.get(id) {
return Ok(Arc::clone(schema));
}
for authority in &self.authorities {
return match authority.elements(id) {
Err(error) => match error {
IonSchemaError::IoError { source } => match source.kind() {
ErrorKind::NotFound => continue,
_ => Err(IonSchemaError::IoError { source }),
},
_ => Err(error),
},
Ok(schema_content) => {
let isl = self.isl_schema_from_elements(schema_content.into_iter(), id)?;
self.schema_from_isl_schema(isl.version(), isl, type_store, load_isl_import)
}
};
}
unresolvable_schema_error("Unable to load schema: ".to_owned() + id)
}
/// Loads an [`IslSchema`] using authorities and type_store based on ISL version.
// If we are loading the root schema then this will be set to `None` ( i.e. in the beginning when
// this method is called from the load_schema method of schema_system it is set to `None`)
// Otherwise if we are loading an import of the schema then this will be set to `Some(isl_import)`
// to be loaded (i.e. Inside schema_from_elements while loading imports this will be set to
// `Some(isl_import)`)
fn load_isl_schema<A: AsRef<str>>(
&mut self,
id: A,
load_isl_import: Option<&IslImport>,
) -> IonSchemaResult<IslSchema> {
let id: &str = id.as_ref();
for authority in &self.authorities {
return match authority.elements(id) {
Ok(schema_content) => self.isl_schema_from_elements(schema_content.into_iter(), id),
Err(IonSchemaError::IoError { source: e }) if e.kind() == ErrorKind::NotFound => {
continue
}
Err(error) => Err(error),
};
}
unresolvable_schema_error("Unable to load ISL model: ".to_owned() + id)
}
}
/// Provides functions for instantiating instances of [`Schema`].
///
/// [`SchemaSystem`] is *[Send and Sync]* i.e. it is safe to send it to another thread and to be shared between threads.
/// For cases when one does need thread-safe interior mutability, they can use the explicit locking via [`std::sync::Mutex`] and [`std::sync::RwLock`].
///
/// [Send and Sync]: https://doc.rust-lang.org/nomicon/send-and-sync.html
pub struct SchemaSystem {
resolver: Resolver,
}
// TODO: make methods public based on the requirements
impl SchemaSystem {
pub fn new(authorities: Vec<Box<dyn DocumentAuthority>>) -> Self {
Self {
resolver: Resolver::new(authorities),
}
}
/// Requests each of the provided [`DocumentAuthority`]s, in order, to resolve the requested schema id
/// until one successfully resolves it.
/// If an authority throws an exception, resolution silently proceeds to the next authority.
/// This method returns an `Arc<Schema>` which allows to load this schema once re-use it across threads.
// TODO: Add support for Rc<Schema> by providing a trait implementation of schema and schema cache. This should
// allow users to choose what variant of schema they want.
pub fn load_schema<A: AsRef<str>>(&mut self, id: A) -> IonSchemaResult<Arc<Schema>> {
self.resolver
.load_schema(id, &mut TypeStore::default(), None)
}
/// Constructs a new schema using provided ISL content.
pub fn new_schema(&mut self, schema_content: &[u8], id: &str) -> IonSchemaResult<Arc<Schema>> {
let elements = Element::read_all(schema_content)?;
let isl = self
.resolver
.isl_schema_from_elements(elements.into_iter(), id)?;
self.resolver
.schema_from_isl_schema(isl.version(), isl, &mut TypeStore::default(), None)
}
/// Requests each of the provided [`DocumentAuthority`]s, in order, to get ISL model for the
/// requested schema id until one successfully resolves it.
/// If an authority throws an exception, resolution silently proceeds to the next authority.
pub fn load_isl_schema<A: AsRef<str>>(&mut self, id: A) -> IonSchemaResult<IslSchema> {
self.resolver.load_isl_schema(id, None)
}
/// Constructs a new ISL model using provided ISL content.
pub fn new_isl_schema(
&mut self,
schema_content: &[u8],
id: &str,
) -> IonSchemaResult<IslSchema> {
let elements = Element::read_all(schema_content)?;
self.resolver
.isl_schema_from_elements(elements.into_iter(), id)
}
/// Resolves given ISL 1.0 model into a [Schema].
/// If the given ISL model has any ISL 2.0 related types/constraints, resolution returns an error.
/// This method returns an `Arc<Schema>` which allows to load this schema once re-use it across threads.
// TODO: Add support for Rc<Schema> by providing a trait implementation of schema and schema cache. This should
// allow users to choose what variant of schema they want.
pub fn load_schema_from_isl_schema_v1_0(
&mut self,
isl: IslSchema,
) -> IonSchemaResult<Arc<Schema>> {
self.resolver
.schema_from_isl_schema(IslVersion::V1_0, isl, &mut TypeStore::default(), None)
}
/// Resolves given ISL 2.0 model into a [Schema].
/// If the given ISL model has any ISL 1.0 related types/constraints, resolution returns an error.
/// This method returns an `Arc<Schema>` which allows to load this schema once re-use it across threads.
// TODO: Add support for Rc<Schema> by providing a trait implementation of schema and schema cache. This should
// allow users to choose what variant of schema they want.
pub fn load_schema_from_isl_schema_v2_0(
&mut self,
isl: IslSchema,
) -> IonSchemaResult<Arc<Schema>> {
self.resolver
.schema_from_isl_schema(IslVersion::V2_0, isl, &mut TypeStore::default(), None)
}
/// Returns authorities associated with this [`SchemaSystem`]
fn authorities(&mut self) -> &[Box<dyn DocumentAuthority>] {
&self.resolver.authorities
}
/// Adds the provided authority to the list of [`DocumentAuthority`]s.
fn add_authority(&mut self, authority: Box<dyn DocumentAuthority>) {
self.resolver.authorities.push(authority);
}
/// Replaces the list of [`DocumentAuthority`]s with a list containing only the specified authority.
fn with_authority(&mut self, authority: Box<dyn DocumentAuthority>) {
let authorities: Vec<Box<dyn DocumentAuthority>> = vec![authority];
self.resolver.authorities = authorities;
}
// TODO: Use IntoIterator here instead of a Vec
/// Replaces the list of [`DocumentAuthority`]s with the specified list of [`DocumentAuthority`]s.
fn with_authorities(&mut self, authorities: Vec<Box<dyn DocumentAuthority>>) {
self.resolver.authorities = authorities;
}
/// Creates a schema from given [`IslType`]s using ISL 1.0
/// Note: This method assumes that there are no imported type definitions used for these [`IslType`]s
pub fn schema_from_isl_types_v1_0<A: AsRef<str>, B: Into<Vec<IslType>>>(
&self,
id: A,
isl_types: B,
) -> IonSchemaResult<Schema> {
self.resolver
.schema_from_isl_types(IslVersion::V1_0, id, isl_types)
}
/// Creates a schema from given [`IslType`]s using ISL 2.0
/// Note: This method assumes that there are no imported type definitions used for these [`IslType`]s
pub fn schema_from_isl_types_v2_0<A: AsRef<str>, B: Into<Vec<IslType>>>(
&self,
id: A,
isl_types: B,
) -> IonSchemaResult<Schema> {
self.resolver
.schema_from_isl_types(IslVersion::V2_0, id, isl_types)
}
}
#[cfg(test)]
mod schema_system_tests {
use super::*;
use crate::authority::{FileSystemDocumentAuthority, MapDocumentAuthority};
use crate::isl::isl_constraint;
use crate::isl::isl_type;
use crate::isl::isl_type_reference;
use crate::system::IonSchemaError::InvalidSchemaError;
use std::path::Path;
#[test]
fn schema_system_add_authorities_test() {
let mut schema_system = SchemaSystem::new(vec![Box::new(
FileSystemDocumentAuthority::new(Path::new("")),
)]);
schema_system.add_authority(Box::new(FileSystemDocumentAuthority::new(Path::new(
"test",
))));
let schema_system_authorities = schema_system.authorities();
assert_eq!(2, schema_system_authorities.len());
}
#[test]
fn schema_system_with_authority_test() {
let mut schema_system = SchemaSystem::new(vec![Box::new(
FileSystemDocumentAuthority::new(Path::new("")),
)]);
schema_system.with_authority(Box::new(FileSystemDocumentAuthority::new(Path::new(
"test",
))));
let schema_system_authorities = schema_system.authorities();
assert_eq!(1, schema_system_authorities.len());
}
#[test]
fn schema_system_with_authorities_test() {
let mut schema_system = SchemaSystem::new(vec![Box::new(
FileSystemDocumentAuthority::new(Path::new("")),
)]);
schema_system.with_authorities(vec![
Box::new(FileSystemDocumentAuthority::new(Path::new("test"))),
Box::new(FileSystemDocumentAuthority::new(Path::new("ion"))),
]);
let schema_system_authorities = schema_system.authorities();
assert_eq!(2, schema_system_authorities.len());
}
#[test]
fn schema_system_map_authority_with_type_alias_import_test() {
// map with (id, ion content)
let map_authority = [
(
"sample_number.isl",
r#"
schema_header::{
imports: [{ id: "sample_decimal.isl", type: my_decimal, as: other_decimal }],
}
type::{
name: my_int,
type: int,
}
type::{
name: my_number,
all_of: [
my_int,
other_decimal,
],
}
schema_footer::{
}
"#,
),
(
"sample_decimal.isl",
r#"
schema_header::{
imports: [],
}
type::{
name: my_decimal,
type: decimal,
}
type::{
name: my_string,
type: string,
}
schema_footer::{
}
"#,
),
];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
// verify if the schema loads without any errors
let schema = schema_system.load_schema("sample_number.isl");
assert!(schema.is_ok());
}
#[test]
fn schema_system_map_authority_with_type_import_test() {
// map with (id, ion content)
let map_authority = [
(
"sample_number.isl",
r#"
schema_header::{
imports: [{ id: "sample_decimal.isl", type: my_decimal }],
}
type::{
name: my_int,
type: int,
}
type::{
name: my_number,
all_of: [
my_int,
my_decimal,
],
}
schema_footer::{
}
"#,
),
(
"sample_decimal.isl",
r#"
schema_header::{
imports: [],
}
type::{
name: my_decimal,
type: decimal,
}
type::{
name: my_string,
type: string,
}
schema_footer::{
}
"#,
),
];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
// verify if the schema loads without any errors
let schema = schema_system.load_schema("sample_number.isl");
assert!(schema.is_ok());
}
#[test]
fn schema_system_map_authority_with_schema_import_test() {
// map with (id, ion content)
let map_authority = [
(
"sample_import_string.isl",
r#"
schema_header::{
imports: [{ id: "sample_string.isl" }],
}
type::{
name: import_string,
type: my_string,
}
schema_footer::{
}
"#,
),
(
"sample_string.isl",
r#"
schema_header::{
imports: [],
}
type::{
name: my_string,
type: string,
}
schema_footer::{
}
"#,
),
];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
// verify if the schema loads without any errors
let schema = schema_system.load_schema("sample_import_string.isl");
assert!(schema.is_ok());
}
#[test]
fn schema_system_map_authority_with_inline_import_type_test() {
// map with (id, ion content)
let map_authority = [
(
"sample_number.isl",
r#"
schema_header::{
imports: [],
}
type::{
name: my_int,
type: int,
}
type::{
name: my_number,
all_of: [
my_int,
{ id: "sample_decimal.isl", type: my_decimal },
],
}
schema_footer::{
}
"#,
),
(
"sample_decimal.isl",
r#"
schema_header::{
imports: [],
}
type::{
name: my_decimal,
type: decimal,
}
type::{
name: my_string,
type: string,
}
schema_footer::{
}
"#,
),
];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
// verify if the schema loads without any errors
let schema = schema_system.load_schema("sample_number.isl");
assert!(schema.is_ok());
}
#[test]
fn schema_system_map_authority_with_incorrect_inline_import_type_test() {
// map with (id, ion content)
let map_authority = [
(
"sample_number.isl",
r#"
$ion_schema_2_0
schema_header::{
imports: [],
}
type::{
name: my_int,
type: int,
}
type::{
name: my_number,
all_of: [
my_int,
{ id: "sample_decimal.isl", type: my_decimal, as: other_decimal},
],
}
schema_footer::{
}
"#,
),
(
"sample_decimal.isl",
r#"
$ion_schema_2_0
schema_header::{
imports: [],
}
type::{
name: my_decimal,
type: decimal,
}
type::{
name: my_string,
type: string,
}
schema_footer::{
}
"#,
),
];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
// verify if the schema loads with specific errors
let schema = schema_system.load_schema("sample_number.isl");
assert!(schema.is_err());
assert!(matches!(schema.unwrap_err(), InvalidSchemaError { .. }));
}
#[test]
fn schema_system_map_authority_with_isl_builtin_derived_types() {
// map with (id, ion content)
let map_authority = [
(
"sample.isl",
r#"
schema_header::{
imports: [ { id: "sample_builtin_types.isl" } ],
}
type::{
name: my_number,
type: number,
}
type::{
name: my_type,
one_of: [
my_number,
my_text,
my_lob
],
}
schema_footer::{
}
"#,
),
(
"sample_builtin_types.isl",
r#"
schema_header::{
imports: [],
}
type::{
name: my_text,
type: text,
}
type::{
name: my_lob,
type: lob,
}
schema_footer::{
}
"#,
),
];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
// verify if the schema loads without any errors
let schema = schema_system.load_schema("sample.isl");
assert!(schema.is_ok());
}
#[test]
fn schema_system_map_authority_with_isl_builtin_derived_nullable_types() {
// map with (id, ion content)
let map_authority = [
(
"sample.isl",
r#"
schema_header::{
imports: [ { id: "sample_builtin_nullable_types.isl" } ],
}
type::{
name: my_number,
type: $number,
}
type::{
name: my_any,
type: $any,
}
type::{
name: my_type,
one_of: [
my_number,
my_text,
my_lob
],
}
schema_footer::{
}
"#,
),
(
"sample_builtin_nullable_types.isl",
r#"
schema_header::{
imports: [],
}
type::{
name: my_text,
type: $text,
}
type::{
name: my_lob,
type: $lob,
}
schema_footer::{
}
"#,
),
];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
// verify if the schema loads without any errors
let schema = schema_system.load_schema("sample.isl");
assert!(schema.is_ok());
}
#[test]
fn schema_system_map_authority_with_valid_transitive_type_import_test() {
// map with (id, ion content)
let map_authority = [
(
"sample.isl",
r#"
schema_header::{
imports: [ { id: "sample_builtin_nullable_types.isl", type: my_text } ],
}
type::{
name: my_type,
type: my_text
}
schema_footer::{
}
"#,
),
(
"sample_builtin_nullable_types.isl",
r#"
schema_header::{
imports: [],
}
type::{
name: my_text,
one_of: [
my_string,
symbol,
],
}
type::{
name: my_string,
type: string,
}
schema_footer::{
}
"#,
),
];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
// verify if the schema loads without any error
let schema = schema_system.load_schema("sample.isl");
assert!(schema.is_ok());
}
#[test]
fn schema_system_map_authority_with_invalid_transitive_type_import_test() {
// map with (id, ion content)
let map_authority = [
(
"sample.isl",
r#"
schema_header::{
imports: [ { id: "sample_builtin_nullable_types.isl", type: my_text } ],
}
type::{
name: my_type,
type: my_string, // this type reference was not imported by name in sample.isl
}
schema_footer::{
}
"#,
),
(
"sample_builtin_nullable_types.isl",
r#"
schema_header::{
imports: [],
}
type::{
name: my_text,
one_of: [
my_string,
symbol,
],
}
type::{
name: my_string,
type: string,
}
schema_footer::{
}
"#,
),
];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
// verify if the schema loads with an error for invalid transitive type import
let schema = schema_system.load_schema("sample.isl");
assert!(schema.is_err());
}
#[test]
fn schema_system_map_authority_with_multiple_type_definitions() {
// map with (id, ion content)
let map_authority = [(
"sample.isl",
r#"
schema_header::{
imports: [],
}
type::{
name: my_text,
one_of: [
my_string,
symbol,
],
}
type::{
name: my_string,
type: string,
}
schema_footer::{
}
"#,
)];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
// verify if the schema loads without any errors
let schema = schema_system.load_schema("sample.isl");
assert!(schema.is_ok());
}
#[test]
fn schema_system_map_authority_with_multiple_codependent_type_definitions() {
// map with (id, ion content)
let map_authority = [(
"sample.isl",
r#"
type::{
name: node_a,
type: list,
element: node_b,
}
type::{
name: node_b,
type: sexp,
element: node_a,
}
"#,
)];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
// verify if the schema loads without any errors
let schema = schema_system.load_schema("sample.isl");
assert!(schema.is_ok());
}
#[test]
fn schema_system_map_authority_with_self_referencing_type_definition() {
// map with (id, ion content)
let map_authority = [(
"sample.isl",
r#"
type::{
name: binary_heap_node,
type: sexp,
element: { one_of: [ binary_heap_node, int ] },
container_length: range::[0, 2],
}
"#,
)];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
// verify if the schema loads without any errors
let schema = schema_system.load_schema("sample.isl");
assert!(schema.is_ok());
}
#[test]
fn top_level_type_def_without_name_field() {
// map with (id, ion content)
let map_authority = [(
"sample.isl",
r#"
type::{
// top level type definition must contain a `name` field
}
"#,
)];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
// verify if the schema return error for top level type definition without `name` field
let schema = schema_system.load_schema("sample.isl");
assert!(schema.is_err());
}
#[test]
fn top_level_type_def_with_multiple_name_field() {
// map with (id, ion content)
let map_authority = [(
"sample.isl",
r#"
type::{
name: my_type,
name: new_type
}
"#,
)];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
// verify if the schema return error for top level type definition with multiple `name` field
let schema = schema_system.load_schema("sample.isl");
assert!(schema.is_err());
}
#[test]
fn top_level_type_def_with_non_symbol_name_field() {
// map with (id, ion content)
let map_authority = [(
"sample.isl",
r#"
type::{
name: "my_type"
}
"#,
)];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
// verify if the schema return error for top level type definition with a `name` field of string type
let schema = schema_system.load_schema("sample.isl");
assert!(schema.is_err());
}
#[test]
fn valid_isl_version_marker_test() {
// map with (id, ion content)
let map_authority = [(
"sample.isl",
r#"
$ion_schema_1_0
"#,
)];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
// verify if the schema loads without any errors
let schema = schema_system.load_schema("sample.isl");
assert!(schema.is_ok());
}
#[test]
fn invalid_isl_version_marker_test() {
// map with (id, ion content)
let map_authority = [(
"sample.isl",
r#"
$ion_schema_4_5
"#,
)];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
// verify if the schema return error for invalid ISL version marker
let schema = schema_system.load_schema("sample.isl");
assert!(schema.is_err());
}
#[test]
fn unsupported_isl_version_marker_test() {
// map with (id, ion content)
let map_authority = [(
"sample.isl",
r#"
$ion_schema_2_1
"#,
)];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
// verify if the schema return error for unsupported ISL version marker
let schema = schema_system.load_schema("sample.isl");
assert!(schema.is_err());
}
#[test]
fn open_content_test() -> IonSchemaResult<()> {
// map with (id, ion content)
let map_authority = [(
"sample.isl",
r#"
schema_header::{}
type::{
name: my_type,
type: string,
}
open_content_1::{
unknown_constraint: "this is an open content struct"
}
open_content_2::{
unknown_constraint: "this is an open content struct"
}
schema_footer::{}
"#,
)];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
let schema = schema_system.load_isl_schema("sample.isl")?;
let expected_open_content = Element::read_all(
r#"
open_content_1::{
unknown_constraint: "this is an open content struct"
}
open_content_2::{
unknown_constraint: "this is an open content struct"
}
"#
.as_bytes(),
)?;
// verify the open content that is retrieved from the ISL model is same as the expected open content
assert_eq!(&schema.open_content().len(), &2);
assert_eq!(schema.open_content(), &expected_open_content);
Ok(())
}
#[test]
fn unexpected_fields_in_isl_v2_0_header() {
// map with (id, ion content)
let map_authority = [(
"sample.isl",
r#"
$ion_schema_2_0
schema_header::{
user_reserved_fields: {
schema_header: [ foo, bar ],
type: [ baz ]
},
baz: "this is an unexpected field in schema header"
}
type::{
name: my_type,
type: string,
}
schema_footer::{}
"#,
)];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
let schema = schema_system.load_isl_schema("sample.isl");
assert!(schema.is_err());
}
#[test]
fn unexpected_fields_in_isl_v2_0_footer() {
// map with (id, ion content)
let map_authority = [(
"sample.isl",
r#"
$ion_schema_2_0
schema_header::{
user_reserved_fields: {
schema_footer: [ foo, bar ],
sdhema_header: [ baz ]
},
}
type::{
name: my_type,
type: string,
}
schema_footer::{
baz: "this is an unexpected field in schema header"
}
"#,
)];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
let schema = schema_system.load_isl_schema("sample.isl");
assert!(schema.is_err());
}
#[test]
fn unexpected_fields_in_isl_v2_0_type() {
// map with (id, ion content)
let map_authority = [(
"sample.isl",
r#"
$ion_schema_2_0
schema_header::{
user_reserved_fields: {
schema_header: [ baz ],
type: [ foo, bar ]
},
}
type::{
name: my_type,
type: string,
baz: "this is an unexpected field in schema header"
}
schema_footer::{}
"#,
)];
let mut schema_system =
SchemaSystem::new(vec![Box::new(MapDocumentAuthority::new(map_authority))]);
let schema = schema_system.load_isl_schema("sample.isl");
assert!(schema.is_err());
}
#[test]
fn load_schema_from_isl_schema_v1_0_test() {
// an ISL 1.0 type definition
let isl_type = isl_type::v_1_0::named_type(
"my_type",
[isl_constraint::v_1_0::element(
isl_type_reference::v_1_0::named_type_ref("int"),
)],
);
let isl = IslSchema::schema_v_1_0("sample.isl", vec![], vec![isl_type], vec![], vec![]);
let mut schema_system = SchemaSystem::new(vec![]);
let schema = schema_system.load_schema_from_isl_schema_v1_0(isl);
// verify the resolved schema generated from the ISL 1.0 model is valid
assert!(schema.is_ok());
}
#[test]
fn load_schema_from_isl_schema_v2_0_test() {
// an ISL 2.0 type definition
let isl_type = isl_type::v_2_0::named_type(
"my_type",
[isl_constraint::v_2_0::type_constraint(
isl_type_reference::v_2_0::named_type_ref("int"),
)],
);
let isl = IslSchema::schema_v_2_0(
"sample.isl",
UserReservedFields::default(),
vec![],
vec![isl_type],
vec![],
vec![],
);
let mut schema_system = SchemaSystem::new(vec![]);
let schema = schema_system.load_schema_from_isl_schema_v2_0(isl);
// verify the resolved schema generated from the ISL 2.0 model is valid
assert!(schema.is_ok());
}
#[test]
fn load_schema_from_isl_schema_v1_0_with_isl_v2_0_constraints_test() {
// an ISL 1.0 type that contains ISL 2.0 related constraints
let isl_type = isl_type::v_1_0::named_type(
"my_type",
[isl_constraint::v_2_0::type_constraint(
isl_type_reference::v_2_0::named_type_ref("int"),
)],
);
let isl = IslSchema::schema_v_1_0("sample.isl", vec![], vec![isl_type], vec![], vec![]);
let mut schema_system = SchemaSystem::new(vec![]);
let schema = schema_system.load_schema_from_isl_schema_v1_0(isl);
// verify the resolved schema generated from the ISL 1.0 model that contains ISL 2.0 constraints is invalid
assert!(schema.is_err());
}
#[test]
fn load_schema_from_isl_schema_v2_0_with_isl_v1_0_constraints_test() {
// an ISL 2.0 type that contains ISL 1.0 related constraints
let isl_type = isl_type::v_2_0::named_type(
"my_type",
[isl_constraint::v_1_0::type_constraint(
isl_type_reference::v_1_0::named_type_ref("int"),
)],
);
let isl = IslSchema::schema_v_2_0(
"sample.isl",
UserReservedFields::default(),
vec![],
vec![isl_type],
vec![],
vec![],
);
let mut schema_system = SchemaSystem::new(vec![]);
let schema = schema_system.load_schema_from_isl_schema_v2_0(isl);
// verify the resolved schema generated from the ISL 2.0 model that contains ISL 1.0 constraints is invalid
assert!(&schema.is_err());
}
#[test]
fn new_schema_test() {
let mut schema_system = SchemaSystem::new(vec![]);
let schema = schema_system.new_schema(
br#"
$ion_schema_2_0
schema_header::{}
type::{
name: my_type,
type: string,
}
schema_footer::{}
"#,
"sample.isl",
);
assert!(schema.is_ok());
}
#[test]
fn new_schema_invalid_test() {
let mut schema_system = SchemaSystem::new(vec![]);
let schema = schema_system.new_schema(
br#"
$ion_schema_2_0
schema_header::{}
type::{
name: my_type,
type: nullable::string, // `nullable` annotation is not supported in ISL 2.0
}
schema_footer::{}
"#,
"sample.isl",
);
assert!(schema.is_err());
}
#[test]
fn new_isl_schema_test() {
let mut schema_system = SchemaSystem::new(vec![]);
let isl = schema_system.new_isl_schema(
br#"
$ion_schema_2_0
schema_header::{}
type::{
name: my_type,
type: string,
}
schema_footer::{}
"#,
"sample.isl",
);
assert!(isl.is_ok());
}
#[test]
fn new_isl_schema_invalid_test() {
let mut schema_system = SchemaSystem::new(vec![]);
let isl = schema_system.new_isl_schema(
br#"
$ion_schema_2_0
schema_header::{}
type::{
name: my_type,
type: nullable::string, // `nullable` annotation is not supported in ISL 2.0
}
schema_footer::{}
"#,
"sample.isl",
);
assert!(isl.is_err());
}
#[test]
fn test_send_schema() {
fn assert_send<T: Send>() {}
assert_send::<Schema>();
}
#[test]
fn test_sync_schema() {
fn assert_sync<T: Sync>() {}
assert_sync::<Schema>();
}
#[test]
fn test_send_schema_system() {
fn assert_send<T: Send>() {}
assert_send::<SchemaSystem>();
}
#[test]
fn test_sync_schema_system() {
fn assert_sync<T: Sync>() {}
assert_sync::<SchemaSystem>();
}
}