juniper_codegen/lib.rs
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 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504
#![doc = include_str!("../README.md")]
#![recursion_limit = "1024"]
// NOTICE: Unfortunately this macro MUST be defined here, in the crate's root module, because Rust
// doesn't allow to export `macro_rules!` macros from a `proc-macro` crate type currently,
// and so we cannot move the definition into a sub-module and use the `#[macro_export]`
// attribute.
/// Attempts to merge an [`Option`]ed `$field` of a `$self` struct with the same `$field` of
/// `$another` struct. If both are [`Some`], then throws a duplication error with a [`Span`] related
/// to the `$another` struct (a later one).
///
/// The type of [`Span`] may be explicitly specified as one of the [`SpanContainer`] methods.
/// By default, [`SpanContainer::span_ident`] is used.
///
/// [`Span`]: proc_macro2::Span
/// [`SpanContainer`]: crate::common::SpanContainer
/// [`SpanContainer::span_ident`]: crate::common::SpanContainer::span_ident
macro_rules! try_merge_opt {
($field:ident: $self:ident, $another:ident => $span:ident) => {{
if let Some(v) = $self.$field {
$another
.$field
.replace(v)
.none_or_else(|dup| crate::common::parse::attr::err::dup_arg(&dup.$span()))?;
}
$another.$field
}};
($field:ident: $self:ident, $another:ident) => {
try_merge_opt!($field: $self, $another => span_ident)
};
}
// NOTICE: Unfortunately this macro MUST be defined here, in the crate's root module, because Rust
// doesn't allow to export `macro_rules!` macros from a `proc-macro` crate type currently,
// and so we cannot move the definition into a sub-module and use the `#[macro_export]`
// attribute.
/// Attempts to merge a [`HashMap`] `$field` of a `$self` struct with the same `$field` of
/// `$another` struct. If some [`HashMap`] entries are duplicated, then throws a duplication error
/// with a [`Span`] related to the `$another` struct (a later one).
///
/// The type of [`Span`] may be explicitly specified as one of the [`SpanContainer`] methods.
/// By default, [`SpanContainer::span_ident`] is used.
///
/// [`HashMap`]: std::collections::HashMap
/// [`Span`]: proc_macro2::Span
/// [`SpanContainer`]: crate::common::SpanContainer
/// [`SpanContainer::span_ident`]: crate::common::SpanContainer::span_ident
macro_rules! try_merge_hashmap {
($field:ident: $self:ident, $another:ident => $span:ident) => {{
if !$self.$field.is_empty() {
for (ty, rslvr) in $self.$field {
$another
.$field
.insert(ty, rslvr)
.none_or_else(|dup| crate::common::parse::attr::err::dup_arg(&dup.$span()))?;
}
}
$another.$field
}};
($field:ident: $self:ident, $another:ident) => {
try_merge_hashmap!($field: $self, $another => span_ident)
};
}
// NOTICE: Unfortunately this macro MUST be defined here, in the crate's root module, because Rust
// doesn't allow to export `macro_rules!` macros from a `proc-macro` crate type currently,
// and so we cannot move the definition into a sub-module and use the `#[macro_export]`
// attribute.
/// Attempts to merge a [`HashSet`] `$field` of a `$self` struct with the same `$field` of
/// `$another` struct. If some [`HashSet`] entries are duplicated, then throws a duplication error
/// with a [`Span`] related to the `$another` struct (a later one).
///
/// The type of [`Span`] may be explicitly specified as one of the [`SpanContainer`] methods.
/// By default, [`SpanContainer::span_ident`] is used.
///
/// [`HashSet`]: std::collections::HashSet
/// [`Span`]: proc_macro2::Span
/// [`SpanContainer`]: crate::common::SpanContainer
/// [`SpanContainer::span_ident`]: crate::common::SpanContainer::span_ident
macro_rules! try_merge_hashset {
($field:ident: $self:ident, $another:ident => $span:ident) => {{
if !$self.$field.is_empty() {
for ty in $self.$field {
$another
.$field
.replace(ty)
.none_or_else(|dup| crate::common::parse::attr::err::dup_arg(&dup.$span()))?;
}
}
$another.$field
}};
($field:ident: $self:ident, $another:ident) => {
try_merge_hashset!($field: $self, $another => span_ident)
};
}
mod common;
mod graphql_enum;
mod graphql_input_object;
mod graphql_interface;
mod graphql_object;
mod graphql_scalar;
mod graphql_subscription;
mod graphql_union;
mod scalar_value;
use proc_macro::TokenStream;
use self::common::diagnostic::{self, ResultExt as _};
/// `#[derive(GraphQLInputObject)]` macro for deriving a
/// [GraphQL input object][0] implementation for a Rust struct. Each
/// non-ignored field type must itself be [GraphQL input object][0] or a
/// [GraphQL scalar][2].
///
/// The `#[graphql]` helper attribute is used for configuring the derived
/// implementation. Specifying multiple `#[graphql]` attributes on the same
/// definition is totally okay. They all will be treated as a single attribute.
///
/// ```rust
/// use juniper::GraphQLInputObject;
///
/// #[derive(GraphQLInputObject)]
/// struct Point2D {
/// x: f64,
/// y: f64,
/// }
/// ```
///
/// # Custom name and description
///
/// The name of a [GraphQL input object][0] or its [fields][1] may be overridden
/// with the `name` attribute's argument. By default, a type name or a struct
/// field name is used in a `camelCase`.
///
/// The description of a [GraphQL input object][0] or its [fields][1] may be
/// specified either with the `description`/`desc` attribute's argument, or with
/// a regular Rust doc comment.
///
/// ```rust
/// # use juniper::GraphQLInputObject;
/// #
/// #[derive(GraphQLInputObject)]
/// #[graphql(
/// // Rename the type for GraphQL by specifying the name here.
/// name = "Point",
/// // You may also specify a description here.
/// // If present, doc comments will be ignored.
/// desc = "A point is the simplest two-dimensional primitive.",
/// )]
/// struct Point2D {
/// /// Abscissa value.
/// x: f64,
///
/// #[graphql(name = "y", desc = "Ordinate value")]
/// y_coord: f64,
/// }
/// ```
///
/// # Renaming policy
///
/// By default, all [GraphQL input object fields][1] are renamed in a
/// `camelCase` manner (so a `y_coord` Rust struct field becomes a
/// `yCoord` [value][1] in GraphQL schema, and so on). This complies with
/// default GraphQL naming conventions as [demonstrated in spec][0].
///
/// However, if you need for some reason another naming convention, it's
/// possible to do so by using the `rename_all` attribute's argument. At the
/// moment, it supports the following policies only: `SCREAMING_SNAKE_CASE`,
/// `camelCase`, `none` (disables any renaming).
///
/// ```rust
/// # use juniper::GraphQLInputObject;
/// #
/// #[derive(GraphQLInputObject)]
/// #[graphql(rename_all = "none")] // disables renaming
/// struct Point2D {
/// x: f64,
/// y_coord: f64, // will be `y_coord` instead of `yCoord` in GraphQL schema
/// }
/// ```
///
/// # Ignoring fields
///
/// To omit exposing a Rust field in a GraphQL schema, use the `ignore`
/// attribute's argument directly on that field. Ignored fields must implement
/// [`Default`] or have the `default = <expression>` attribute's argument.
///
/// ```rust
/// # use juniper::GraphQLInputObject;
/// #
/// enum System {
/// Cartesian,
/// }
///
/// #[derive(GraphQLInputObject)]
/// struct Point2D {
/// x: f64,
/// y: f64,
/// #[graphql(ignore, default = System::Cartesian)]
/// // ^^^^^^^^^^^^^^^^^^^^^^^^^^^
/// // This attribute is required, as we need to be able to construct
/// // a `Point2D` value from the `{ x: 0.0, y: 0.0 }` GraphQL input value,
/// // received from client-side.
/// system: System,
/// // `Default::default()` value is used, if no
/// // `#[graphql(default = <expression>)]` is specified.
/// #[graphql(skip)]
/// // ^^^^ alternative naming, up to your preference
/// shift: f64,
/// }
/// ```
///
/// [`ScalarValue`]: juniper::ScalarValue
/// [0]: https://spec.graphql.org/October2021#sec-Input-Objects
/// [1]: https://spec.graphql.org/October2021#InputFieldsDefinition
/// [2]: https://spec.graphql.org/October2021#sec-Scalars
#[proc_macro_derive(GraphQLInputObject, attributes(graphql))]
pub fn derive_input_object(input: TokenStream) -> TokenStream {
diagnostic::entry_point(|| {
graphql_input_object::derive::expand(input.into())
.unwrap_or_abort()
.into()
})
}
/// `#[derive(GraphQLEnum)]` macro for deriving a [GraphQL enum][0]
/// implementation for Rust enums.
///
/// The `#[graphql]` helper attribute is used for configuring the derived
/// implementation. Specifying multiple `#[graphql]` attributes on the same
/// definition is totally okay. They all will be treated as a single attribute.
///
/// ```rust
/// use juniper::GraphQLEnum;
///
/// #[derive(GraphQLEnum)]
/// enum Episode {
/// NewHope,
/// Empire,
/// Jedi,
/// }
/// ```
///
/// # Custom name, description and deprecation
///
/// The name of a [GraphQL enum][0] or its [values][1] may be overridden with
/// the `name` attribute's argument. By default, a type name is used or a
/// variant name in `SCREAMING_SNAKE_CASE`.
///
/// The description of a [GraphQL enum][0] or its [values][1] may be specified
/// either with the `description`/`desc` attribute's argument, or with a regular
/// Rust doc comment.
///
/// [GraphQL enum value][1] may be deprecated by specifying the `deprecated`
/// attribute's argument, or with regular a Rust `#[deprecated]` attribute.
///
/// ```rust
/// # #![allow(deprecated)]
/// #
/// # use juniper::GraphQLEnum;
/// #
/// #[derive(GraphQLEnum)]
/// #[graphql(
/// // Rename the type for GraphQL by specifying the name here.
/// name = "AvailableEpisodes",
/// // You may also specify a description here.
/// // If present, doc comments will be ignored.
/// desc = "Possible episodes.",
/// )]
/// enum Episode {
/// /// Doc comment, also acting as description.
/// #[deprecated(note = "Don't use it")]
/// NewHope,
///
/// #[graphql(name = "Jedi", desc = "Arguably the best one in the trilogy")]
/// #[graphql(deprecated = "Don't use it")]
/// Jedai,
///
/// Empire,
/// }
/// ```
///
/// # Renaming policy
///
/// By default, all [GraphQL enum values][1] are renamed in a
/// `SCREAMING_SNAKE_CASE` manner (so a `NewHope` Rust enum variant becomes a
/// `NEW_HOPE` [value][1] in GraphQL schema, and so on). This complies with
/// default GraphQL naming conventions as [demonstrated in spec][0].
///
/// However, if you need for some reason another naming convention, it's
/// possible to do so by using the `rename_all` attribute's argument. At the
/// moment, it supports the following policies only: `SCREAMING_SNAKE_CASE`,
/// `camelCase`, `none` (disables any renaming).
///
/// ```rust
/// # use juniper::GraphQLEnum;
/// #
/// #[derive(GraphQLEnum)]
/// #[graphql(rename_all = "none")] // disables renaming
/// enum Episode {
/// NewHope,
/// Empire,
/// Jedi,
/// }
/// ```
///
/// # Ignoring enum variants
///
/// To omit exposing a Rust enum variant in a GraphQL schema, use the `ignore`
/// attribute's argument directly on that variant. Only ignored Rust enum
/// variants are allowed to contain fields.
///
/// ```rust
/// # use juniper::GraphQLEnum;
/// #
/// #[derive(GraphQLEnum)]
/// enum Episode<T> {
/// NewHope,
/// Empire,
/// Jedi,
/// #[graphql(ignore)]
/// Legends(T),
/// #[graphql(skip)]
/// // ^^^^ alternative naming, up to your preference
/// CloneWars(T),
/// }
/// ```
///
/// # Custom `ScalarValue`
///
/// By default, `#[derive(GraphQLEnum)]` macro generates code, which is generic
/// over a [`ScalarValue`] type. This can be changed with the `scalar`
/// attribute's argument.
///
/// ```rust
/// # use juniper::{DefaultScalarValue, GraphQLEnum};
/// #
/// #[derive(GraphQLEnum)]
/// #[graphql(scalar = DefaultScalarValue)]
/// enum Episode {
/// NewHope,
/// Empire,
/// Jedi,
/// }
/// ```
///
/// [`ScalarValue`]: juniper::ScalarValue
/// [0]: https://spec.graphql.org/October2021#sec-Enums
/// [1]: https://spec.graphql.org/October2021#sec-Enum-Value
#[proc_macro_derive(GraphQLEnum, attributes(graphql))]
pub fn derive_enum(input: TokenStream) -> TokenStream {
diagnostic::entry_point(|| {
graphql_enum::derive::expand(input.into())
.unwrap_or_abort()
.into()
})
}
/// `#[derive(GraphQLScalar)]` macro for deriving a [GraphQL scalar][0]
/// implementation.
///
/// # Transparent delegation
///
/// Quite often we want to create a custom [GraphQL scalar][0] type by just
/// wrapping an existing one, inheriting all its behavior. In Rust, this is
/// often called as ["newtype pattern"][1]. This is achieved by annotating
/// the definition with the `#[graphql(transparent)]` attribute:
/// ```rust
/// # use juniper::{GraphQLObject, GraphQLScalar};
/// #
/// #[derive(GraphQLScalar)]
/// #[graphql(transparent)]
/// struct UserId(String);
///
/// #[derive(GraphQLScalar)]
/// #[graphql(transparent)]
/// struct DroidId {
/// value: String,
/// }
///
/// #[derive(GraphQLObject)]
/// struct Pair {
/// user_id: UserId,
/// droid_id: DroidId,
/// }
/// ```
///
/// The inherited behaviour may also be customized:
/// ```rust
/// # use juniper::GraphQLScalar;
/// #
/// /// Doc comments are used for the GraphQL type description.
/// #[derive(GraphQLScalar)]
/// #[graphql(
/// // Custom GraphQL name.
/// name = "MyUserId",
/// // Description can also specified in the attribute.
/// // This will the doc comment, if one exists.
/// description = "...",
/// // Optional specification URL.
/// specified_by_url = "https://tools.ietf.org/html/rfc4122",
/// // Explicit generic scalar.
/// scalar = S: juniper::ScalarValue,
/// transparent,
/// )]
/// struct UserId(String);
/// ```
///
/// All of the methods inherited from `Newtype`'s field may also be overridden
/// with the attributes described below.
///
/// # Custom resolving
///
/// Customization of a [GraphQL scalar][0] type resolving is possible via
/// `#[graphql(to_output_with = <fn path>)]` attribute:
/// ```rust
/// # use juniper::{GraphQLScalar, ScalarValue, Value};
/// #
/// #[derive(GraphQLScalar)]
/// #[graphql(to_output_with = to_output, transparent)]
/// struct Incremented(i32);
///
/// /// Increments [`Incremented`] before converting into a [`Value`].
/// fn to_output<S: ScalarValue>(v: &Incremented) -> Value<S> {
/// let inc = v.0 + 1;
/// Value::from(inc)
/// }
/// ```
///
/// # Custom parsing
///
/// Customization of a [GraphQL scalar][0] type parsing is possible via
/// `#[graphql(from_input_with = <fn path>)]` attribute:
/// ```rust
/// # use juniper::{DefaultScalarValue, GraphQLScalar, InputValue, ScalarValue};
/// #
/// #[derive(GraphQLScalar)]
/// #[graphql(from_input_with = Self::from_input, transparent)]
/// struct UserId(String);
///
/// impl UserId {
/// /// Checks whether [`InputValue`] is `String` beginning with `id: ` and
/// /// strips it.
/// fn from_input<S: ScalarValue>(
/// input: &InputValue<S>,
/// ) -> Result<Self, String> {
/// // ^^^^^^ must implement `IntoFieldError`
/// input.as_string_value()
/// .ok_or_else(|| format!("Expected `String`, found: {input}"))
/// .and_then(|str| {
/// str.strip_prefix("id: ")
/// .ok_or_else(|| {
/// format!(
/// "Expected `UserId` to begin with `id: `, \
/// found: {input}",
/// )
/// })
/// })
/// .map(|id| Self(id.into()))
/// }
/// }
/// ```
///
/// # Custom token parsing
///
/// Customization of which tokens a [GraphQL scalar][0] type should be parsed is
/// possible via `#[graphql(parse_token_with = <fn path>)]` or
/// `#[graphql(parse_token(<types>)]` attributes:
/// ```rust
/// # use juniper::{
/// # GraphQLScalar, InputValue, ParseScalarResult, ParseScalarValue,
/// # ScalarValue, ScalarToken, Value,
/// # };
/// #
/// #[derive(GraphQLScalar)]
/// #[graphql(
/// to_output_with = to_output,
/// from_input_with = from_input,
/// parse_token_with = parse_token,
/// )]
/// // ^^^^^^^^^^^^^^^^ Can be replaced with `parse_token(String, i32)`, which
/// // tries to parse as `String` first, and then as `i32` if
/// // prior fails.
/// enum StringOrInt {
/// String(String),
/// Int(i32),
/// }
///
/// fn to_output<S: ScalarValue>(v: &StringOrInt) -> Value<S> {
/// match v {
/// StringOrInt::String(s) => Value::scalar(s.to_owned()),
/// StringOrInt::Int(i) => Value::scalar(*i),
/// }
/// }
///
/// fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<StringOrInt, String> {
/// v.as_string_value()
/// .map(|s| StringOrInt::String(s.into()))
/// .or_else(|| v.as_int_value().map(StringOrInt::Int))
/// .ok_or_else(|| format!("Expected `String` or `Int`, found: {v}"))
/// }
///
/// fn parse_token<S: ScalarValue>(value: ScalarToken<'_>) -> ParseScalarResult<S> {
/// <String as ParseScalarValue<S>>::from_str(value)
/// .or_else(|_| <i32 as ParseScalarValue<S>>::from_str(value))
/// }
/// ```
/// > __NOTE:__ Once we provide all 3 custom functions, there is no sense in
/// > following the [newtype pattern][1] anymore.
///
/// # Full behavior
///
/// Instead of providing all custom functions separately, it's possible to
/// provide a module holding the appropriate `to_output()`, `from_input()` and
/// `parse_token()` functions:
/// ```rust
/// # use juniper::{
/// # GraphQLScalar, InputValue, ParseScalarResult, ParseScalarValue,
/// # ScalarValue, ScalarToken, Value,
/// # };
/// #
/// #[derive(GraphQLScalar)]
/// #[graphql(with = string_or_int)]
/// enum StringOrInt {
/// String(String),
/// Int(i32),
/// }
///
/// mod string_or_int {
/// use super::*;
///
/// pub(super) fn to_output<S: ScalarValue>(v: &StringOrInt) -> Value<S> {
/// match v {
/// StringOrInt::String(s) => Value::scalar(s.to_owned()),
/// StringOrInt::Int(i) => Value::scalar(*i),
/// }
/// }
///
/// pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<StringOrInt, String> {
/// v.as_string_value()
/// .map(|s| StringOrInt::String(s.into()))
/// .or_else(|| v.as_int_value().map(StringOrInt::Int))
/// .ok_or_else(|| format!("Expected `String` or `Int`, found: {v}"))
/// }
///
/// pub(super) fn parse_token<S: ScalarValue>(t: ScalarToken<'_>) -> ParseScalarResult<S> {
/// <String as ParseScalarValue<S>>::from_str(t)
/// .or_else(|_| <i32 as ParseScalarValue<S>>::from_str(t))
/// }
/// }
/// #
/// # fn main() {}
/// ```
///
/// A regular `impl` block is also suitable for that:
/// ```rust
/// # use juniper::{
/// # GraphQLScalar, InputValue, ParseScalarResult, ParseScalarValue,
/// # ScalarValue, ScalarToken, Value,
/// # };
/// #
/// #[derive(GraphQLScalar)]
/// // #[graphql(with = Self)] <- default behaviour, so can be omitted
/// enum StringOrInt {
/// String(String),
/// Int(i32),
/// }
///
/// impl StringOrInt {
/// fn to_output<S: ScalarValue>(&self) -> Value<S> {
/// match self {
/// Self::String(s) => Value::scalar(s.to_owned()),
/// Self::Int(i) => Value::scalar(*i),
/// }
/// }
///
/// fn from_input<S>(v: &InputValue<S>) -> Result<Self, String>
/// where
/// S: ScalarValue
/// {
/// v.as_string_value()
/// .map(|s| Self::String(s.into()))
/// .or_else(|| v.as_int_value().map(Self::Int))
/// .ok_or_else(|| format!("Expected `String` or `Int`, found: {v}"))
/// }
///
/// fn parse_token<S>(value: ScalarToken<'_>) -> ParseScalarResult<S>
/// where
/// S: ScalarValue
/// {
/// <String as ParseScalarValue<S>>::from_str(value)
/// .or_else(|_| <i32 as ParseScalarValue<S>>::from_str(value))
/// }
/// }
/// #
/// # fn main() {}
/// ```
///
/// At the same time, any custom function still may be specified separately:
/// ```rust
/// # use juniper::{
/// # GraphQLScalar, InputValue, ParseScalarResult, ScalarValue,
/// # ScalarToken, Value
/// # };
/// #
/// #[derive(GraphQLScalar)]
/// #[graphql(
/// with = string_or_int,
/// parse_token(String, i32)
/// )]
/// enum StringOrInt {
/// String(String),
/// Int(i32),
/// }
///
/// mod string_or_int {
/// use super::*;
///
/// pub(super) fn to_output<S>(v: &StringOrInt) -> Value<S>
/// where
/// S: ScalarValue,
/// {
/// match v {
/// StringOrInt::String(s) => Value::scalar(s.to_owned()),
/// StringOrInt::Int(i) => Value::scalar(*i),
/// }
/// }
///
/// pub(super) fn from_input<S>(v: &InputValue<S>) -> Result<StringOrInt, String>
/// where
/// S: ScalarValue,
/// {
/// v.as_string_value()
/// .map(|s| StringOrInt::String(s.into()))
/// .or_else(|| v.as_int_value().map(StringOrInt::Int))
/// .ok_or_else(|| format!("Expected `String` or `Int`, found: {v}"))
/// }
///
/// // No need in `parse_token()` function.
/// }
/// #
/// # fn main() {}
/// ```
///
/// # Custom `ScalarValue`
///
/// By default, this macro generates code, which is generic over a
/// [`ScalarValue`] type. Concrete [`ScalarValue`] type may be specified via
/// `#[graphql(scalar = <type>)]` attribute.
///
/// It also may be used to provide additional bounds to the [`ScalarValue`]
/// generic, like the following: `#[graphql(scalar = S: Trait)]`.
///
/// # Additional arbitrary trait bounds
///
/// [GraphQL scalar][0] type implementation may be bound with any additional
/// trait bounds via `#[graphql(where(<bounds>))]` attribute, like the
/// following: `#[graphql(where(S: Trait, Self: fmt::Debug + fmt::Display))]`.
///
/// [0]: https://spec.graphql.org/October2021#sec-Scalars
/// [1]: https://rust-unofficial.github.io/patterns/patterns/behavioural/newtype.html
/// [`ScalarValue`]: juniper::ScalarValue
#[proc_macro_derive(GraphQLScalar, attributes(graphql))]
pub fn derive_scalar(input: TokenStream) -> TokenStream {
diagnostic::entry_point(|| {
graphql_scalar::derive::expand(input.into())
.unwrap_or_abort()
.into()
})
}
/// `#[graphql_scalar]` macro.is interchangeable with
/// `#[derive(`[`GraphQLScalar`]`)]` macro, and is used for deriving a
/// [GraphQL scalar][0] implementation.
///
/// ```rust
/// # use juniper::graphql_scalar;
/// #
/// /// Doc comments are used for the GraphQL type description.
/// #[graphql_scalar]
/// #[graphql(
/// // Custom GraphQL name.
/// name = "MyUserId",
/// // Description can also specified in the attribute.
/// // This will the doc comment, if one exists.
/// description = "...",
/// // Optional specification URL.
/// specified_by_url = "https://tools.ietf.org/html/rfc4122",
/// // Explicit generic scalar.
/// scalar = S: juniper::ScalarValue,
/// transparent,
/// )]
/// struct UserId(String);
/// ```
///
/// # Foreign types
///
/// Additionally, `#[graphql_scalar]` can be used directly on foreign types via
/// type alias, without using the [newtype pattern][1].
///
/// > __NOTE:__ To satisfy [orphan rules] you should provide local
/// > [`ScalarValue`] implementation.
///
/// ```rust
/// # mod date {
/// # use std::{fmt, str::FromStr};
/// #
/// # pub struct Date;
/// #
/// # impl FromStr for Date {
/// # type Err = String;
/// #
/// # fn from_str(_: &str) -> Result<Self, Self::Err> {
/// # unimplemented!()
/// # }
/// # }
/// #
/// # impl fmt::Display for Date {
/// # fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
/// # unimplemented!()
/// # }
/// # }
/// # }
/// #
/// # use juniper::DefaultScalarValue as CustomScalarValue;
/// use juniper::{graphql_scalar, InputValue, ScalarValue, Value};
///
/// #[graphql_scalar]
/// #[graphql(
/// with = date_scalar,
/// parse_token(String),
/// scalar = CustomScalarValue,
/// )]
/// // ^^^^^^^^^^^^^^^^^ local `ScalarValue` implementation
/// type Date = date::Date;
/// // ^^^^^^^^^^ type from another crate
///
/// mod date_scalar {
/// use super::*;
///
/// pub(super) fn to_output(v: &Date) -> Value<CustomScalarValue> {
/// Value::scalar(v.to_string())
/// }
///
/// pub(super) fn from_input(v: &InputValue<CustomScalarValue>) -> Result<Date, String> {
/// v.as_string_value()
/// .ok_or_else(|| format!("Expected `String`, found: {v}"))
/// .and_then(|s| s.parse().map_err(|e| format!("Failed to parse `Date`: {e}")))
/// }
/// }
/// #
/// # fn main() {}
/// ```
///
/// [0]: https://spec.graphql.org/October2021#sec-Scalars
/// [1]: https://rust-unofficial.github.io/patterns/patterns/behavioural/newtype.html
/// [orphan rules]: https://bit.ly/3glAGC2
/// [`GraphQLScalar`]: juniper::GraphQLScalar
/// [`ScalarValue`]: juniper::ScalarValue
#[proc_macro_attribute]
pub fn graphql_scalar(attr: TokenStream, body: TokenStream) -> TokenStream {
diagnostic::entry_point_with_preserved_body(body.clone(), || {
graphql_scalar::attr::expand(attr.into(), body.into())
.unwrap_or_abort()
.into()
})
}
/// `#[derive(ScalarValue)]` macro for deriving a [`ScalarValue`]
/// implementation.
///
/// To derive a [`ScalarValue`] on enum you should mark the corresponding enum
/// variants with `as_int`, `as_float`, `as_string`, `into_string`, `as_str` and
/// `as_bool` attribute argumentes (names correspond to [`ScalarValue`] required
/// methods).
///
/// ```rust
/// # use std::fmt;
/// #
/// # use serde::{de, Deserialize, Deserializer, Serialize};
/// # use juniper::ScalarValue;
/// #
/// #[derive(Clone, Debug, PartialEq, ScalarValue, Serialize)]
/// #[serde(untagged)]
/// enum MyScalarValue {
/// #[value(as_float, as_int)]
/// Int(i32),
/// Long(i64),
/// #[value(as_float)]
/// Float(f64),
/// #[value(
/// into_string,
/// as_str,
/// as_string = String::clone,
/// )]
/// // ^^^^^^^^^^^^^ custom resolvers may be provided
/// String(String),
/// #[value(as_bool)]
/// Boolean(bool),
/// }
///
/// impl<'de> Deserialize<'de> for MyScalarValue {
/// fn deserialize<D: Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
/// struct Visitor;
///
/// impl<'de> de::Visitor<'de> for Visitor {
/// type Value = MyScalarValue;
///
/// fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
/// f.write_str("a valid input value")
/// }
///
/// fn visit_bool<E: de::Error>(self, b: bool) -> Result<Self::Value, E> {
/// Ok(MyScalarValue::Boolean(b))
/// }
///
/// fn visit_i32<E: de::Error>(self, n: i32) -> Result<Self::Value, E> {
/// Ok(MyScalarValue::Int(n))
/// }
///
/// fn visit_i64<E: de::Error>(self, n: i64) -> Result<Self::Value, E> {
/// if n <= i64::from(i32::MAX) {
/// self.visit_i32(n.try_into().unwrap())
/// } else {
/// Ok(MyScalarValue::Long(n))
/// }
/// }
///
/// fn visit_u32<E: de::Error>(self, n: u32) -> Result<Self::Value, E> {
/// if n <= i32::MAX as u32 {
/// self.visit_i32(n.try_into().unwrap())
/// } else {
/// self.visit_u64(n.into())
/// }
/// }
///
/// fn visit_u64<E: de::Error>(self, n: u64) -> Result<Self::Value, E> {
/// if n <= i64::MAX as u64 {
/// self.visit_i64(n.try_into().unwrap())
/// } else {
/// // Browser's `JSON.stringify()` serialize all numbers
/// // having no fractional part as integers (no decimal
/// // point), so we must parse large integers as floating
/// // point, otherwise we would error on transferring large
/// // floating point numbers.
/// Ok(MyScalarValue::Float(n as f64))
/// }
/// }
///
/// fn visit_f64<E: de::Error>(self, f: f64) -> Result<Self::Value, E> {
/// Ok(MyScalarValue::Float(f))
/// }
///
/// fn visit_str<E: de::Error>(self, s: &str) -> Result<Self::Value, E> {
/// self.visit_string(s.into())
/// }
///
/// fn visit_string<E: de::Error>(self, s: String) -> Result<Self::Value, E> {
/// Ok(MyScalarValue::String(s))
/// }
/// }
///
/// de.deserialize_any(Visitor)
/// }
/// }
/// ```
///
/// [`ScalarValue`]: juniper::ScalarValue
#[proc_macro_derive(ScalarValue, attributes(value))]
pub fn derive_scalar_value(input: TokenStream) -> TokenStream {
diagnostic::entry_point(|| {
scalar_value::expand_derive(input.into())
.unwrap_or_abort()
.into()
})
}
/// `#[graphql_interface]` macro for generating a [GraphQL interface][1]
/// implementation for traits and its implementers.
///
/// Specifying multiple `#[graphql_interface]` attributes on the same definition
/// is totally okay. They all will be treated as a single attribute.
///
/// [GraphQL interfaces][1] are more like structurally-typed interfaces, while
/// Rust's traits are more like type classes. Using `impl Trait` isn't an
/// option, so you have to cover all trait's methods with type's fields or
/// impl block.
///
/// Another difference between [GraphQL interface][1] type and Rust trait is
/// that the former serves both as an _abstraction_ and a _value downcastable to
/// concrete implementers_, while in Rust, a trait is an _abstraction only_ and
/// you need a separate type to downcast into a concrete implementer, like enum
/// or [trait object][3], because trait doesn't represent a type itself.
/// Macro uses Rust enums only to represent a value type of a
/// [GraphQL interface][1].
///
/// [GraphQL interface][1] can be represented with struct in case methods don't
/// have any arguments:
///
/// ```rust
/// use juniper::{graphql_interface, GraphQLObject};
///
/// // NOTICE: By default a `CharacterValue` enum is generated by macro to represent values of this
/// // GraphQL interface.
/// #[graphql_interface]
/// #[graphql(for = Human)] // enumerating all implementers is mandatory
/// struct Character {
/// id: String,
/// }
///
/// #[derive(GraphQLObject)]
/// #[graphql(impl = CharacterValue)] // notice the enum type name, not trait name
/// struct Human {
/// id: String, // this field is used to resolve Character::id
/// home_planet: String,
/// }
/// ```
///
/// Also [GraphQL interface][1] can be represented with trait:
///
/// ```rust
/// use juniper::{graphql_interface, GraphQLObject};
///
/// // NOTICE: By default a `CharacterValue` enum is generated by macro to represent values of this
/// // GraphQL interface.
/// #[graphql_interface]
/// #[graphql(for = Human)] // enumerating all implementers is mandatory
/// trait Character {
/// fn id(&self) -> &str;
/// }
///
/// #[derive(GraphQLObject)]
/// #[graphql(impl = CharacterValue)] // notice the enum type name, not trait name
/// struct Human {
/// id: String, // this field is used to resolve Character::id
/// home_planet: String,
/// }
/// ```
///
/// > __NOTE:__ Struct or trait representing interface acts only as a blueprint
/// > for names of methods, their arguments and return type, so isn't
/// > actually used at a runtime. But no-one is stopping you from
/// > implementing trait manually for your own usage.
///
/// # Custom name, description, deprecation and argument defaults
///
/// The name of [GraphQL interface][1], its field, or a field argument may be overridden with a
/// `name` attribute's argument. By default, a type name is used or `camelCased` method/argument
/// name.
///
/// The description of [GraphQL interface][1], its field, or a field argument may be specified
/// either with a `description`/`desc` attribute's argument, or with a regular Rust doc comment.
///
/// A field of [GraphQL interface][1] may be deprecated by specifying a `deprecated` attribute's
/// argument, or with regular Rust `#[deprecated]` attribute.
///
/// The default value of a field argument may be specified with a `default` attribute argument (if
/// no exact value is specified then [`Default::default`] is used).
///
/// ```rust
/// # use juniper::graphql_interface;
/// #
/// #[graphql_interface]
/// #[graphql(name = "Character", desc = "Possible episode characters.")]
/// trait Chrctr {
/// #[graphql(name = "id", desc = "ID of the character.")]
/// #[graphql(deprecated = "Don't use it")]
/// fn some_id(
/// &self,
/// #[graphql(name = "number", desc = "Arbitrary number.")]
/// #[graphql(default = 5)]
/// num: i32,
/// ) -> &str;
/// }
///
/// // NOTICE: Rust docs are used as GraphQL description.
/// /// Possible episode characters.
/// #[graphql_interface]
/// trait CharacterWithDocs {
/// /// ID of the character.
/// #[deprecated]
/// fn id(&self, #[graphql(default)] num: i32) -> &str;
/// }
/// ```
///
/// # Interfaces implementing other interfaces
///
/// GraphQL allows implementing interfaces on other interfaces in addition to
/// objects.
///
/// > __NOTE:__ Every interface has to specify all other interfaces/objects it
/// > implements or is implemented for. Missing one of `for = ` or
/// > `impl = ` attributes is an understandable compile-time error.
///
/// ```rust
/// # extern crate juniper;
/// use juniper::{graphql_interface, graphql_object, ID};
///
/// #[graphql_interface]
/// #[graphql(for = [HumanValue, Luke])]
/// struct Node {
/// id: ID,
/// }
///
/// #[graphql_interface]
/// #[graphql(impl = NodeValue, for = Luke)]
/// struct Human {
/// id: ID,
/// home_planet: String,
/// }
///
/// struct Luke {
/// id: ID,
/// }
///
/// #[graphql_object]
/// #[graphql(impl = [HumanValue, NodeValue])]
/// impl Luke {
/// fn id(&self) -> &ID {
/// &self.id
/// }
///
/// // As `String` and `&str` aren't distinguished by
/// // GraphQL spec, you can use them interchangeably.
/// // Same is applied for `Cow<'a, str>`.
/// // ⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄
/// fn home_planet() -> &'static str {
/// "Tatooine"
/// }
/// }
/// ```
///
/// # GraphQL subtyping and additional `null`able fields
///
/// GraphQL allows implementers (both objects and other interfaces) to return
/// "subtypes" instead of an original value. Basically, this allows you to
/// impose additional bounds on the implementation.
///
/// Valid "subtypes" are:
/// - interface implementer instead of an interface itself:
/// - `I implements T` in place of a `T`;
/// - `Vec<I implements T>` in place of a `Vec<T>`.
/// - non-`null` value in place of a `null`able:
/// - `T` in place of a `Option<T>`;
/// - `Vec<T>` in place of a `Vec<Option<T>>`.
///
/// These rules are recursively applied, so `Vec<Vec<I implements T>>` is a
/// valid "subtype" of a `Option<Vec<Option<Vec<Option<T>>>>>`.
///
/// Also, GraphQL allows implementers to add `null`able fields, which aren't
/// present on an original interface.
///
/// ```rust
/// # extern crate juniper;
/// use juniper::{graphql_interface, graphql_object, ID};
///
/// #[graphql_interface]
/// #[graphql(for = [HumanValue, Luke])]
/// struct Node {
/// id: ID,
/// }
///
/// #[graphql_interface]
/// #[graphql(for = HumanConnectionValue)]
/// struct Connection {
/// nodes: Vec<NodeValue>,
/// }
///
/// #[graphql_interface]
/// #[graphql(impl = NodeValue, for = Luke)]
/// struct Human {
/// id: ID,
/// home_planet: String,
/// }
///
/// #[graphql_interface]
/// #[graphql(impl = ConnectionValue)]
/// struct HumanConnection {
/// nodes: Vec<HumanValue>,
/// // ^^^^^^^^^^ notice not `NodeValue`
/// // This can happen, because every `Human` is a `Node` too, so we are
/// // just imposing additional bounds, which still can be resolved with
/// // `... on Connection { nodes }`.
/// }
///
/// struct Luke {
/// id: ID,
/// }
///
/// #[graphql_object]
/// #[graphql(impl = [HumanValue, NodeValue])]
/// impl Luke {
/// fn id(&self) -> &ID {
/// &self.id
/// }
///
/// fn home_planet(language: Option<String>) -> &'static str {
/// // ^^^^^^^^^^^^^^
/// // Notice additional `null`able field, which is missing on `Human`.
/// // Resolving `...on Human { homePlanet }` will provide `None` for
/// // this argument.
/// match language.as_deref() {
/// None | Some("en") => "Tatooine",
/// Some("ko") => "타투인",
/// _ => todo!(),
/// }
/// }
/// }
/// #
/// # fn main() {}
/// ```
///
/// # Renaming policy
///
/// By default, all [GraphQL interface][1] fields and their arguments are renamed
/// via `camelCase` policy (so `fn my_id(&self) -> String` becomes `myId` field
/// in GraphQL schema, and so on). This complies with default GraphQL naming
/// conventions [demonstrated in spec][0].
///
/// However, if you need for some reason apply another naming convention, it's
/// possible to do by using `rename_all` attribute's argument. At the moment it
/// supports the following policies only: `SCREAMING_SNAKE_CASE`, `camelCase`,
/// `none` (disables any renaming).
///
/// ```rust
/// # use juniper::{graphql_interface, graphql_object};
/// #
/// #[graphql_interface]
/// #[graphql(for = Human, rename_all = "none")] // disables renaming
/// trait Character {
/// // NOTICE: In the generated GraphQL schema this field and its argument
/// // will be `detailed_info` and `info_kind`.
/// fn detailed_info(&self, info_kind: String) -> String;
/// }
///
/// struct Human {
/// id: String,
/// home_planet: String,
/// }
///
/// #[graphql_object]
/// #[graphql(impl = CharacterValue, rename_all = "none")]
/// impl Human {
/// fn id(&self) -> &str {
/// &self.id
/// }
///
/// fn home_planet(&self) -> &str {
/// &self.home_planet
/// }
///
/// // You can return `&str` even if trait definition returns `String`.
/// fn detailed_info(&self, info_kind: String) -> &str {
/// (info_kind == "planet")
/// .then_some(&self.home_planet)
/// .unwrap_or(&self.id)
/// }
/// }
/// ```
///
/// # Ignoring trait methods
///
/// To omit some trait method to be assumed as a [GraphQL interface][1] field
/// and ignore it, use an `ignore` attribute's argument directly on that method.
///
/// ```rust
/// # use juniper::graphql_interface;
/// #
/// #[graphql_interface]
/// trait Character {
/// fn id(&self) -> &str;
///
/// #[graphql(ignore)]
/// fn kaboom(&mut self);
/// }
/// ```
///
/// # Custom context
///
/// By default, the generated implementation tries to infer [`Context`] type from signatures of
/// trait methods, and uses [unit type `()`][4] if signatures contains no [`Context`] arguments.
///
/// If [`Context`] type cannot be inferred or is inferred incorrectly, then specify it explicitly
/// with `context` attribute's argument.
///
/// If trait method represents a [GraphQL interface][1] field and its argument is named as `context`
/// or `ctx` then this argument is assumed as [`Context`] and will be omitted in GraphQL schema.
/// Additionally, any argument may be marked as [`Context`] with a `context` attribute's argument.
///
/// ```rust
/// # use std::collections::HashMap;
/// # use juniper::{graphql_interface, graphql_object};
/// #
/// struct Database {
/// humans: HashMap<String, Human>,
/// droids: HashMap<String, Droid>,
/// }
/// impl juniper::Context for Database {}
///
/// #[graphql_interface]
/// #[graphql(for = [Human, Droid], Context = Database)]
/// trait Character {
/// fn id<'db>(&self, ctx: &'db Database) -> Option<&'db str>;
/// fn info<'db>(&self, #[graphql(context)] db: &'db Database) -> Option<&'db str>;
/// }
///
/// struct Human {
/// id: String,
/// home_planet: String,
/// }
/// #[graphql_object]
/// #[graphql(impl = CharacterValue, Context = Database)]
/// impl Human {
/// fn id<'db>(&self, context: &'db Database) -> Option<&'db str> {
/// context.humans.get(&self.id).map(|h| h.id.as_str())
/// }
/// fn info<'db>(&self, #[graphql(context)] db: &'db Database) -> Option<&'db str> {
/// db.humans.get(&self.id).map(|h| h.home_planet.as_str())
/// }
/// fn home_planet(&self) -> &str {
/// &self.home_planet
/// }
/// }
///
/// struct Droid {
/// id: String,
/// primary_function: String,
/// }
/// #[graphql_object]
/// #[graphql(impl = CharacterValue, Context = Database)]
/// impl Droid {
/// fn id<'db>(&self, ctx: &'db Database) -> Option<&'db str> {
/// ctx.droids.get(&self.id).map(|h| h.id.as_str())
/// }
/// fn info<'db>(&self, #[graphql(context)] db: &'db Database) -> Option<&'db str> {
/// db.droids.get(&self.id).map(|h| h.primary_function.as_str())
/// }
/// fn primary_function(&self) -> &str {
/// &self.primary_function
/// }
/// }
/// ```
///
/// # Using `Executor`
///
/// If an [`Executor`] is required in a trait method to resolve a [GraphQL interface][1] field,
/// specify it as an argument named as `executor` or explicitly marked with an `executor`
/// attribute's argument. Such method argument will be omitted in GraphQL schema.
///
/// However, this requires to explicitly parametrize over [`ScalarValue`], as [`Executor`] does so.
///
/// ```rust
/// # use juniper::{graphql_interface, graphql_object, Executor, ScalarValue};
/// #
/// #[graphql_interface]
/// // NOTICE: Specifying `ScalarValue` as existing type parameter.
/// #[graphql(for = Human, scalar = S)]
/// trait Character<S: ScalarValue> {
/// fn id<'a>(&self, executor: &'a Executor<'_, '_, (), S>) -> &'a str;
///
/// fn name<'b>(
/// &'b self,
/// #[graphql(executor)] another: &Executor<'_, '_, (), S>,
/// ) -> &'b str;
/// }
///
/// struct Human {
/// id: String,
/// name: String,
/// }
/// #[graphql_object]
/// #[graphql(scalar = S: ScalarValue, impl = CharacterValue<S>)]
/// impl Human {
/// async fn id<'a, S>(&self, executor: &'a Executor<'_, '_, (), S>) -> &'a str
/// where
/// S: ScalarValue,
/// {
/// executor.look_ahead().field_name()
/// }
///
/// async fn name<'b, S>(&'b self, _executor: &Executor<'_, '_, (), S>) -> &'b str {
/// &self.name
/// }
/// }
/// ```
///
/// # Custom `ScalarValue`
///
/// By default, `#[graphql_interface]` macro generates code, which is generic
/// over a [`ScalarValue`] type. This may introduce a problem when at least one
/// of [GraphQL interface][1] implementers is restricted to a concrete
/// [`ScalarValue`] type in its implementation. To resolve such problem, a
/// concrete [`ScalarValue`] type should be specified with a `scalar`
/// attribute's argument.
///
/// ```rust
/// # use juniper::{graphql_interface, DefaultScalarValue, GraphQLObject};
/// #
/// #[graphql_interface]
/// // NOTICE: Removing `Scalar` argument will fail compilation.
/// #[graphql(for = Human, scalar = DefaultScalarValue)]
/// trait Character {
/// fn id(&self) -> &str;
/// }
///
/// #[derive(GraphQLObject)]
/// #[graphql(impl = CharacterValue, scalar = DefaultScalarValue)]
/// struct Human {
/// id: String,
/// home_planet: String,
/// }
/// ```
///
/// [`Context`]: juniper::Context
/// [`Executor`]: juniper::Executor
/// [`ScalarValue`]: juniper::ScalarValue
/// [0]: https://spec.graphql.org/October2021
/// [1]: https://spec.graphql.org/October2021#sec-Interfaces
/// [2]: https://doc.rust-lang.org/stable/reference/items/traits.html#object-safety
/// [3]: https://doc.rust-lang.org/stable/reference/types/trait-object.html
/// [4]: https://doc.rust-lang.org/stable/std/primitive.unit.html
#[proc_macro_attribute]
pub fn graphql_interface(attr: TokenStream, body: TokenStream) -> TokenStream {
diagnostic::entry_point_with_preserved_body(body.clone(), || {
self::graphql_interface::attr::expand(attr.into(), body.into())
.unwrap_or_abort()
.into()
})
}
/// `#[derive(GraphQLInterface)]` macro for generating a [GraphQL interface][1]
/// implementation for traits and its implementers.
///
/// This macro is applicable only to structs and useful in case [interface][1]
/// fields don't have any arguments:
///
/// ```rust
/// use juniper::{GraphQLInterface, GraphQLObject};
///
/// // NOTICE: By default a `CharacterValue` enum is generated by macro to represent values of this
/// // GraphQL interface.
/// #[derive(GraphQLInterface)]
/// #[graphql(for = Human)] // enumerating all implementers is mandatory
/// struct Character {
/// id: String,
/// }
///
/// #[derive(GraphQLObject)]
/// #[graphql(impl = CharacterValue)] // notice the enum type name, not trait name
/// struct Human {
/// id: String, // this field is used to resolve Character::id
/// home_planet: String,
/// }
/// ```
///
/// For more info and possibilities see [`#[graphql_interface]`][0] macro.
///
/// [0]: crate::graphql_interface
/// [1]: https://spec.graphql.org/October2021#sec-Interfaces
#[proc_macro_derive(GraphQLInterface, attributes(graphql))]
pub fn derive_interface(body: TokenStream) -> TokenStream {
diagnostic::entry_point(|| {
self::graphql_interface::derive::expand(body.into())
.unwrap_or_abort()
.into()
})
}
/// `#[derive(GraphQLObject)]` macro for deriving a [GraphQL object][1]
/// implementation for structs.
///
/// The `#[graphql]` helper attribute is used for configuring the derived
/// implementation. Specifying multiple `#[graphql]` attributes on the same
/// definition is totally okay. They all will be treated as a single attribute.
///
/// ```
/// use juniper::GraphQLObject;
///
/// #[derive(GraphQLObject)]
/// struct Query {
/// // NOTICE: By default, field names will be converted to `camelCase`.
/// // In the generated GraphQL schema this field will be available
/// // as `apiVersion`.
/// api_version: &'static str,
/// }
/// ```
///
/// # Custom name, description and deprecation
///
/// The name of [GraphQL object][1] or its field may be overridden with a `name`
/// attribute's argument. By default, a type name is used or `camelCased` field
/// name.
///
/// The description of [GraphQL object][1] or its field may be specified either
/// with a `description`/`desc` attribute's argument, or with a regular Rust doc
/// comment.
///
/// A field of [GraphQL object][1] may be deprecated by specifying a
/// `deprecated` attribute's argument, or with regular Rust `#[deprecated]`
/// attribute.
///
/// ```
/// # use juniper::GraphQLObject;
/// #
/// #[derive(GraphQLObject)]
/// #[graphql(
/// // Rename the type for GraphQL by specifying the name here.
/// name = "Human",
/// // You may also specify a description here.
/// // If present, doc comments will be ignored.
/// desc = "Possible episode human.",
/// )]
/// struct HumanWithAttrs {
/// #[graphql(name = "id", desc = "ID of the human.")]
/// #[graphql(deprecated = "Don't use it")]
/// some_id: String,
/// }
///
/// // Rust docs are used as GraphQL description.
/// /// Possible episode human.
/// #[derive(GraphQLObject)]
/// struct HumanWithDocs {
/// // Doc comments also work on fields.
/// /// ID of the human.
/// #[deprecated]
/// id: String,
/// }
/// ```
///
/// # Renaming policy
///
/// By default, all [GraphQL object][1] fields are renamed via `camelCase`
/// policy (so `api_version: String` becomes `apiVersion` field in GraphQL
/// schema, and so on). This complies with default GraphQL naming conventions
/// [demonstrated in spec][0].
///
/// However, if you need for some reason apply another naming convention, it's
/// possible to do by using `rename_all` attribute's argument. At the moment it
/// supports the following policies only: `SCREAMING_SNAKE_CASE`, `camelCase`,
/// `none` (disables any renaming).
///
/// ```
/// # use juniper::GraphQLObject;
/// #
/// #[derive(GraphQLObject)]
/// #[graphql(rename_all = "none")] // disables renaming
/// struct Query {
/// // NOTICE: In the generated GraphQL schema this field will be available
/// // as `api_version`.
/// api_version: String,
/// }
/// ```
///
/// # Ignoring struct fields
///
/// To omit exposing a struct field in the GraphQL schema, use an `ignore`
/// attribute's argument directly on that field.
///
/// ```
/// # use juniper::GraphQLObject;
/// #
/// #[derive(GraphQLObject)]
/// struct Human {
/// id: String,
/// #[graphql(ignore)]
/// home_planet: String,
/// #[graphql(skip)]
/// // ^^^^ alternative naming, up to your preference
/// password_hash: String,
/// }
/// ```
///
/// # Custom `ScalarValue`
///
/// By default, `#[derive(GraphQLObject)]` macro generates code, which is
/// generic over a [`ScalarValue`] type. This may introduce a problem when at
/// least one of its fields is restricted to a concrete [`ScalarValue`] type in
/// its implementation. To resolve such problem, a concrete [`ScalarValue`] type
/// should be specified with a `scalar` attribute's argument.
///
/// ```
/// # use juniper::{DefaultScalarValue, GraphQLObject};
/// #
/// #[derive(GraphQLObject)]
/// // NOTICE: Removing `scalar` argument will fail compilation.
/// #[graphql(scalar = DefaultScalarValue)]
/// struct Human {
/// id: String,
/// helper: Droid,
/// }
///
/// #[derive(GraphQLObject)]
/// #[graphql(scalar = DefaultScalarValue)]
/// struct Droid {
/// id: String,
/// }
/// ```
///
/// [`ScalarValue`]: juniper::ScalarValue
/// [1]: https://spec.graphql.org/October2021#sec-Objects
#[proc_macro_derive(GraphQLObject, attributes(graphql))]
pub fn derive_object(body: TokenStream) -> TokenStream {
diagnostic::entry_point(|| {
self::graphql_object::derive::expand(body.into())
.unwrap_or_abort()
.into()
})
}
/// `#[graphql_object]` macro for generating a [GraphQL object][1]
/// implementation for structs with computable field resolvers (declared via
/// a regular Rust `impl` block).
///
/// It enables you to write GraphQL field resolvers for a type by declaring a
/// regular Rust `impl` block. Under the hood, the macro implements
/// [`GraphQLType`]/[`GraphQLValue`] traits.
///
/// Specifying multiple `#[graphql_object]` attributes on the same definition
/// is totally okay. They all will be treated as a single attribute.
///
/// ```
/// use juniper::graphql_object;
///
/// // We can declare the type as a plain struct without any members.
/// struct Query;
///
/// #[graphql_object]
/// impl Query {
/// // WARNING: Only GraphQL fields can be specified in this `impl` block.
/// // If normal methods are required on the struct, they can be
/// // defined either in a separate "normal" `impl` block, or
/// // marked with `#[graphql(ignore)]` attribute.
///
/// // This defines a simple, static field which does not require any
/// // context.
/// // Such field can return any value that implements `GraphQLType` and
/// // `GraphQLValue` traits.
/// //
/// // NOTICE: By default, field names will be converted to `camelCase`.
/// // In the generated GraphQL schema this field will be available
/// // as `apiVersion`.
/// fn api_version() -> &'static str {
/// "0.1"
/// }
///
/// // This field takes two arguments.
/// // GraphQL arguments are just regular function parameters.
/// //
/// // NOTICE: In `juniper`, arguments are non-nullable by default. For
/// // optional arguments, you have to specify them as `Option<_>`.
/// async fn add(a: f64, b: f64, c: Option<f64>) -> f64 {
/// a + b + c.unwrap_or(0.0)
/// }
/// }
/// ```
///
/// # Accessing self
///
/// Fields may also have a `self` receiver.
///
/// ```
/// # use juniper::graphql_object;
/// #
/// struct Person {
/// first_name: String,
/// last_name: String,
/// }
///
/// #[graphql_object]
/// impl Person {
/// fn first_name(&self) -> &str {
/// &self.first_name
/// }
///
/// fn last_name(&self) -> &str {
/// &self.last_name
/// }
///
/// fn full_name(&self) -> String {
/// self.build_full_name()
/// }
///
/// // This method is useful only to define GraphQL fields, but is not
/// // a field itself, so we ignore it in schema.
/// #[graphql(ignore)] // or `#[graphql(skip)]`, up to your preference
/// fn build_full_name(&self) -> String {
/// format!("{} {}", self.first_name, self.last_name)
/// }
/// }
/// ```
///
/// # Custom name, description, deprecation and argument defaults
///
/// The name of [GraphQL object][1], its field, or a field argument may be
/// overridden with a `name` attribute's argument. By default, a type name is
/// used or `camelCased` method/argument name.
///
/// The description of [GraphQL object][1], its field, or a field argument may
/// be specified either with a `description`/`desc` attribute's argument, or
/// with a regular Rust doc comment.
///
/// A field of [GraphQL object][1] may be deprecated by specifying a
/// `deprecated` attribute's argument, or with regular Rust `#[deprecated]`
/// attribute.
///
/// The default value of a field argument may be specified with a `default`
/// attribute argument (if no exact value is specified then [`Default::default`]
/// is used).
///
/// ```
/// # use juniper::graphql_object;
/// #
/// struct HumanWithAttrs;
///
/// #[graphql_object]
/// #[graphql(
/// // Rename the type for GraphQL by specifying the name here.
/// name = "Human",
/// // You may also specify a description here.
/// // If present, doc comments will be ignored.
/// desc = "Possible episode human.",
/// )]
/// impl HumanWithAttrs {
/// #[graphql(name = "id", desc = "ID of the human.")]
/// #[graphql(deprecated = "Don't use it")]
/// fn some_id(
/// &self,
/// #[graphql(name = "number", desc = "Arbitrary number.")]
/// // You may specify default values.
/// // A default can be any valid expression that yields the right type.
/// #[graphql(default = 5)]
/// num: i32,
/// ) -> &str {
/// "Don't use me!"
/// }
/// }
///
/// struct HumanWithDocs;
///
/// // Rust docs are used as GraphQL description.
/// /// Possible episode human.
/// #[graphql_object]
/// impl HumanWithDocs {
/// // Doc comments also work on fields.
/// /// ID of the human.
/// #[deprecated]
/// fn id(
/// &self,
/// // If expression is not specified then `Default::default()` is used.
/// #[graphql(default)] num: i32,
/// ) -> &str {
/// "Deprecated"
/// }
/// }
/// ```
///
/// # Renaming policy
///
/// By default, all [GraphQL object][1] fields and their arguments are renamed
/// via `camelCase` policy (so `fn api_version() -> String` becomes `apiVersion`
/// field in GraphQL schema, and so on). This complies with default GraphQL
/// naming conventions [demonstrated in spec][0].
///
/// However, if you need for some reason apply another naming convention, it's
/// possible to do by using `rename_all` attribute's argument. At the moment it
/// supports the following policies only: `SCREAMING_SNAKE_CASE`, `camelCase`,
/// `none` (disables any renaming).
///
/// ```
/// # use juniper::graphql_object;
/// #
/// struct Query;
///
/// #[graphql_object]
/// #[graphql(rename_all = "none")] // disables renaming
/// impl Query {
/// // NOTICE: In the generated GraphQL schema this field will be available
/// // as `api_version`.
/// fn api_version() -> &'static str {
/// "0.1"
/// }
///
/// // NOTICE: In the generated GraphQL schema these field arguments will be
/// // available as `arg_a` and `arg_b`.
/// async fn add(arg_a: f64, arg_b: f64, c: Option<f64>) -> f64 {
/// arg_a + arg_b + c.unwrap_or(0.0)
/// }
/// }
/// ```
///
/// # Ignoring methods
///
/// To omit some method to be assumed as a [GraphQL object][1] field and ignore
/// it, use an `ignore` attribute's argument directly on that method.
///
/// ```
/// # use juniper::graphql_object;
/// #
/// struct Human(String);
///
/// #[graphql_object]
/// impl Human {
/// fn id(&self) -> &str {
/// &self.0
/// }
///
/// #[graphql(ignore)]
/// fn kaboom(&mut self) {}
/// }
/// ```
///
/// # Custom context
///
/// By default, the generated implementation tries to infer [`Context`] type
/// from signatures of `impl` block methods, and uses [unit type `()`][4] if
/// signatures contains no [`Context`] arguments.
///
/// If [`Context`] type cannot be inferred or is inferred incorrectly, then
/// specify it explicitly with `context` attribute's argument.
///
/// If method argument is named as `context` or `ctx` then this argument is
/// assumed as [`Context`] and will be omitted in GraphQL schema.
/// Additionally, any argument may be marked as [`Context`] with a `context`
/// attribute's argument.
///
/// ```
/// # use std::collections::HashMap;
/// # use juniper::graphql_object;
/// #
/// struct Database {
/// humans: HashMap<String, Human>,
/// }
/// impl juniper::Context for Database {}
///
/// struct Human {
/// id: String,
/// home_planet: String,
/// }
///
/// #[graphql_object]
/// #[graphql(context = Database)]
/// impl Human {
/// fn id<'db>(&self, context: &'db Database) -> Option<&'db str> {
/// context.humans.get(&self.id).map(|h| h.id.as_str())
/// }
/// fn info<'db>(&self, context: &'db Database) -> Option<&'db str> {
/// context.humans.get(&self.id).map(|h| h.home_planet.as_str())
/// }
/// }
/// ```
///
/// # Using `Executor`
///
/// If an [`Executor`] is required in a method to resolve a [GraphQL object][1]
/// field, specify it as an argument named as `executor` or explicitly marked
/// with an `executor` attribute's argument. Such method argument will be
/// omitted in GraphQL schema.
///
/// However, this requires to explicitly parametrize over [`ScalarValue`], as
/// [`Executor`] does so.
///
/// ```
/// # use juniper::{graphql_object, Executor, GraphQLObject, ScalarValue};
/// #
/// struct Human {
/// name: String,
/// }
///
/// #[graphql_object]
/// // NOTICE: Specifying `ScalarValue` as custom named type parameter.
/// // Its name should be similar to the one used in methods.
/// #[graphql(scalar = S: ScalarValue)]
/// impl Human {
/// async fn id<'a, S: ScalarValue>(
/// &self,
/// executor: &'a Executor<'_, '_, (), S>,
/// ) -> &'a str {
/// executor.look_ahead().field_name()
/// }
///
/// fn name<'b, S: ScalarValue>(
/// &'b self,
/// #[graphql(executor)] _another: &Executor<'_, '_, (), S>,
/// ) -> &'b str {
/// &self.name
/// }
/// }
/// ```
///
/// # Custom `ScalarValue`
///
/// By default, `#[graphql_object]` macro generates code, which is generic over
/// a [`ScalarValue`] type. This may introduce a problem when at least one of
/// its fields is restricted to a concrete [`ScalarValue`] type in its
/// implementation. To resolve such problem, a concrete [`ScalarValue`] type
/// should be specified with a `scalar` attribute's argument.
///
/// ```
/// # use juniper::{graphql_object, DefaultScalarValue, GraphQLObject};
/// #
/// struct Human(String);
///
/// #[graphql_object]
/// // NOTICE: Removing `scalar` argument will fail compilation.
/// #[graphql(scalar = DefaultScalarValue)]
/// impl Human {
/// fn id(&self) -> &str {
/// &self.0
/// }
///
/// fn helper(&self) -> Droid {
/// Droid {
/// id: self.0.clone(),
/// }
/// }
/// }
///
/// #[derive(GraphQLObject)]
/// #[graphql(scalar = DefaultScalarValue)]
/// struct Droid {
/// id: String,
/// }
/// ```
///
/// [`Context`]: juniper::Context
/// [`Executor`]: juniper::Executor
/// [`GraphQLType`]: juniper::GraphQLType
/// [`GraphQLValue`]: juniper::GraphQLValue
/// [`ScalarValue`]: juniper::ScalarValue
/// [0]: https://spec.graphql.org/October2021
/// [1]: https://spec.graphql.org/October2021#sec-Objects
#[proc_macro_attribute]
pub fn graphql_object(attr: TokenStream, body: TokenStream) -> TokenStream {
diagnostic::entry_point_with_preserved_body(body.clone(), || {
self::graphql_object::attr::expand(attr.into(), body.into())
.unwrap_or_abort()
.into()
})
}
/// `#[graphql_subscription]` macro for generating a [GraphQL subscription][1]
/// implementation for structs with computable field resolvers (declared via
/// a regular Rust `impl` block).
///
/// It enables you to write GraphQL field resolvers for a type by declaring a
/// regular Rust `impl` block. Under the hood, the macro implements
/// [`GraphQLType`]/[`GraphQLSubscriptionValue`] traits.
///
/// Specifying multiple `#[graphql_subscription]` attributes on the same
/// definition is totally okay. They all will be treated as a single attribute.
///
/// This macro is similar to [`#[graphql_object]` macro](macro@graphql_object)
/// and has all its properties, but requires methods to be `async` and return
/// [`Stream`] of values instead of a value itself.
///
/// ```
/// # use futures::stream::{self, BoxStream};
/// use juniper::graphql_subscription;
///
/// // We can declare the type as a plain struct without any members.
/// struct Subscription;
///
/// #[graphql_subscription]
/// impl Subscription {
/// // WARNING: Only GraphQL fields can be specified in this `impl` block.
/// // If normal methods are required on the struct, they can be
/// // defined either in a separate "normal" `impl` block, or
/// // marked with `#[graphql(ignore)]` attribute.
///
/// // This defines a simple, static field which does not require any
/// // context.
/// // Such field can return a `Stream` of any value implementing
/// // `GraphQLType` and `GraphQLValue` traits.
/// //
/// // NOTICE: Method must be `async`.
/// async fn api_version() -> BoxStream<'static, &'static str> {
/// Box::pin(stream::once(async { "0.1" }))
/// }
/// }
/// ```
///
/// [`GraphQLType`]: juniper::GraphQLType
/// [`GraphQLSubscriptionValue`]: juniper::GraphQLSubscriptionValue
/// [`Stream`]: futures::Stream
/// [1]: https://spec.graphql.org/October2021#sec-Subscription
#[proc_macro_attribute]
pub fn graphql_subscription(attr: TokenStream, body: TokenStream) -> TokenStream {
diagnostic::entry_point_with_preserved_body(body.clone(), || {
self::graphql_subscription::attr::expand(attr.into(), body.into())
.unwrap_or_abort()
.into()
})
}
/// `#[derive(GraphQLUnion)]` macro for deriving a [GraphQL union][1] implementation for enums and
/// structs.
///
/// The `#[graphql]` helper attribute is used for configuring the derived implementation. Specifying
/// multiple `#[graphql]` attributes on the same definition is totally okay. They all will be
/// treated as a single attribute.
///
/// ```
/// use derive_more::From;
/// use juniper::{GraphQLObject, GraphQLUnion};
///
/// #[derive(GraphQLObject)]
/// struct Human {
/// id: String,
/// home_planet: String,
/// }
///
/// #[derive(GraphQLObject)]
/// struct Droid {
/// id: String,
/// primary_function: String,
/// }
///
/// #[derive(From, GraphQLUnion)]
/// enum CharacterEnum {
/// Human(Human),
/// Droid(Droid),
/// }
/// ```
///
/// # Custom name and description
///
/// The name of [GraphQL union][1] may be overriden with a `name` attribute's argument. By default,
/// a type name is used.
///
/// The description of [GraphQL union][1] may be specified either with a `description`/`desc`
/// attribute's argument, or with a regular Rust doc comment.
///
/// ```
/// # use juniper::{GraphQLObject, GraphQLUnion};
/// #
/// # #[derive(GraphQLObject)]
/// # struct Human {
/// # id: String,
/// # home_planet: String,
/// # }
/// #
/// # #[derive(GraphQLObject)]
/// # struct Droid {
/// # id: String,
/// # primary_function: String,
/// # }
/// #
/// #[derive(GraphQLUnion)]
/// #[graphql(name = "Character", desc = "Possible episode characters.")]
/// enum Chrctr {
/// Human(Human),
/// Droid(Droid),
/// }
///
/// // NOTICE: Rust docs are used as GraphQL description.
/// /// Possible episode characters.
/// #[derive(GraphQLUnion)]
/// enum CharacterWithDocs {
/// Human(Human),
/// Droid(Droid),
/// }
///
/// // NOTICE: `description` argument takes precedence over Rust docs.
/// /// Not a GraphQL description anymore.
/// #[derive(GraphQLUnion)]
/// #[graphql(description = "Possible episode characters.")]
/// enum CharacterWithDescription {
/// Human(Human),
/// Droid(Droid),
/// }
/// ```
///
/// # Custom context
///
/// By default, the generated implementation uses [unit type `()`][4] as [`Context`]. To use a
/// custom [`Context`] type for [GraphQL union][1] variants types or external resolver functions,
/// specify it with `context` attribute's argument.
///
/// ```
/// # use juniper::{GraphQLObject, GraphQLUnion};
/// #
/// #[derive(GraphQLObject)]
/// #[graphql(Context = CustomContext)]
/// struct Human {
/// id: String,
/// home_planet: String,
/// }
///
/// #[derive(GraphQLObject)]
/// #[graphql(Context = CustomContext)]
/// struct Droid {
/// id: String,
/// primary_function: String,
/// }
///
/// pub struct CustomContext;
/// impl juniper::Context for CustomContext {}
///
/// #[derive(GraphQLUnion)]
/// #[graphql(Context = CustomContext)]
/// enum Character {
/// Human(Human),
/// Droid(Droid),
/// }
/// ```
///
/// # Custom `ScalarValue`
///
/// By default, this macro generates code, which is generic over a
/// [`ScalarValue`] type. This may introduce a problem when at least one of
/// [GraphQL union][1] variants is restricted to a concrete [`ScalarValue`] type
/// in its implementation. To resolve such problem, a concrete [`ScalarValue`]
/// type should be specified with a `scalar` attribute's argument.
///
/// ```
/// # use juniper::{DefaultScalarValue, GraphQLObject, GraphQLUnion};
/// #
/// #[derive(GraphQLObject)]
/// #[graphql(scalar = DefaultScalarValue)]
/// struct Human {
/// id: String,
/// home_planet: String,
/// }
///
/// #[derive(GraphQLObject)]
/// struct Droid {
/// id: String,
/// primary_function: String,
/// }
///
/// // NOTICE: Removing `Scalar` argument will fail compilation.
/// #[derive(GraphQLUnion)]
/// #[graphql(scalar = DefaultScalarValue)]
/// enum Character {
/// Human(Human),
/// Droid(Droid),
/// }
/// ```
///
/// # Ignoring enum variants
///
/// To omit exposing an enum variant in the GraphQL schema, use an `ignore`
/// attribute's argument directly on that variant.
///
/// > __WARNING__:
/// > It's the _library user's responsibility_ to ensure that ignored enum variant is _never_
/// > returned from resolvers, otherwise resolving the GraphQL query will __panic at runtime__.
///
/// ```
/// # use std::marker::PhantomData;
/// use derive_more::From;
/// use juniper::{GraphQLObject, GraphQLUnion};
///
/// #[derive(GraphQLObject)]
/// struct Human {
/// id: String,
/// home_planet: String,
/// }
///
/// #[derive(GraphQLObject)]
/// struct Droid {
/// id: String,
/// primary_function: String,
/// }
///
/// #[derive(From, GraphQLUnion)]
/// enum Character<S> {
/// Human(Human),
/// Droid(Droid),
/// #[from(ignore)]
/// #[graphql(ignore)]
/// _State(PhantomData<S>),
/// }
/// ```
///
/// # External resolver functions
///
/// To use a custom logic for resolving a [GraphQL union][1] variant, an external resolver function
/// may be specified with:
/// - either a `with` attribute's argument on an enum variant;
/// - or an `on` attribute's argument on an enum/struct itself.
///
/// ```
/// # use juniper::{GraphQLObject, GraphQLUnion};
/// #
/// #[derive(GraphQLObject)]
/// #[graphql(Context = CustomContext)]
/// struct Human {
/// id: String,
/// home_planet: String,
/// }
///
/// #[derive(GraphQLObject)]
/// #[graphql(Context = CustomContext)]
/// struct Droid {
/// id: String,
/// primary_function: String,
/// }
///
/// pub struct CustomContext {
/// droid: Droid,
/// }
/// impl juniper::Context for CustomContext {}
///
/// #[derive(GraphQLUnion)]
/// #[graphql(Context = CustomContext)]
/// enum Character {
/// Human(Human),
/// #[graphql(with = Character::droid_from_context)]
/// Droid(Droid),
/// }
///
/// impl Character {
/// // NOTICE: The function signature must contain `&self` and `&Context`,
/// // and return `Option<&VariantType>`.
/// fn droid_from_context<'c>(&self, ctx: &'c CustomContext) -> Option<&'c Droid> {
/// Some(&ctx.droid)
/// }
/// }
///
/// #[derive(GraphQLUnion)]
/// #[graphql(Context = CustomContext)]
/// #[graphql(on Droid = CharacterWithoutDroid::droid_from_context)]
/// enum CharacterWithoutDroid {
/// Human(Human),
/// #[graphql(ignore)]
/// Droid,
/// }
///
/// impl CharacterWithoutDroid {
/// fn droid_from_context<'c>(&self, ctx: &'c CustomContext) -> Option<&'c Droid> {
/// if let Self::Droid = self {
/// Some(&ctx.droid)
/// } else {
/// None
/// }
/// }
/// }
/// ```
///
/// # Deriving structs
///
/// Specifying external resolver functions is mandatory for using a struct as a [GraphQL union][1],
/// because this is the only way to declare [GraphQL union][1] variants in this case.
///
/// ```
/// # use std::collections::HashMap;
/// # use juniper::{GraphQLObject, GraphQLUnion};
/// #
/// #[derive(GraphQLObject)]
/// #[graphql(Context = Database)]
/// struct Human {
/// id: String,
/// home_planet: String,
/// }
///
/// #[derive(GraphQLObject)]
/// #[graphql(Context = Database)]
/// struct Droid {
/// id: String,
/// primary_function: String,
/// }
///
/// struct Database {
/// humans: HashMap<String, Human>,
/// droids: HashMap<String, Droid>,
/// }
/// impl juniper::Context for Database {}
///
/// #[derive(GraphQLUnion)]
/// #[graphql(
/// Context = Database,
/// on Human = Character::get_human,
/// on Droid = Character::get_droid,
/// )]
/// struct Character {
/// id: String,
/// }
///
/// impl Character {
/// fn get_human<'db>(&self, ctx: &'db Database) -> Option<&'db Human>{
/// ctx.humans.get(&self.id)
/// }
///
/// fn get_droid<'db>(&self, ctx: &'db Database) -> Option<&'db Droid>{
/// ctx.droids.get(&self.id)
/// }
/// }
/// ```
///
/// [`Context`]: juniper::Context
/// [`ScalarValue`]: juniper::ScalarValue
/// [1]: https://spec.graphql.org/October2021#sec-Unions
/// [4]: https://doc.rust-lang.org/stable/std/primitive.unit.html
#[proc_macro_derive(GraphQLUnion, attributes(graphql))]
pub fn derive_union(body: TokenStream) -> TokenStream {
diagnostic::entry_point(|| {
self::graphql_union::derive::expand(body.into())
.unwrap_or_abort()
.into()
})
}
/// `#[graphql_union]` macro for deriving a [GraphQL union][1] implementation for traits.
///
/// Specifying multiple `#[graphql_union]` attributes on the same definition is totally okay. They
/// all will be treated as a single attribute.
///
/// A __trait has to be [object safe][2]__, because schema resolvers will need to return a
/// [trait object][3] to specify a [GraphQL union][1] behind it. The [trait object][3] has to be
/// [`Send`] and [`Sync`].
///
/// ```
/// use juniper::{graphql_union, GraphQLObject};
///
/// #[derive(GraphQLObject)]
/// struct Human {
/// id: String,
/// home_planet: String,
/// }
///
/// #[derive(GraphQLObject)]
/// struct Droid {
/// id: String,
/// primary_function: String,
/// }
///
/// #[graphql_union]
/// trait Character {
/// // NOTICE: The method signature must contain `&self` and return `Option<&VariantType>`.
/// fn as_human(&self) -> Option<&Human> { None }
/// fn as_droid(&self) -> Option<&Droid> { None }
/// }
///
/// impl Character for Human {
/// fn as_human(&self) -> Option<&Human> { Some(&self) }
/// }
///
/// impl Character for Droid {
/// fn as_droid(&self) -> Option<&Droid> { Some(&self) }
/// }
/// ```
///
/// # Custom name and description
///
/// The name of [GraphQL union][1] may be overriden with a `name` attribute's argument. By default,
/// a type name is used.
///
/// The description of [GraphQL union][1] may be specified either with a `description`/`desc`
/// attribute's argument, or with a regular Rust doc comment.
///
/// ```
/// # use juniper::{graphql_union, GraphQLObject};
/// #
/// # #[derive(GraphQLObject)]
/// # struct Human {
/// # id: String,
/// # home_planet: String,
/// # }
/// #
/// # #[derive(GraphQLObject)]
/// # struct Droid {
/// # id: String,
/// # primary_function: String,
/// # }
/// #
/// #[graphql_union]
/// #[graphql(name = "Character", desc = "Possible episode characters.")]
/// trait Chrctr {
/// fn as_human(&self) -> Option<&Human> { None }
/// fn as_droid(&self) -> Option<&Droid> { None }
/// }
///
/// // NOTICE: Rust docs are used as GraphQL description.
/// /// Possible episode characters.
/// trait CharacterWithDocs {
/// fn as_human(&self) -> Option<&Human> { None }
/// fn as_droid(&self) -> Option<&Droid> { None }
/// }
///
/// // NOTICE: `description` argument takes precedence over Rust docs.
/// /// Not a GraphQL description anymore.
/// #[graphql_union]
/// #[graphql(description = "Possible episode characters.")]
/// trait CharacterWithDescription {
/// fn as_human(&self) -> Option<&Human> { None }
/// fn as_droid(&self) -> Option<&Droid> { None }
/// }
/// #
/// # impl Chrctr for Human {}
/// # impl Chrctr for Droid {}
/// # impl CharacterWithDocs for Human {}
/// # impl CharacterWithDocs for Droid {}
/// # impl CharacterWithDescription for Human {}
/// # impl CharacterWithDescription for Droid {}
/// ```
///
/// # Custom context
///
/// By default, the generated implementation tries to infer [`Context`] type from signatures of
/// trait methods, and uses [unit type `()`][4] if signatures contains no [`Context`] arguments.
///
/// If [`Context`] type cannot be inferred or is inferred incorrectly, then specify it explicitly
/// with `context` attribute's argument.
///
/// ```
/// # use std::collections::HashMap;
/// # use juniper::{graphql_union, GraphQLObject};
/// #
/// #[derive(GraphQLObject)]
/// #[graphql(Context = Database)]
/// struct Human {
/// id: String,
/// home_planet: String,
/// }
///
/// #[derive(GraphQLObject)]
/// #[graphql(Context = Database)]
/// struct Droid {
/// id: String,
/// primary_function: String,
/// }
///
/// struct Database {
/// humans: HashMap<String, Human>,
/// droids: HashMap<String, Droid>,
/// }
/// impl juniper::Context for Database {}
///
/// #[graphql_union]
/// #[graphql(context = Database)]
/// trait Character {
/// fn as_human<'db>(&self, ctx: &'db Database) -> Option<&'db Human> { None }
/// fn as_droid<'db>(&self, ctx: &'db Database) -> Option<&'db Droid> { None }
/// }
///
/// impl Character for Human {
/// fn as_human<'db>(&self, ctx: &'db Database) -> Option<&'db Human> {
/// ctx.humans.get(&self.id)
/// }
/// }
///
/// impl Character for Droid {
/// fn as_droid<'db>(&self, ctx: &'db Database) -> Option<&'db Droid> {
/// ctx.droids.get(&self.id)
/// }
/// }
/// ```
///
/// # Custom `ScalarValue`
///
/// By default, `#[graphql_union]` macro generates code, which is generic over
/// a [`ScalarValue`] type. This may introduce a problem when at least one of
/// [GraphQL union][1] variants is restricted to a concrete [`ScalarValue`] type
/// in its implementation. To resolve such problem, a concrete [`ScalarValue`]
/// type should be specified with a `scalar` attribute's argument.
///
/// ```
/// # use juniper::{graphql_union, DefaultScalarValue, GraphQLObject};
/// #
/// #[derive(GraphQLObject)]
/// #[graphql(scalar = DefaultScalarValue)]
/// struct Human {
/// id: String,
/// home_planet: String,
/// }
///
/// #[derive(GraphQLObject)]
/// struct Droid {
/// id: String,
/// primary_function: String,
/// }
///
/// // NOTICE: Removing `scalar` argument will fail compilation.
/// #[graphql_union]
/// #[graphql(scalar = DefaultScalarValue)]
/// trait Character {
/// fn as_human(&self) -> Option<&Human> { None }
/// fn as_droid(&self) -> Option<&Droid> { None }
/// }
/// #
/// # impl Character for Human {}
/// # impl Character for Droid {}
/// ```
///
/// # Ignoring trait methods
///
/// To omit some trait method to be assumed as a [GraphQL union][1] variant and
/// ignore it, use an `ignore` attribute's argument directly on that method.
///
/// ```
/// # use juniper::{graphql_union, GraphQLObject};
/// #
/// # #[derive(GraphQLObject)]
/// # struct Human {
/// # id: String,
/// # home_planet: String,
/// # }
/// #
/// # #[derive(GraphQLObject)]
/// # struct Droid {
/// # id: String,
/// # primary_function: String,
/// # }
/// #
/// #[graphql_union]
/// trait Character {
/// fn as_human(&self) -> Option<&Human> { None }
/// fn as_droid(&self) -> Option<&Droid> { None }
/// #[graphql(ignore)]
/// fn id(&self) -> &str;
/// }
/// #
/// # impl Character for Human {
/// # fn id(&self) -> &str { self.id.as_str() }
/// # }
/// #
/// # impl Character for Droid {
/// # fn id(&self) -> &str { self.id.as_str() }
/// # }
/// ```
///
/// # External resolver functions
///
/// It's not mandatory to use trait methods as [GraphQL union][1] variant resolvers, and instead
/// custom functions may be specified with an `on` attribute's argument.
///
/// ```
/// # use std::collections::HashMap;
/// # use juniper::{graphql_union, GraphQLObject};
/// #
/// #[derive(GraphQLObject)]
/// #[graphql(Context = Database)]
/// struct Human {
/// id: String,
/// home_planet: String,
/// }
///
/// #[derive(GraphQLObject)]
/// #[graphql(Context = Database)]
/// struct Droid {
/// id: String,
/// primary_function: String,
/// }
///
/// struct Database {
/// humans: HashMap<String, Human>,
/// droids: HashMap<String, Droid>,
/// }
/// impl juniper::Context for Database {}
///
/// #[graphql_union]
/// #[graphql(context = Database)]
/// #[graphql(
/// on Human = DynCharacter::get_human,
/// on Droid = get_droid,
/// )]
/// trait Character {
/// #[graphql(ignore)]
/// fn id(&self) -> &str;
/// }
///
/// impl Character for Human {
/// fn id(&self) -> &str { self.id.as_str() }
/// }
///
/// impl Character for Droid {
/// fn id(&self) -> &str { self.id.as_str() }
/// }
///
/// // NOTICE: The trait object is always `Send` and `Sync`.
/// type DynCharacter<'a> = dyn Character + Send + Sync + 'a;
///
/// impl<'a> DynCharacter<'a> {
/// fn get_human<'db>(&self, ctx: &'db Database) -> Option<&'db Human> {
/// ctx.humans.get(self.id())
/// }
/// }
///
/// // NOTICE: Custom resolver function doesn't have to be a method of a type.
/// // It's only a matter of the function signature to match the requirements.
/// fn get_droid<'db>(ch: &DynCharacter<'_>, ctx: &'db Database) -> Option<&'db Droid> {
/// ctx.droids.get(ch.id())
/// }
/// ```
///
/// [`Context`]: juniper::Context
/// [`ScalarValue`]: juniper::ScalarValue
/// [1]: https://spec.graphql.org/October2021#sec-Unions
/// [2]: https://doc.rust-lang.org/stable/reference/items/traits.html#object-safety
/// [3]: https://doc.rust-lang.org/stable/reference/types/trait-object.html
/// [4]: https://doc.rust-lang.org/stable/std/primitive.unit.html
#[proc_macro_attribute]
pub fn graphql_union(attr: TokenStream, body: TokenStream) -> TokenStream {
diagnostic::entry_point_with_preserved_body(body.clone(), || {
self::graphql_union::attr::expand(attr.into(), body.into())
.unwrap_or_abort()
.into()
})
}