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
|
//! `#[deftly(...)]` meta attributes
//!
//! # Used meta checking
//!
//! Most of this file is concerned with generating
//! accurate and useful messages
//! when a driver is decorated with `#[deftly(...)]` attributes
//! which are not used by any template.
//!
//! We distinguish "used" metas from "recognised" ones.
//!
//! "Used" ones are those actually tested, and used,
//! during the dynamic expansion of the template.
//! They are recorded in the [`PreprocessedMetas`],
//! which contains a `Cell` for each supplied node.
//!
//! "Recognised" ones are those which appear anywhere in the template.
//! These are represented in a data structure [``Recognised`].
//! This is calculated by scanning the template,
//! using the `FindRecogMetas` trait.
//!
//! Both of these sets are threaded through
//! the ACCUM data in successive template expansions;
//! in the final call (`EngineFinalInput`),
//! they are combined together,
//! and the driver's metas are checked against them.
use super::framework::*;
use indexmap::IndexMap;
use Usage as U;
//---------- common definitions ----------
/// Indicates one of `fmeta`, `vmeta` or `tmeta`
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
#[derive(AsRefStr, EnumString, EnumIter)]
#[rustfmt::skip]
pub enum Scope {
// NB these keywords are duplicated in SubstDetails
#[strum(serialize = "tmeta")] T,
#[strum(serialize = "vmeta")] V,
#[strum(serialize = "fmeta")] F,
}
/// Scope of a *supplied* meta (`#[deftly(...)]`) attribute
///
/// Also encodes, for metas at the toplevel,
/// whether it's a struct or an enum.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] //
#[derive(strum::Display, EnumIter)]
#[strum(serialize_all = "snake_case")]
pub enum SuppliedScope {
Struct,
Enum,
Variant,
Field,
}
impl SuppliedScope {
fn recog_search(self) -> impl Iterator<Item = Scope> {
use Scope as S;
use SuppliedScope as SS;
match self {
SS::Struct => &[S::T, S::V] as &[_],
SS::Enum => &[S::T],
SS::Variant => &[S::V],
SS::Field => &[S::F],
}
.iter()
.copied()
}
}
/// `(foo(bar))` in eg `fmeta(foo(bar))`
///
/// includes the parens
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Label {
// Nonempty list, each with nonempty segments.
// Outermost first.
pub lpaths: Vec<syn::Path>,
}
/// Meta designator eg `fmeta(foo(bar))`
// Field order must be the same as BorrowedDesig
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Desig {
pub scope: Scope,
pub label: Label,
}
#[derive(Hash)]
// Field order must be the same as meta::Desig
struct BorrowedDesig<'p> {
pub scope: Scope,
pub lpaths: &'p [&'p syn::Path],
}
//---------- substitutions in a template ----------
#[derive(Debug)]
pub struct SubstMeta<O: SubstParseContext> {
pub desig: Desig,
pub as_: Option<SubstAs<O>>,
pub default: Option<(Argument<O>, O::NotInBool, beta::Enabled)>,
}
#[derive(Debug, Clone, AsRefStr, Display)]
#[allow(non_camel_case_types)] // clearer to use the exact ident
pub enum SubstAs<O: SubstParseContext> {
expr(O::NotInBool, AllowTokens<O>, SubstAsSupported<ValueExpr>),
ident(O::NotInBool),
items(O::NotInBool, AllowTokens<O>, SubstAsSupported<ValueItems>),
path(O::NotInBool),
str(O::NotInBool),
token_stream(O::NotInBool, AllowTokens<O>),
ty(O::NotInBool),
}
//---------- meta attrs in a driver ----------
/// A part like `(foo,bar(baz),zonk="value")`
#[derive(Debug)]
pub struct PreprocessedValueList {
pub content: Punctuated<PreprocessedTree, token::Comma>,
}
/// `#[deftly(...)]` helper attributes
pub type PreprocessedMetas = Vec<PreprocessedValueList>;
/// An `#[deftly()]` attribute, or a sub-tree within one
///
/// Has interior mutability, for tracking whether the value is used.
/// (So should ideally not be Clone, to help avoid aliasing bugs.)
#[derive(Debug)]
pub struct PreprocessedTree {
pub path: syn::Path,
pub value: PreprocessedValue,
pub used: Cell<Usage>,
}
/// Content of a meta attribute
///
/// Examples in doc comments are for
/// `PreprocessedMeta.path` of `foo`,
/// ie the examples are for `#[deftly(foo ..)]`.
#[derive(Debug)]
pub enum PreprocessedValue {
/// `#[deftly(foo)]`
Unit,
/// `#[deftly(foo = "lit")]`
Value { value: syn::Lit },
/// `#[deftly(foo(...))]`
List(PreprocessedValueList),
}
//---------- search and match results ----------
/// Node in tree structure found in driver `#[deftly(some(thing))]`
#[derive(Debug)]
pub struct FoundNode<'l> {
kind: FoundNodeKind<'l>,
path_span: Span,
ptree: &'l PreprocessedTree,
}
/// Node in tree structure found in driver `#[deftly(some(thing))]`
#[derive(Debug)]
pub enum FoundNodeKind<'l> {
Unit,
Lit(&'l syn::Lit),
}
/// Information about a nearby meta node we found
///
/// "Nearby" means that the node we found is a prefix (in tree descent)
/// of the one we were looking for, or vice versa.
#[derive(Debug)]
pub struct FoundNearbyNode<'l> {
pub kind: FoundNearbyNodeKind,
/// Span of the identifier in the actual `#[deftly]` driver attribute
pub path_span: Span,
pub ptree: &'l PreprocessedTree,
}
/// How the nearby node relates to the one we were looking for
#[derive(Debug)]
pub enum FoundNearbyNodeKind {
/// We were looking to go deeper, but found a unit in `#[deftly]`
Unit,
/// We were looking to go deeper, but found a `name = value` in `#[deftly]`
Lit,
/// We were looking for a leaf, but we found nested list in `#[deftly]`
List,
}
pub use FoundNearbyNodeKind as FNNK;
pub use FoundNodeKind as FNK;
//---------- meta attr enumeration and checking ----------
#[derive(Default, Debug, Clone, Copy, Eq, PartialEq)]
pub struct UsageInfo<M> {
unit: Option<M>,
value: Option<M>,
}
pub type Usage = UsageInfo<IsUsed>;
impl Usage {
pub const BOOL_ONLY: Usage = UsageInfo {
unit: Some(IsUsed),
value: None,
};
pub const VALUE_ONLY: Usage = UsageInfo {
unit: None,
value: Some(IsUsed),
};
pub const VALUE: Usage = UsageInfo {
unit: Some(IsUsed),
value: Some(IsUsed),
};
pub const NONE: Usage = UsageInfo {
unit: None,
value: None,
};
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, strum::EnumIter)]
pub enum UsageMode {
Unit,
Value,
}
impl<M> UsageInfo<M> {
pub fn get(&self, mode: UsageMode) -> Option<&M> {
match mode {
UsageMode::Unit => self.unit.as_ref(),
UsageMode::Value => self.value.as_ref(),
}
}
pub fn get_mut(&mut self, mode: UsageMode) -> &mut Option<M> {
match mode {
UsageMode::Unit => &mut self.unit,
UsageMode::Value => &mut self.value,
}
}
}
impl std::ops::BitOr for Usage {
type Output = Usage;
fn bitor(self, other: Usage) -> Usage {
let mut out = self;
for mode in UsageMode::iter() {
let ent = out.get_mut(mode);
*ent = cmp::max(*ent, other.get(mode).copied());
}
out
}
}
#[derive(Default, Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
pub struct IsUsed;
/// One lot of used metas in accumulation - argument to a `_meta_used` accum
#[derive(Debug)]
pub struct UsedGroup {
pub content: TokenStream,
}
/// Something representing possibly checking that meta attributes are used
#[derive(Debug, Clone)]
pub enum CheckUsed<T> {
/// Yes, check them, by/with/from/to `T`
Check(T),
/// No, don't check them.
Unchecked,
}
/// Information for meta checking, found in accumulation
#[derive(Debug, Default)]
pub struct Accum {
pub recog: Recognised,
pub used: Vec<UsedGroup>,
}
#[derive(Default, Debug, Clone)]
pub struct Recognised {
map: IndexMap<Desig, Usage>,
}
pub trait FindRecogMetas {
/// Search for `fmeta(..)` etc. expansions
///
/// Add to `acc` any that are
/// (recusively) within `self`, syntactically,
fn find_recog_metas(&self, acc: &mut Recognised);
}
//==================== implementations) ====================
//---------- template parsing ----------
impl<O: SubstParseContext> SubstMeta<O> {
fn span_whole(&self, scope_span: Span) -> Span {
spans_join(chain!(
[scope_span], //
self.desig.label.spans(),
))
.unwrap()
}
}
impl Label {
/// Nonempty
pub fn spans(&self) -> impl Iterator<Item = Span> + '_ {
self.lpaths.iter().map(|path| path.span())
}
}
impl<O: SubstParseContext> SubstAs<O> {
fn parse(input: ParseStream, nb: O::NotInBool) -> syn::Result<Self> {
let kw: IdentAny = input.parse()?;
let from_sma = |sma: SubstAs<_>| Ok(sma);
// See keyword_general! in utils.rs
macro_rules! keyword { { $($args:tt)* } => {
keyword_general! { kw from_sma SubstAs; $($args)* }
} }
let allow_tokens = || O::allow_tokens(&kw);
fn supported<P>(kw: &IdentAny) -> syn::Result<SubstAsSupported<P>>
where
P: SubstAsSupportStatus,
{
SubstAsSupportStatus::new(&kw)
}
keyword! { expr(nb, allow_tokens()?, supported(&kw)?) }
keyword! { ident(nb) }
keyword! { items(nb, allow_tokens()?, supported(&kw)?) }
keyword! { path(nb) }
keyword! { str(nb) }
keyword! { token_stream(nb, allow_tokens()?) }
keyword! { ty(nb) }
Err(kw.error("unknown derive-deftly 'as' syntax type keyword"))
}
}
impl<O: SubstParseContext> SubstMeta<O> {
pub fn parse(
input: ParseStream,
kw_span: Span,
scope: Scope,
) -> syn::Result<Self> {
if input.is_empty() {
O::missing_keyword_arguments(kw_span)?;
}
let label: Label = input.parse()?;
fn store<V>(
kw: Span,
already: &mut Option<(Span, V)>,
call: impl FnOnce() -> syn::Result<V>,
) -> syn::Result<()> {
if let Some((already, _)) = already {
return Err([(*already, "first"), (kw, "second")]
.error("`${Xmeta ..}` option repeated"));
}
let v = call()?;
*already = Some((kw, v));
Ok(())
}
let mut as_ = None::<(Span, SubstAs<O>)>;
let mut default = None;
while !O::IS_BOOL && !input.is_empty() {
let keyword = Ident::parse_any(input)?;
let kw_span = keyword.span();
let nb = O::not_in_bool(&kw_span).expect("checked already");
let ue = || beta::Enabled::new_for_syntax(kw_span);
if keyword == "as" {
store(kw_span, &mut as_, || SubstAs::parse(input, nb))?;
} else if keyword == "default" {
store(kw_span, &mut default, || {
Ok((input.parse()?, nb, ue()?))
})?;
} else {
return Err(keyword.error("unknown option in `${Xmeta }`"));
}
if input.is_empty() {
break;
}
let _: Token![,] = input.parse()?;
}
macro_rules! ret { { $( $f:ident )* } => {
SubstMeta {
desig: Desig { label, scope },
$( $f: $f.map(|(_span, v)| v), )*
}
} }
Ok(ret! {
as_
default
})
}
}
//---------- driver parsing ----------
impl PreprocessedValueList {
fn parse_outer(input: ParseStream) -> syn::Result<Self> {
let meta;
let _paren = parenthesized!(meta in input);
Self::parse_inner(&meta)
}
}
impl PreprocessedValueList {
pub fn parse_inner(input: ParseStream) -> syn::Result<Self> {
let content = Punctuated::parse_terminated(input)?;
Ok(PreprocessedValueList { content })
}
}
impl Parse for PreprocessedTree {
fn parse(input: ParseStream) -> syn::Result<Self> {
use PreprocessedValue as PV;
let path = input.call(syn::Path::parse_mod_style)?;
let la = input.lookahead1();
let value = if la.peek(Token![=]) {
let _: Token![=] = input.parse()?;
let value = input.parse()?;
PV::Value { value }
} else if la.peek(token::Paren) {
let list = input.call(PreprocessedValueList::parse_outer)?;
PV::List(list)
} else if la.peek(Token![,]) || input.is_empty() {
PV::Unit
} else {
return Err(la.error());
};
let used = Usage::default().into(); // will be filled in later
Ok(PreprocessedTree { path, value, used })
}
}
impl Parse for Label {
fn parse(outer: ParseStream) -> syn::Result<Self> {
fn recurse(
lpaths: &mut Vec<syn::Path>,
outer: ParseStream,
) -> syn::Result<()> {
let input;
let paren = parenthesized!(input in outer);
let path = input.call(syn::Path::parse_mod_style)?;
if path.segments.is_empty() {
return Err(paren
.span
.error("`deftly` attribute must have nonempty path"));
}
lpaths.push(path);
if !input.is_empty() {
recurse(lpaths, &input)?;
}
Ok(())
}
let mut lpaths = vec![];
recurse(&mut lpaths, outer)?;
Ok(Label { lpaths })
}
}
//---------- searching and matching ----------
impl Label {
/// Caller must note meta attrs that end up being used!
pub fn search<'a, F, G, E>(
&self,
pmetas: &'a [PreprocessedValueList],
f: &mut F,
g: &mut G,
) -> Result<(), E>
where
F: FnMut(FoundNode<'a>) -> Result<(), E>,
G: FnMut(FoundNearbyNode<'a>) -> Result<(), E>,
{
for m in pmetas {
for l in &m.content {
Self::search_1(&self.lpaths, l, &mut *f, &mut *g)?;
}
}
Ok(())
}
fn search_1<'a, E, F, G>(
// Nonempty
lpaths: &[syn::Path],
ptree: &'a PreprocessedTree,
f: &mut F,
g: &mut G,
) -> Result<(), E>
where
F: FnMut(FoundNode<'a>) -> Result<(), E>,
G: FnMut(FoundNearbyNode<'a>) -> Result<(), E>,
{
use PreprocessedValue as PV;
if ptree.path != lpaths[0] {
return Ok(());
}
let path_span = ptree.path.span();
let mut nearby = |kind| {
g(FoundNearbyNode {
kind,
path_span,
ptree,
})
};
let deeper = if lpaths.len() <= 1 {
None
} else {
Some(&lpaths[1..])
};
match (deeper, &ptree.value) {
(None, PV::Unit) => f(FoundNode {
path_span,
kind: FNK::Unit,
ptree,
})?,
(None, PV::List(_)) => nearby(FNNK::List)?,
(None, PV::Value { value, .. }) => f(FoundNode {
path_span,
kind: FNK::Lit(value),
ptree,
})?,
(Some(_), PV::Value { .. }) => nearby(FNNK::Lit)?,
(Some(_), PV::Unit) => nearby(FNNK::Unit)?,
(Some(d), PV::List(l)) => {
for m in l.content.iter() {
Self::search_1(d, m, &mut *f, &mut *g)?;
}
}
}
Ok(())
}
}
impl Label {
pub fn search_eval_bool(
&self,
pmetas: &PreprocessedMetas,
) -> Result<(), Found> {
let found = |ptree: &PreprocessedTree| {
ptree.update_used(Usage::BOOL_ONLY);
Err(Found)
};
self.search(
pmetas,
&mut |av| /* got it! */ found(av.ptree),
&mut |nearby| match nearby.kind {
FNNK::List => found(nearby.ptree),
FNNK::Unit => Ok(()),
FNNK::Lit => Ok(()),
},
)
}
}
//---------- scope and designator handling ----------
impl<O> SubstMeta<O>
where
O: SubstParseContext,
{
pub fn repeat_over(&self) -> Option<RepeatOver> {
match self.desig.scope {
Scope::T => None,
Scope::V => Some(RO::Variants),
Scope::F => Some(RO::Fields),
}
}
}
impl<O> SubstMeta<O>
where
O: SubstParseContext,
{
pub fn pmetas<'c>(
&self,
ctx: &'c Context<'c>,
kw_span: Span,
) -> syn::Result<&'c PreprocessedMetas> {
Ok(match self.desig.scope {
Scope::T => &ctx.pmetas,
Scope::V => &ctx.variant(&kw_span)?.pmetas,
Scope::F => &ctx.field(&kw_span)?.pfield.pmetas,
})
}
}
impl ToTokens for Label {
fn to_tokens(&self, out: &mut TokenStream) {
let mut lpaths = self.lpaths.iter().rev();
let mut current =
lpaths.next().expect("empty path!").to_token_stream();
let r = loop {
let group = group_new_with_span(
Delimiter::Parenthesis,
current.span(),
current,
);
let wrap = if let Some(y) = lpaths.next() {
y
} else {
break group;
};
current = quote! { #wrap #group };
};
r.to_tokens(out);
}
}
impl Desig {
fn to_tokens(&self, scope_span: Span, out: &mut TokenStream) {
let scope: &str = self.scope.as_ref();
Ident::new(scope, scope_span).to_tokens(out);
self.label.to_tokens(out);
}
}
impl Parse for Desig {
fn parse(input: ParseStream) -> syn::Result<Self> {
let scope: syn::Ident = input.parse()?;
let scope = scope
.to_string()
.parse()
.map_err(|_| scope.error("invalid meta keyword/level"))?;
let label = input.parse()?;
Ok(Self { scope, label })
}
}
impl indexmap::Equivalent<Desig> for BorrowedDesig<'_> {
fn equivalent(&self, desig: &Desig) -> bool {
let BorrowedDesig { scope, lpaths } = self;
*scope == desig.scope
&& itertools::equal(lpaths.iter().copied(), &desig.label.lpaths)
}
}
/// `Display`s as a `#[deftly(...)]` as the user might write it
struct DisplayAsIfSpecified<'r> {
lpaths: &'r [&'r syn::Path],
/// Included after the innermost lpath, inside the parens
inside_after: &'r str,
}
impl Display for DisplayAsIfSpecified<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "#[deftly")?;
for p in self.lpaths {
write!(f, "({}", p.to_token_stream())?;
}
write!(f, "{}", self.inside_after)?;
for _ in self.lpaths {
write!(f, ")")?;
}
Ok(())
}
}
// Tests that our `BorrowedDesig` `equivalent` impl is justified.
#[test]
fn check_borrowed_desig() {
use super::*;
use indexmap::Equivalent;
use itertools::iproduct;
use std::hash::{Hash, Hasher};
#[derive(PartialEq, Eq, Debug, Default)]
struct TrackingHasher(Vec<Vec<u8>>);
impl Hasher for TrackingHasher {
fn write(&mut self, bytes: &[u8]) {
self.0.push(bytes.to_owned());
}
fn finish(&self) -> u64 {
unreachable!()
}
}
impl TrackingHasher {
fn hash(t: impl Hash) -> Self {
let mut self_ = Self::default();
t.hash(&mut self_);
self_
}
}
type Case = (Scope, &'static [&'static str]);
const TEST_CASES: &[Case] = &[
(Scope::T, &["path"]),
(Scope::T, &["r#path"]),
(Scope::V, &["path", "some::path"]),
(Scope::V, &["r#struct", "with_generics::<()>"]),
(Scope::F, &[]), // illegal Desig, but test anyway
];
struct Desigs<'b> {
owned: Desig,
borrowed: BorrowedDesig<'b>,
}
impl Desigs<'_> {
fn with((scope, lpaths): &Case, f: impl FnOnce(Desigs<'_>)) {
let scope = *scope;
let lpaths = lpaths
.iter()
.map(|l| syn::parse_str(l).expect(l))
.collect_vec();
let owned = {
let label = Label {
lpaths: lpaths.clone(),
};
Desig { scope, label }
};
let lpaths_borrowed;
let borrowed = {
lpaths_borrowed = lpaths.iter().collect_vec();
BorrowedDesig {
scope,
lpaths: &*lpaths_borrowed,
}
};
f(Desigs { owned, borrowed })
}
}
// Test that for each entry in TEST_CASES, when parsed into Paths, etc.,
// BorrowedDesig is `equivalent` to, and hashes the same as, Desig.
for case in TEST_CASES {
Desigs::with(case, |d| {
assert!(d.borrowed.equivalent(&d.owned));
assert_eq!(
TrackingHasher::hash(&d.owned),
TrackingHasher::hash(&d.borrowed),
);
});
}
// Compare every TEST_CASES entry with every other entry.
// See if the owned forms are equal (according to `PartialEq`).
// Insist that the Borrowed vs owned `equivalent` relation agrees,
// in both directions.
// And, if they are equal, insist that the hashes all agree.
for (case0, case1) in iproduct!(TEST_CASES, TEST_CASES) {
Desigs::with(case0, |d0| {
Desigs::with(case1, |d1| {
let equal = d0.owned == d1.owned;
assert_eq!(equal, d0.borrowed.equivalent(&d1.owned));
assert_eq!(equal, d1.borrowed.equivalent(&d0.owned));
if equal {
let hash = TrackingHasher::hash(&d0.owned);
assert_eq!(hash, TrackingHasher::hash(&d1.owned));
assert_eq!(hash, TrackingHasher::hash(&d0.borrowed));
assert_eq!(hash, TrackingHasher::hash(&d1.borrowed));
}
});
});
}
}
//---------- conditional support for `Xmeta as items` ----------
#[cfg(feature = "meta-as-expr")]
pub type ValueExpr = syn::Expr;
#[cfg(not(feature = "meta-as-expr"))]
pub type ValueExpr = MetaUnsupported;
#[cfg(feature = "meta-as-items")]
pub type ValueItems = Concatenated<syn::Item>;
#[cfg(not(feature = "meta-as-items"))]
pub type ValueItems = MetaUnsupported;
/// newtype to avoid coherence - it doesn't impl `Parse + ToTokens`
#[derive(Debug, Copy, Clone)]
#[allow(dead_code)] // rust-lang/rust/issues/145936
pub struct MetaUnsupported(Void);
#[derive(Debug, Copy, Clone)]
pub struct SubstAsSupported<P: SubstAsSupportStatus>(P::Marker);
/// Implemented for syn types supported in this build, and `MetaUnsupported`
pub trait SubstAsSupportStatus: Sized {
type Marker;
type Parsed: Parse + ToTokens;
fn new(kw: &IdentAny) -> syn::Result<SubstAsSupported<Self>>;
}
impl<P: SubstAsSupportStatus> SubstAsSupported<P> {
fn infer_type(&self, _parsed: &P::Parsed) {}
}
impl<T: Parse + ToTokens> SubstAsSupportStatus for T {
type Marker = ();
type Parsed = T;
fn new(_kw: &IdentAny) -> syn::Result<SubstAsSupported<Self>> {
Ok(SubstAsSupported(()))
}
}
impl SubstAsSupportStatus for MetaUnsupported {
type Marker = MetaUnsupported;
type Parsed = TokenStream;
fn new(kw: &IdentAny) -> syn::Result<SubstAsSupported<Self>> {
Err(kw.error(format_args!(
// We're a bit fast and loose here: if kw contained `_`,
// or there were aliases, this message would be a bit wrong.
"${{Xmeta as {}}} used but cargo feature meta-as-{} disabled",
**kw, **kw,
)))
}
}
impl ToTokens for MetaUnsupported {
fn to_tokens(&self, _out: &mut TokenStream) {
void::unreachable(self.0)
}
}
//---------- template expansion ----------
impl<O> SubstMeta<O>
where
O: ExpansionOutput,
TemplateElement<O>: Expand<O>,
{
pub fn expand(
&self,
ctx: &Context,
kw_span: Span,
out: &mut O,
pmetas: &PreprocessedMetas,
) -> syn::Result<()> {
let SubstMeta {
desig,
as_,
default,
} = self;
let mut found = None::<FoundNode>;
let mut hint = None::<FoundNearbyNode>;
let span_whole = self.span_whole(kw_span);
let self_loc = || (span_whole, "expansion");
let error_loc = || [ctx.error_loc(), self_loc()];
desig.label.search(
pmetas,
&mut |av: FoundNode| {
if let Some(first) = &found {
return Err([(first.path_span, "first occurrence"),
(av.path_span, "second occurrence"),
self_loc()].error(
"tried to expand just attribute value, but it was specified multiple times"
));
}
found = Some(av);
Ok(())
},
&mut |nearby| {
hint.get_or_insert(nearby);
Ok(())
},
)?;
if let Some((def, ..)) = default {
if match found {
None => true,
Some(FoundNode {
kind: FNK::Unit,
ptree,
..
}) => {
// Specified as unit, but we have a default.
// So ignore the unit for these purposes.
ptree.update_used(Usage::VALUE_ONLY);
true
}
_ => false,
} {
return Ok(def.expand(ctx.as_general(), out));
}
}
let found = found.ok_or_else(|| {
if let Some(hint) = hint {
let hint_msg = match hint.kind {
FNNK::Unit =>
"expected a list with sub-attributes, found a unit",
FNNK::Lit =>
"expected a list with sub-attributes, found a simple value",
FNNK::List =>
"expected a leaf node, found a list with sub-attributes",
};
let mut err = hint.path_span.error(hint_msg);
err.combine(error_loc().error(
"attribute value expanded, but no suitable value in data structure definition"
));
err
} else {
error_loc().error(
"attribute value expanded, but no value in data structure definition"
)
}
})?;
found.ptree.update_used(Usage::VALUE);
found.expand(span_whole, as_, out)?;
Ok(())
}
}
fn metavalue_spans(tspan: Span, vspan: Span) -> [ErrorLoc<'static>; 2] {
[(vspan, "attribute value"), (tspan, "template")]
}
/// Obtain the `LiStr` from a meta node value (ie, a `Lit`)
///
/// This is the thing we actually use.
/// Non-string-literal values are not allowed.
fn metavalue_litstr<'l>(
lit: &'l syn::Lit,
tspan: Span,
msg: fmt::Arguments<'_>,
) -> syn::Result<&'l syn::LitStr> {
match lit {
syn::Lit::Str(s) => Ok(s),
// having checked derive_builder, it doesn't handle
// Lit::Verbatim so I guess we don't need to either.
_ => Err(metavalue_spans(tspan, lit.span()).error(msg)),
}
}
/// Convert a literal found in a meta item into `T`
///
/// `into_what` is used only for error reporting
pub fn metavalue_lit_as<T>(
lit: &syn::Lit,
tspan: Span,
into_what: &dyn Display,
) -> syn::Result<T>
where
T: Parse + ToTokens,
{
let s = metavalue_litstr(
lit,
tspan,
format_args!(
"expected string literal, for conversion to {}",
into_what,
),
)?;
let t: TokenStream = s.parse().map_err(|e| {
// Empirically, parsing a LitStr in actual proc macro context, with
// proc_macro2, into tokens, can generate a lexical error with a
// "fallback" Span. Then, attempting to render the results,
// including the eventual compiler_error! invocation, back to
// a compiler proc_ma cor::TokenStream can panic with
// "compiler/fallback mismatch".
//
// https://github.com/dtolnay/syn/issues/1504
//
// Attempt to detect this situation.
match (|| {
let _: String = (&e).into_iter().next()?.span().source_text()?;
Some(())
})() {
Some(()) => e,
None => lit.span().error(e.to_string()),
}
})?;
let thing: T = syn::parse2(t)?;
Ok(thing)
}
impl<'l> FoundNode<'l> {
fn expand<O>(
&self,
tspan: Span,
as_: &Option<SubstAs<O>>,
out: &mut O,
) -> syn::Result<()>
where
O: ExpansionOutput,
{
let spans = |vspan| metavalue_spans(tspan, vspan);
let lit = match self.kind {
FNK::Unit => return Err(spans(self.path_span).error(
"tried to expand attribute which is just a unit, not a literal"
)),
FNK::Lit(lit) => lit,
};
use SubstAs as SA;
let default_buf;
let as_ = match as_ {
Some(as_) => as_,
None => {
default_buf = O::default_subst_meta_as(tspan)?;
&default_buf
}
};
match as_ {
as_ @ SA::expr(.., at, supported) => {
let expr = metavalue_lit_as(lit, tspan, as_)?;
supported.infer_type(&expr);
let span = expr.span();
out.append_tokens(at, Grouping::Parens.surround(span, expr))?;
}
as_ @ SA::ident(..) => {
let ident: IdentAny = metavalue_lit_as(lit, tspan, as_)?;
out.append_identfrag_toks(&*ident)?;
}
SA::items(_, np, supported) => {
let items = metavalue_lit_as(lit, tspan, &"items")?;
supported.infer_type(&items);
out.append_tokens(np, items)?;
}
as_ @ SA::path(..) => out.append_syn_type(
tspan,
syn::Type::Path(metavalue_lit_as(lit, tspan, as_)?),
Grouping::Invisible,
),
SA::str(..) => {
let s = metavalue_litstr(
lit,
tspan,
format_args!("expected string literal, for meta value",),
)?;
out.append_syn_litstr(s);
}
as_ @ SA::ty(..) => out.append_syn_type(
tspan,
metavalue_lit_as(lit, tspan, as_)?,
Grouping::Invisible,
),
SA::token_stream(_, np) => {
let tokens: TokenStream =
metavalue_lit_as(lit, tspan, &"tokens")?;
out.append_tokens(np, tokens)?;
}
}
Ok(())
}
}
//==================== implementations - usage checking ====================
impl Parse for CheckUsed<UsedGroup> {
fn parse(input: ParseStream) -> syn::Result<Self> {
let la = input.lookahead1();
Ok(if la.peek(Token![*]) {
let _star: Token![*] = input.parse()?;
mCU::Unchecked
} else if la.peek(token::Bracket) {
let group: proc_macro2::Group = input.parse()?;
let content = group.stream();
mCU::Check(UsedGroup { content })
} else {
return Err(la.error());
})
}
}
impl Recognised {
/// Ensures that `self[k] >= v`
pub fn update(&mut self, k: Desig, v: Usage) {
let ent = self.map.entry(k).or_insert(v);
*ent = *ent | v
}
}
impl ToTokens for Recognised {
fn to_tokens(&self, out: &mut TokenStream) {
for (desig, allow) in &self.map {
match *allow {
Usage::BOOL_ONLY => out.extend(quote! { ? }),
Usage::VALUE_ONLY => out.extend(quote! { + }),
Usage::VALUE => {}
Usage::NONE => panic!("should be impossible!"),
}
desig.to_tokens(Span::call_site(), out);
}
}
}
impl PreprocessedTree {
pub fn update_used(&self, ra: Usage) {
self.used.set(self.used.get() | ra);
}
}
//---------- decoding used metas ----------
impl PreprocessedValueList {
fn decode_update_used(&self, input: ParseStream) -> syn::Result<()> {
use PreprocessedValue as PV;
for ptree in &self.content {
if input.is_empty() {
return Ok(());
}
if !input.peek(Token![,]) {
let path = input.call(syn::Path::parse_mod_style)?;
if path != ptree.path {
return Err([
(path.span(), "found"),
(ptree.path.span(), "expected"),
].error(
"mismatch (desynchronised) incorporating previous expansions' used metas"
));
}
let used = if input.peek(Token![=]) {
let _: Token![=] = input.parse()?;
Some(Usage::VALUE)
} else if input.peek(Token![?]) {
let _: Token![?] = input.parse()?;
Some(Usage::BOOL_ONLY)
} else if input.peek(Token![+]) {
let _: Token![+] = input.parse()?;
Some(Usage::VALUE_ONLY)
} else {
None
};
if let Some(used) = used {
ptree.update_used(used);
}
if input.peek(token::Paren) {
let inner;
let paren = parenthesized!(inner in input);
let sub_list = match &ptree.value {
PV::Unit | PV::Value { .. } => return Err([
(paren.span.open(), "found"),
(ptree.path.span(), "defined"),
].error(
"mismatch (tree vs terminal) incorporating previous expansions' used metas"
)),
PV::List(l) => l,
};
sub_list.decode_update_used(&inner)?;
}
}
if input.is_empty() {
return Ok(());
}
let _: Token![,] = input.parse()?;
}
Ok(())
}
}
impl<'c> Context<'c> {
pub fn decode_update_metas_used(
&self,
input: /* group content */ ParseStream,
) -> syn::Result<()> {
#[derive(Default)]
struct Intended {
variant: Option<syn::Ident>,
field: Option<Either<syn::Ident, u32>>,
attr_i: usize,
}
let mut intended = Intended::default();
let mut visit =
|pmetas: &PreprocessedMetas,
current_variant: Option<&syn::Ident>,
current_field: Option<Either<&syn::Ident, &u32>>| {
loop {
let la = input.lookahead1();
if input.is_empty() {
// keep visiting until we exit all the loops
return Ok(());
} else if la.peek(Token![::]) {
let _: Token![::] = input.parse()?;
intended = Intended {
variant: Some(input.parse()?),
field: None,
attr_i: 0,
};
} else if la.peek(Token![.]) {
let _: Token![.] = input.parse()?;
intended.field = Some(match input.parse()? {
syn::Member::Named(n) => Either::Left(n),
syn::Member::Unnamed(i) => Either::Right(i.index),
});
intended.attr_i = 0;
} else if {
let intended_field_refish = intended
.field
.as_ref()
.map(|some: &Either<_, _>| some.as_ref());
!(current_variant == intended.variant.as_ref()
&& current_field == intended_field_refish)
} {
// visit subsequent things, hopefully one will match
return Ok(());
} else if la.peek(token::Paren) {
// we're in the right place and have found a #[deftly()]
let i = intended.attr_i;
intended.attr_i += 1;
let m = pmetas.get(i).ok_or_else(|| {
input.error("more used metas, out of range!")
})?;
let r;
let _ = parenthesized!(r in input);
m.decode_update_used(&r)?;
} else {
return Err(la.error());
}
}
};
visit(&self.pmetas, None, None)?;
WithinVariant::for_each(self, |ctx, wv| {
let current_variant = wv.variant.map(|wv| &wv.ident);
if !wv.is_struct_toplevel_as_variant() {
visit(&wv.pmetas, current_variant, None)?;
}
WithinField::for_each(ctx, |_ctx, wf| {
let current_field = if let Some(ref ident) = wf.field.ident {
Either::Left(ident)
} else {
Either::Right(&wf.index)
};
visit(&wf.pfield.pmetas, current_variant, Some(current_field))
})
})
// if we didn't consume all of the input, due to mismatches/
// misordering, then syn will give an error for us
}
}
//---------- encoding used metas ---------
impl PreprocessedTree {
/// Returns `(....)`
fn encode_useds(
list: &PreprocessedValueList,
) -> Option<proc_macro2::Group> {
let preamble = syn::parse::Nothing;
let sep = Token);
let mut ts = TokenStream::new();
let mut ot = TokenOutputTrimmer::new(&mut ts, &preamble, &sep);
for t in &list.content {
t.encode_used(&mut ot);
ot.push_sep();
}
if ts.is_empty() {
None
} else {
Some(proc_macro2::Group::new(Delimiter::Parenthesis, ts))
}
}
/// Writes `path?=(...)` (or, rather, the parts of it that are needed)
fn encode_used(&self, out: &mut TokenOutputTrimmer) {
use PreprocessedValue as PV;
struct OutputTrimmerWrapper<'or, 'o, 't, 'p> {
// None if we have written the path already
path: Option<&'p syn::Path>,
out: &'or mut TokenOutputTrimmer<'t, 'o>,
}
let mut out = OutputTrimmerWrapper {
path: Some(&self.path),
out,
};
impl OutputTrimmerWrapper<'_, '_, '_, '_> {
fn push_reified(&mut self, t: &dyn ToTokens) {
if let Some(path) = self.path.take() {
self.out.push_reified(path);
}
self.out.push_reified(t);
}
}
let tspan = Span::call_site();
match self.used.get() {
Usage::BOOL_ONLY => out.push_reified(&Token),
Usage::VALUE => out.push_reified(&Token),
Usage::VALUE_ONLY => out.push_reified(&Token),
Usage::NONE => {}
}
match &self.value {
PV::Unit | PV::Value { .. } => {}
PV::List(l) => {
if let Some(group) = PreprocessedTree::encode_useds(l) {
out.push_reified(&group);
}
}
}
}
}
impl<'c> Context<'c> {
/// Returns `[::Variant .field () ...]`
pub fn encode_metas_used(&self) -> proc_macro2::Group {
let parenthesize =
|ts| proc_macro2::Group::new(Delimiter::Parenthesis, ts);
let an_empty = parenthesize(TokenStream::new());
let mut ts = TokenStream::new();
struct Preamble<'p> {
variant: Option<&'p syn::Variant>,
field: Option<&'p WithinField<'p>>,
}
impl ToTokens for Preamble<'_> {
fn to_tokens(&self, out: &mut TokenStream) {
let span = Span::call_site();
if let Some(v) = self.variant {
Token.to_tokens(out);
v.ident.to_tokens(out);
}
if let Some(f) = self.field {
Token.to_tokens(out);
f.fname(span).to_tokens(out);
}
}
}
let mut last_variant: *const syn::Variant = ptr::null();
let mut last_field: *const syn::Field = ptr::null();
fn ptr_of_ref<'i, InDi>(r: Option<&'i InDi>) -> *const InDi {
r.map(|r| r as _).unwrap_or_else(ptr::null)
}
let mut encode = |pmetas: &PreprocessedMetas,
wv: Option<&WithinVariant>,
wf: Option<&WithinField>| {
let now_variant: *const syn::Variant =
ptr_of_ref(wv.map(|wv| wv.variant).flatten());
let now_field: *const syn::Field =
ptr_of_ref(wf.map(|wf| wf.field));
let preamble = Preamble {
variant: (!ptr::eq(last_variant, now_variant)).then(|| {
last_field = ptr::null();
let v = wv.expect("had WithinVariant, now not");
v.variant.expect("variant was syn::Variant, now not")
}),
field: (!ptr::eq(last_field, now_field)).then(|| {
wf.expect("had WithinField (Field), now not") //
}),
};
let mut ot =
TokenOutputTrimmer::new(&mut ts, &preamble, &an_empty);
for m in pmetas {
if let Some(group) = PreprocessedTree::encode_useds(m) {
ot.push_reified(group);
} else {
ot.push_sep();
}
}
if ot.did_preamble().is_some() {
last_variant = now_variant;
last_field = now_field;
}
Ok::<_, Void>(())
};
encode(&self.pmetas, None, None).void_unwrap();
WithinVariant::for_each(self, |ctx, wv| {
if !wv.is_struct_toplevel_as_variant() {
encode(&wv.pmetas, Some(wv), None)?;
}
WithinField::for_each(ctx, |_ctx, wf| {
encode(&wf.pfield.pmetas, Some(wv), Some(wf))
})
})
.void_unwrap();
proc_macro2::Group::new(Delimiter::Bracket, ts)
}
}
//---------- checking used metas ----------
struct UsedChecker<'c, 'e> {
current: Vec<&'c syn::Path>,
reported: &'e mut HashSet<Label>,
recog: &'c Recognised,
supplied_scope: SuppliedScope,
errors: &'e mut ErrorAccumulator,
}
impl PreprocessedTree {
fn check_used<'c>(&'c self, checker: &mut UsedChecker<'c, '_>) {
checker.current.push(&self.path);
let mut err = |err| {
let lpaths = checker.current.iter().copied().cloned().collect();
if checker.reported.insert(Label { lpaths }) {
checker.errors.push(err);
}
};
let mut need = |supplied_mode| {
let used = self.used.get();
match used.get(supplied_mode) {
Some(IsUsed) => {}
None => err(unrecognised_error(
checker.recog,
checker.supplied_scope,
supplied_mode,
self.path.span(),
used,
&checker.current,
)
.void_unwrap_err()),
}
};
match &self.value {
PreprocessedValue::Unit => need(UsageMode::Unit),
PreprocessedValue::Value { .. } => need(UsageMode::Value),
PreprocessedValue::List(l) => {
if l.content.is_empty() {
err(self.path.error(
"empty nested list in #[deftly], is not useable by any template"
));
}
for subtree in &l.content {
subtree.check_used(checker);
}
}
}
checker
.current
.pop()
.expect("pushed earlier, but can't pop?");
}
}
impl<'c> Context<'c> {
pub(crate) fn check_metas_used(
&self,
errors: &mut ErrorAccumulator,
recog: &Recognised,
) {
use SuppliedScope as SS;
let mut reported = HashSet::new();
let mut chk_pmetas = |supplied_scope, pmetas: &PreprocessedMetas| {
let mut checker = UsedChecker {
reported: &mut reported,
current: vec![],
recog,
errors,
supplied_scope,
};
for a in pmetas {
for l in &a.content {
l.check_used(&mut checker);
}
}
Ok::<_, Void>(())
};
chk_pmetas(
match &self.top.data {
syn::Data::Struct(_) | syn::Data::Union(_) => SS::Struct,
syn::Data::Enum(_) => SS::Enum,
},
&self.pmetas,
)
.void_unwrap();
WithinVariant::for_each(self, |ctx, wv| {
// If variant is None, this is the imaginary variant for
// the toplevel, and it has a copy of the ref to the metas,
// in which case we don't want to process it again.
if !wv.is_struct_toplevel_as_variant() {
chk_pmetas(SS::Variant, &wv.pmetas)?;
}
WithinField::for_each(ctx, |_ctx, wf| {
chk_pmetas(SS::Field, &wf.pfield.pmetas)
})
})
.void_unwrap();
}
}
fn unrecognised_error(
recog: &Recognised,
supplied_scope: SuppliedScope,
supplied_mode: UsageMode,
supplied_span: Span,
used: Usage,
lpaths: &[&syn::Path],
) -> Result<Void, syn::Error> /* return type allows (ab)use of ? */ {
// This could have been a method on UsedChecker, but that runs into
// borrowck trouble.
let try_case = |e: Option<_>| e.map(Err).unwrap_or(Ok(()));
let some_err = |m: &dyn Display| Some(supplied_span.error(m));
// Maybe this would have been recognised in other circumstances.
// If so, report that.
try_case((|| {
let recog_allow = supplied_scope
.recog_search()
.map(|scope| {
recog
.map
.get(&BorrowedDesig { scope, lpaths })
.copied()
.unwrap_or_default()
})
.reduce(std::ops::BitOr::bitor)
.unwrap_or_default();
// Have we supplied more than would ever be recognised?
let _: &IsUsed = recog_allow.get(supplied_mode)?;
match used {
U::NONE => some_err(
&"meta attribute provided, and (conditionally) recognised; but not used in these particular circumstances"
),
U::BOOL_ONLY => some_err(
&"meta attribute provided with value, and (conditionally) recognised with value; but in these particular circumstances only used as a boolean"
),
U::VALUE_ONLY => some_err(
&"meta attribute provided as a unit, and (conditionally) recognised as such; but in these particular circumstances only used in contexts with a default value, so the unit is ignored"
),
U::VALUE => unreachable!(),
}
})())?;
// Now we know that even the static scan doesn't
// recognise this item.
// Maybe it's just that a value was supplied by mistake
try_case((|| {
(supplied_mode == UsageMode::Value).then(|| ())?;
let _: IsUsed = used.unit?;
some_err(
&"meta attribute value provided, but is used only as a boolean",
)
})())?;
// Maybe it's just that a *unit* was supplied by mistake
try_case((|| {
(supplied_mode == UsageMode::Unit).then(|| ())?;
let _: IsUsed = used.value?;
some_err(
&"meta attribute provided as unit (flag), but is used only with default values, so the unit is ignored"
)
})())?;
// Look to see if it would have been recognised in
// another scope. That would mean the attr is
// merely misplaced, rather than totally wrong.
try_case((|| {
let y_scopes = Scope::iter()
.filter(|&scope| {
recog.map.contains_key(&BorrowedDesig { scope, lpaths })
})
.collect_vec();
if y_scopes.is_empty() {
return None;
}
let y_ss = SuppliedScope::iter()
.filter(|ss| ss.recog_search().any(|s| y_scopes.contains(&s)))
.map(|ss| ss.to_string())
.join("/");
let y_scopes = y_scopes.iter().map(|s| s.as_ref()).join("/");
some_err(&format_args!(
"meta attribute provided for {}, but recognised by template only for {} ({})",
supplied_scope,
y_ss,
y_scopes,
))
})())?;
// Look to see if user supplied `#[deftly(foo(bar))]`
// when the template wanted `#[deftly(foo = "bar")]`.
try_case((|| {
let (upper, recog) =
supplied_scope.recog_search().find_map(|scope| {
let upper = BorrowedDesig {
scope,
lpaths: lpaths.split_last()?.1,
};
let recog = recog.map.get(&upper)?;
Some((upper, recog))
})?;
let _: IsUsed = recog.value?;
some_err(&format_args!(
"nested meta provided and not recognised; but, template would recognise {}",
DisplayAsIfSpecified {
lpaths: upper.lpaths,
inside_after: " = ..",
},
))
})())?;
// Look to see if the specified attribute is a prefix of
// a recognised one
try_case((|| {
recog.map.keys().find_map(|desig| {
// deliberately ignore scope
if !itertools::equal(
lpaths.iter().copied(),
desig.label.lpaths.iter().take(lpaths.len()),
) {
return None;
}
Some(())
})?;
some_err(&format_args!(
"meta attribute provided, but not recognised; template only uses it as a container"
))
})())?;
Err(supplied_span
.error("meta attribute provided, but not recognised by template"))
}
//---------- impls of FindRecogMetas ----------
impl<O: SubstParseContext> FindRecogMetas for Template<O> {
fn find_recog_metas(&self, acc: &mut Recognised) {
for e in &self.elements {
e.find_recog_metas(acc)
}
}
}
impl<O: SubstParseContext> FindRecogMetas for TemplateElement<O> {
fn find_recog_metas(&self, acc: &mut Recognised) {
match self {
TE::Ident(..)
| TE::LitStr(_)
| TE::Literal(..)
| TE::Punct(..) => {}
TE::Group { template, .. } => template.find_recog_metas(acc),
TE::Subst(n) => n.find_recog_metas(acc),
TE::Repeat(n) => n.find_recog_metas(acc),
}
}
}
impl<O: SubstParseContext> FindRecogMetas for RepeatedTemplate<O> {
fn find_recog_metas(&self, acc: &mut Recognised) {
self.template.find_recog_metas(acc);
self.whens.find_recog_metas(acc);
}
}
impl<O: SubstParseContext> FindRecogMetas for Subst<O> {
fn find_recog_metas(&self, acc: &mut Recognised) {
self.sd.find_recog_metas(acc);
}
}
macro_rules! impL_find_recog_metas_via_iter { {
( $($gens:tt)* ), $i:ty
} => {
impl<T: FindRecogMetas, $($gens)*> FindRecogMetas for $i {
fn find_recog_metas(&self, acc: &mut Recognised) {
#[allow(for_loops_over_fallibles)]
for item in self {
item.find_recog_metas(acc)
}
}
}
} }
impL_find_recog_metas_via_iter!((), [T]);
impL_find_recog_metas_via_iter!((), Option<T>);
impL_find_recog_metas_via_iter!((U), Punctuated<T, U>);
macro_rules! impL_find_recog_metas_via_deref { {
( $($gens:tt)* ), $i:ty
} => {
impl<$($gens)*> FindRecogMetas for $i {
fn find_recog_metas(&self, acc: &mut Recognised) {
(**self).find_recog_metas(acc)
}
}
} }
impL_find_recog_metas_via_deref!((O: SubstParseContext), Argument<O>);
impL_find_recog_metas_via_deref!((T: FindRecogMetas), Box<T>);
impl<O: SubstParseContext> FindRecogMetas for SubstDetails<O> {
fn find_recog_metas(&self, acc: &mut Recognised) {
use SD::*;
match self {
Xmeta(v) => v.find_recog_metas(acc),
vpat(v, _, _) => v.find_recog_metas(acc),
vtype(v, _, _) => v.find_recog_metas(acc),
tdefvariants(v, _, _) => v.find_recog_metas(acc),
fdefine(v, _, _) => v.find_recog_metas(acc),
vdefbody(a, b, _, _) => {
a.find_recog_metas(acc);
b.find_recog_metas(acc);
}
paste(v, _) => v.find_recog_metas(acc),
paste_spanned(_span, content, ..) => {
content.find_recog_metas(acc);
}
ChangeCase(v, _, _) => v.find_recog_metas(acc),
concat(v, ..) => v.find_recog_metas(acc),
when(v, _) => v.find_recog_metas(acc),
define(v, _) => v.find_recog_metas(acc),
defcond(v, _) => v.find_recog_metas(acc),
not(v, _) => v.find_recog_metas(acc),
any(v, _) | all(v, _) => v.find_recog_metas(acc),
is_empty(_, v) => v.find_recog_metas(acc),
approx_equal(_, v) => v.find_recog_metas(acc),
For(v, _) => v.find_recog_metas(acc),
If(v, _) | select1(v, _) => v.find_recog_metas(acc),
ignore(v, _) => v.find_recog_metas(acc),
dbg(v) => v.content_parsed.find_recog_metas(acc),
tname(_)
| ttype(_)
| tdeftype(_)
| vname(_)
| fname(_)
| ftype(_)
| fpatname(_)
| vindex(..)
| findex(..)
| tdefkwd(_)
| Vis(_, _)
| tattrs(_, _, _)
| vattrs(_, _, _)
| fattrs(_, _, _)
| tgens(_)
| tdefgens(_, _)
| tgnames(_, _)
| twheres(_, _)
| UserDefined(_)
| False(_)
| True(_)
| is_struct(_)
| is_enum(_)
| is_union(_)
| v_is_unit(_)
| v_is_tuple(_)
| v_is_named(_)
| error(..)
| require_beta(..)
| dbg_all_keywords(_)
| Crate(_, _) => {}
}
}
}
impl<O: SubstParseContext> FindRecogMetas for SubstMeta<O> {
fn find_recog_metas(&self, acc: &mut Recognised) {
let recog = O::meta_recog_usage(self);
acc.update(self.desig.clone(), recog);
}
}
impl FindRecogMetas for SubstVType {
fn find_recog_metas(&self, acc: &mut Recognised) {
let Self { self_, vname } = self;
self_.find_recog_metas(acc);
vname.find_recog_metas(acc);
}
}
impl FindRecogMetas for SubstVPat {
fn find_recog_metas(&self, acc: &mut Recognised) {
let Self { vtype, fprefix } = self;
vtype.find_recog_metas(acc);
fprefix.find_recog_metas(acc);
}
}
impl<B: FindRecogMetas> FindRecogMetas for Definition<B> {
fn find_recog_metas(&self, acc: &mut Recognised) {
let Self {
name: _,
body_span: _,
body,
} = self;
body.find_recog_metas(acc);
}
}
impl FindRecogMetas for DefinitionBody {
fn find_recog_metas(&self, acc: &mut Recognised) {
match self {
DefinitionBody::Normal(v) => v.find_recog_metas(acc),
DefinitionBody::Paste(v) => v.find_recog_metas(acc),
DefinitionBody::Concat(v) => v.find_recog_metas(acc),
}
}
}
impl<O: SubstParseContext> FindRecogMetas for SubstIf<O> {
fn find_recog_metas(&self, acc: &mut Recognised) {
let Self {
tests,
otherwise,
kw_span: _,
} = self;
for (if_, then) in tests {
if_.find_recog_metas(acc);
then.find_recog_metas(acc);
}
otherwise.find_recog_metas(acc);
}
}
|