eslint-plugin-react-hooks.development.js 76.8 KB
Newer Older
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
/** @license React vundefined
 * eslint-plugin-react-hooks.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

'use strict';



if (process.env.NODE_ENV !== "production") {
  (function() {
'use strict';

/* eslint-disable no-for-of-loops/no-for-of-loops */
/**
 * Catch all identifiers that begin with "use" followed by an uppercase Latin
 * character to exclude identifiers like "user".
 */

function isHookName(s) {
  return /^use[A-Z0-9].*$/.test(s);
}
/**
 * We consider hooks to be a hook name identifier or a member expression
 * containing a hook name.
 */


function isHook(node) {
  if (node.type === 'Identifier') {
    return isHookName(node.name);
  } else if (node.type === 'MemberExpression' && !node.computed && isHook(node.property)) {
    // Only consider React.useFoo() to be namespace hooks for now to avoid false positives.
    // We can expand this check later.
    var obj = node.object;
    return obj.type === 'Identifier' && obj.name === 'React';
  } else {
    return false;
  }
}
/**
 * Checks if the node is a React component name. React component names must
 * always start with a non-lowercase letter. So `MyComponent` or `_MyComponent`
 * are valid component names for instance.
 */


function isComponentName(node) {
  if (node.type === 'Identifier') {
    return !/^[a-z]/.test(node.name);
  } else {
    return false;
  }
}

function isReactFunction(node, functionName) {
  return node.name === functionName || node.type === 'MemberExpression' && node.object.name === 'React' && node.property.name === functionName;
}
/**
 * Checks if the node is a callback argument of forwardRef. This render function
 * should follow the rules of hooks.
 */


function isForwardRefCallback(node) {
  return !!(node.parent && node.parent.callee && isReactFunction(node.parent.callee, 'forwardRef'));
}
/**
 * Checks if the node is a callback argument of React.memo. This anonymous
 * functional component should follow the rules of hooks.
 */


function isMemoCallback(node) {
  return !!(node.parent && node.parent.callee && isReactFunction(node.parent.callee, 'memo'));
}

function isInsideComponentOrHook(node) {
  while (node) {
    var functionName = getFunctionName(node);

    if (functionName) {
      if (isComponentName(functionName) || isHook(functionName)) {
        return true;
      }
    }

    if (isForwardRefCallback(node) || isMemoCallback(node)) {
      return true;
    }

    node = node.parent;
  }

  return false;
}

var RuleOfHooks = {
  create: function (context) {
    var codePathReactHooksMapStack = [];
    var codePathSegmentStack = [];
    return {
      // Maintain code segment path stack as we traverse.
      onCodePathSegmentStart: function (segment) {
        return codePathSegmentStack.push(segment);
      },
      onCodePathSegmentEnd: function () {
        return codePathSegmentStack.pop();
      },
      // Maintain code path stack as we traverse.
      onCodePathStart: function () {
        return codePathReactHooksMapStack.push(new Map());
      },
      // Process our code path.
      //
      // Everything is ok if all React Hooks are both reachable from the initial
      // segment and reachable from every final segment.
      onCodePathEnd: function (codePath, codePathNode) {
        var reactHooksMap = codePathReactHooksMapStack.pop();

        if (reactHooksMap.size === 0) {
          return;
        } // All of the segments which are cyclic are recorded in this set.


        var cyclic = new Set();
        /**
         * Count the number of code paths from the start of the function to this
         * segment. For example:
         *
         * ```js
         * function MyComponent() {
         *   if (condition) {
         *     // Segment 1
         *   } else {
         *     // Segment 2
         *   }
         *   // Segment 3
         * }
         * ```
         *
         * Segments 1 and 2 have one path to the beginning of `MyComponent` and
         * segment 3 has two paths to the beginning of `MyComponent` since we
         * could have either taken the path of segment 1 or segment 2.
         *
         * Populates `cyclic` with cyclic segments.
         */

        function countPathsFromStart(segment, pathHistory) {
          var cache = countPathsFromStart.cache;
          var paths = cache.get(segment.id);
          var pathList = new Set(pathHistory); // If `pathList` includes the current segment then we've found a cycle!
          // We need to fill `cyclic` with all segments inside cycle

          if (pathList.has(segment.id)) {
            var pathArray = [].concat(pathList);
            var cyclicSegments = pathArray.slice(pathArray.indexOf(segment.id) + 1);
            var _iteratorNormalCompletion = true;
            var _didIteratorError = false;
            var _iteratorError = undefined;

            try {
              for (var _iterator = cyclicSegments[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                var cyclicSegment = _step.value;
                cyclic.add(cyclicSegment);
              }
            } catch (err) {
              _didIteratorError = true;
              _iteratorError = err;
            } finally {
              try {
                if (!_iteratorNormalCompletion && _iterator.return != null) {
                  _iterator.return();
                }
              } finally {
                if (_didIteratorError) {
                  throw _iteratorError;
                }
              }
            }

            return 0;
          } // add the current segment to pathList


          pathList.add(segment.id); // We have a cached `paths`. Return it.

          if (paths !== undefined) {
            return paths;
          }

          if (codePath.thrownSegments.includes(segment)) {
            paths = 0;
          } else if (segment.prevSegments.length === 0) {
            paths = 1;
          } else {
            paths = 0;
            var _iteratorNormalCompletion2 = true;
            var _didIteratorError2 = false;
            var _iteratorError2 = undefined;

            try {
              for (var _iterator2 = segment.prevSegments[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
                var prevSegment = _step2.value;
                paths += countPathsFromStart(prevSegment, pathList);
              }
            } catch (err) {
              _didIteratorError2 = true;
              _iteratorError2 = err;
            } finally {
              try {
                if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
                  _iterator2.return();
                }
              } finally {
                if (_didIteratorError2) {
                  throw _iteratorError2;
                }
              }
            }
          } // If our segment is reachable then there should be at least one path
          // to it from the start of our code path.


          if (segment.reachable && paths === 0) {
            cache.delete(segment.id);
          } else {
            cache.set(segment.id, paths);
          }

          return paths;
        }
        /**
         * Count the number of code paths from this segment to the end of the
         * function. For example:
         *
         * ```js
         * function MyComponent() {
         *   // Segment 1
         *   if (condition) {
         *     // Segment 2
         *   } else {
         *     // Segment 3
         *   }
         * }
         * ```
         *
         * Segments 2 and 3 have one path to the end of `MyComponent` and
         * segment 1 has two paths to the end of `MyComponent` since we could
         * either take the path of segment 1 or segment 2.
         *
         * Populates `cyclic` with cyclic segments.
         */


        function countPathsToEnd(segment, pathHistory) {
          var cache = countPathsToEnd.cache;
          var paths = cache.get(segment.id);
          var pathList = new Set(pathHistory); // If `pathList` includes the current segment then we've found a cycle!
          // We need to fill `cyclic` with all segments inside cycle

          if (pathList.has(segment.id)) {
            var pathArray = Array.from(pathList);
            var cyclicSegments = pathArray.slice(pathArray.indexOf(segment.id) + 1);
            var _iteratorNormalCompletion3 = true;
            var _didIteratorError3 = false;
            var _iteratorError3 = undefined;

            try {
              for (var _iterator3 = cyclicSegments[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
                var cyclicSegment = _step3.value;
                cyclic.add(cyclicSegment);
              }
            } catch (err) {
              _didIteratorError3 = true;
              _iteratorError3 = err;
            } finally {
              try {
                if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
                  _iterator3.return();
                }
              } finally {
                if (_didIteratorError3) {
                  throw _iteratorError3;
                }
              }
            }

            return 0;
          } // add the current segment to pathList


          pathList.add(segment.id); // We have a cached `paths`. Return it.

          if (paths !== undefined) {
            return paths;
          }

          if (codePath.thrownSegments.includes(segment)) {
            paths = 0;
          } else if (segment.nextSegments.length === 0) {
            paths = 1;
          } else {
            paths = 0;
            var _iteratorNormalCompletion4 = true;
            var _didIteratorError4 = false;
            var _iteratorError4 = undefined;

            try {
              for (var _iterator4 = segment.nextSegments[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
                var nextSegment = _step4.value;
                paths += countPathsToEnd(nextSegment, pathList);
              }
            } catch (err) {
              _didIteratorError4 = true;
              _iteratorError4 = err;
            } finally {
              try {
                if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
                  _iterator4.return();
                }
              } finally {
                if (_didIteratorError4) {
                  throw _iteratorError4;
                }
              }
            }
          }

          cache.set(segment.id, paths);
          return paths;
        }
        /**
         * Gets the shortest path length to the start of a code path.
         * For example:
         *
         * ```js
         * function MyComponent() {
         *   if (condition) {
         *     // Segment 1
         *   }
         *   // Segment 2
         * }
         * ```
         *
         * There is only one path from segment 1 to the code path start. Its
         * length is one so that is the shortest path.
         *
         * There are two paths from segment 2 to the code path start. One
         * through segment 1 with a length of two and another directly to the
         * start with a length of one. The shortest path has a length of one
         * so we would return that.
         */


        function shortestPathLengthToStart(segment) {
          var cache = shortestPathLengthToStart.cache;
          var length = cache.get(segment.id); // If `length` is null then we found a cycle! Return infinity since
          // the shortest path is definitely not the one where we looped.

          if (length === null) {
            return Infinity;
          } // We have a cached `length`. Return it.


          if (length !== undefined) {
            return length;
          } // Compute `length` and cache it. Guarding against cycles.


          cache.set(segment.id, null);

          if (segment.prevSegments.length === 0) {
            length = 1;
          } else {
            length = Infinity;
            var _iteratorNormalCompletion5 = true;
            var _didIteratorError5 = false;
            var _iteratorError5 = undefined;

            try {
              for (var _iterator5 = segment.prevSegments[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
                var prevSegment = _step5.value;
                var prevLength = shortestPathLengthToStart(prevSegment);

                if (prevLength < length) {
                  length = prevLength;
                }
              }
            } catch (err) {
              _didIteratorError5 = true;
              _iteratorError5 = err;
            } finally {
              try {
                if (!_iteratorNormalCompletion5 && _iterator5.return != null) {
                  _iterator5.return();
                }
              } finally {
                if (_didIteratorError5) {
                  throw _iteratorError5;
                }
              }
            }

            length += 1;
          }

          cache.set(segment.id, length);
          return length;
        }

        countPathsFromStart.cache = new Map();
        countPathsToEnd.cache = new Map();
        shortestPathLengthToStart.cache = new Map(); // Count all code paths to the end of our component/hook. Also primes
        // the `countPathsToEnd` cache.

        var allPathsFromStartToEnd = countPathsToEnd(codePath.initialSegment); // Gets the function name for our code path. If the function name is
        // `undefined` then we know either that we have an anonymous function
        // expression or our code path is not in a function. In both cases we
        // will want to error since neither are React function components or
        // hook functions - unless it is an anonymous function argument to
        // forwardRef or memo.

        var codePathFunctionName = getFunctionName(codePathNode); // This is a valid code path for React hooks if we are directly in a React
        // function component or we are in a hook function.

        var isSomewhereInsideComponentOrHook = isInsideComponentOrHook(codePathNode);
        var isDirectlyInsideComponentOrHook = codePathFunctionName ? isComponentName(codePathFunctionName) || isHook(codePathFunctionName) : isForwardRefCallback(codePathNode) || isMemoCallback(codePathNode); // Compute the earliest finalizer level using information from the
        // cache. We expect all reachable final segments to have a cache entry
        // after calling `visitSegment()`.

        var shortestFinalPathLength = Infinity;
        var _iteratorNormalCompletion6 = true;
        var _didIteratorError6 = false;
        var _iteratorError6 = undefined;

        try {
          for (var _iterator6 = codePath.finalSegments[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
            var finalSegment = _step6.value;

            if (!finalSegment.reachable) {
              continue;
            }

            var length = shortestPathLengthToStart(finalSegment);

            if (length < shortestFinalPathLength) {
              shortestFinalPathLength = length;
            }
          } // Make sure all React Hooks pass our lint invariants. Log warnings
          // if not.

        } catch (err) {
          _didIteratorError6 = true;
          _iteratorError6 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion6 && _iterator6.return != null) {
              _iterator6.return();
            }
          } finally {
            if (_didIteratorError6) {
              throw _iteratorError6;
            }
          }
        }

        var _iteratorNormalCompletion7 = true;
        var _didIteratorError7 = false;
        var _iteratorError7 = undefined;

        try {
          for (var _iterator7 = reactHooksMap[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
            var _step7$value = _step7.value,
                segment = _step7$value[0],
                reactHooks = _step7$value[1];

            // NOTE: We could report here that the hook is not reachable, but
            // that would be redundant with more general "no unreachable"
            // lint rules.
            if (!segment.reachable) {
              continue;
            } // If there are any final segments with a shorter path to start then
            // we possibly have an early return.
            //
            // If our segment is a final segment itself then siblings could
            // possibly be early returns.


            var possiblyHasEarlyReturn = segment.nextSegments.length === 0 ? shortestFinalPathLength <= shortestPathLengthToStart(segment) : shortestFinalPathLength < shortestPathLengthToStart(segment); // Count all the paths from the start of our code path to the end of
            // our code path that go _through_ this segment. The critical piece
            // of this is _through_. If we just call `countPathsToEnd(segment)`
            // then we neglect that we may have gone through multiple paths to get
            // to this point! Consider:
            //
            // ```js
            // function MyComponent() {
            //   if (a) {
            //     // Segment 1
            //   } else {
            //     // Segment 2
            //   }
            //   // Segment 3
            //   if (b) {
            //     // Segment 4
            //   } else {
            //     // Segment 5
            //   }
            // }
            // ```
            //
            // In this component we have four code paths:
            //
            // 1. `a = true; b = true`
            // 2. `a = true; b = false`
            // 3. `a = false; b = true`
            // 4. `a = false; b = false`
            //
            // From segment 3 there are two code paths to the end through segment
            // 4 and segment 5. However, we took two paths to get here through
            // segment 1 and segment 2.
            //
            // If we multiply the paths from start (two) by the paths to end (two)
            // for segment 3 we get four. Which is our desired count.

            var pathsFromStartToEnd = countPathsFromStart(segment) * countPathsToEnd(segment); // Is this hook a part of a cyclic segment?

            var cycled = cyclic.has(segment.id);
            var _iteratorNormalCompletion8 = true;
            var _didIteratorError8 = false;
            var _iteratorError8 = undefined;

            try {
              for (var _iterator8 = reactHooks[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
                var hook = _step8.value;

                // Report an error if a hook may be called more then once.
                if (cycled) {
                  context.report({
                    node: hook,
                    message: "React Hook \"" + context.getSource(hook) + "\" may be executed " + 'more than once. Possibly because it is called in a loop. ' + 'React Hooks must be called in the exact same order in ' + 'every component render.'
                  });
                } // If this is not a valid code path for React hooks then we need to
                // log a warning for every hook in this code path.
                //
                // Pick a special message depending on the scope this hook was
                // called in.


                if (isDirectlyInsideComponentOrHook) {
                  // Report an error if a hook does not reach all finalizing code
                  // path segments.
                  //
                  // Special case when we think there might be an early return.
                  if (!cycled && pathsFromStartToEnd !== allPathsFromStartToEnd) {
                    var message = "React Hook \"" + context.getSource(hook) + "\" is called " + 'conditionally. React Hooks must be called in the exact ' + 'same order in every component render.' + (possiblyHasEarlyReturn ? ' Did you accidentally call a React Hook after an' + ' early return?' : '');
                    context.report({
                      node: hook,
                      message: message
                    });
                  }
                } else if (codePathNode.parent && (codePathNode.parent.type === 'MethodDefinition' || codePathNode.parent.type === 'ClassProperty') && codePathNode.parent.value === codePathNode) {
                  // Custom message for hooks inside a class
                  var _message = "React Hook \"" + context.getSource(hook) + "\" cannot be called " + 'in a class component. React Hooks must be called in a ' + 'React function component or a custom React Hook function.';

                  context.report({
                    node: hook,
                    message: _message
                  });
                } else if (codePathFunctionName) {
                  // Custom message if we found an invalid function name.
                  var _message2 = "React Hook \"" + context.getSource(hook) + "\" is called in " + ("function \"" + context.getSource(codePathFunctionName) + "\" ") + 'that is neither a React function component nor a custom ' + 'React Hook function.';

                  context.report({
                    node: hook,
                    message: _message2
                  });
                } else if (codePathNode.type === 'Program') {
                  // These are dangerous if you have inline requires enabled.
                  var _message3 = "React Hook \"" + context.getSource(hook) + "\" cannot be called " + 'at the top level. React Hooks must be called in a ' + 'React function component or a custom React Hook function.';

                  context.report({
                    node: hook,
                    message: _message3
                  });
                } else {
                  // Assume in all other cases the user called a hook in some
                  // random function callback. This should usually be true for
                  // anonymous function expressions. Hopefully this is clarifying
                  // enough in the common case that the incorrect message in
                  // uncommon cases doesn't matter.
                  if (isSomewhereInsideComponentOrHook) {
                    var _message4 = "React Hook \"" + context.getSource(hook) + "\" cannot be called " + 'inside a callback. React Hooks must be called in a ' + 'React function component or a custom React Hook function.';

                    context.report({
                      node: hook,
                      message: _message4
                    });
                  }
                }
              }
            } catch (err) {
              _didIteratorError8 = true;
              _iteratorError8 = err;
            } finally {
              try {
                if (!_iteratorNormalCompletion8 && _iterator8.return != null) {
                  _iterator8.return();
                }
              } finally {
                if (_didIteratorError8) {
                  throw _iteratorError8;
                }
              }
            }
          }
        } catch (err) {
          _didIteratorError7 = true;
          _iteratorError7 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion7 && _iterator7.return != null) {
              _iterator7.return();
            }
          } finally {
            if (_didIteratorError7) {
              throw _iteratorError7;
            }
          }
        }
      },
      // Missed opportunity...We could visit all `Identifier`s instead of all
      // `CallExpression`s and check that _every use_ of a hook name is valid.
      // But that gets complicated and enters type-system territory, so we're
      // only being strict about hook calls for now.
      CallExpression: function (node) {
        if (isHook(node.callee)) {
          // Add the hook node to a map keyed by the code path segment. We will
          // do full code path analysis at the end of our code path.
          var reactHooksMap = last(codePathReactHooksMapStack);
          var codePathSegment = last(codePathSegmentStack);
          var reactHooks = reactHooksMap.get(codePathSegment);

          if (!reactHooks) {
            reactHooks = [];
            reactHooksMap.set(codePathSegment, reactHooks);
          }

          reactHooks.push(node.callee);
        }
      }
    };
  }
};
/**
 * Gets the static name of a function AST node. For function declarations it is
 * easy. For anonymous function expressions it is much harder. If you search for
 * `IsAnonymousFunctionDefinition()` in the ECMAScript spec you'll find places
 * where JS gives anonymous function expressions names. We roughly detect the
 * same AST nodes with some exceptions to better fit our usecase.
 */

function getFunctionName(node) {
  if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' && node.id) {
    // function useHook() {}
    // const whatever = function useHook() {};
    //
    // Function declaration or function expression names win over any
    // assignment statements or other renames.
    return node.id;
  } else if (node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') {
    if (node.parent.type === 'VariableDeclarator' && node.parent.init === node) {
      // const useHook = () => {};
      return node.parent.id;
    } else if (node.parent.type === 'AssignmentExpression' && node.parent.right === node && node.parent.operator === '=') {
      // useHook = () => {};
      return node.parent.left;
    } else if (node.parent.type === 'Property' && node.parent.value === node && !node.parent.computed) {
      // {useHook: () => {}}
      // {useHook() {}}
      return node.parent.key; // NOTE: We could also support `ClassProperty` and `MethodDefinition`
      // here to be pedantic. However, hooks in a class are an anti-pattern. So
      // we don't allow it to error early.
      //
      // class {useHook = () => {}}
      // class {useHook() {}}
    } else if (node.parent.type === 'AssignmentPattern' && node.parent.right === node && !node.parent.computed) {
      // const {useHook = () => {}} = {};
      // ({useHook = () => {}} = {});
      //
      // Kinda clowny, but we'd said we'd follow spec convention for
      // `IsAnonymousFunctionDefinition()` usage.
      return node.parent.left;
    } else {
      return undefined;
    }
  } else {
    return undefined;
  }
}
/**
 * Convenience function for peeking the last item in a stack.
 */


function last(array) {
  return array[array.length - 1];
}

/* eslint-disable no-for-of-loops/no-for-of-loops */

var ExhaustiveDeps = {
  meta: {
    schema: [{
      type: 'object',
      additionalProperties: false,
      properties: {
        additionalHooks: {
          type: 'string'
        }
      }
    }]
  },
  create: function (context) {
    // Parse the `additionalHooks` regex.
    var additionalHooks = context.options && context.options[0] && context.options[0].additionalHooks ? new RegExp(context.options[0].additionalHooks) : undefined;
    var options = {
      additionalHooks: additionalHooks
    }; // Should be shared between visitors.

    var setStateCallSites = new WeakMap();
    var stateVariables = new WeakSet();
    var staticKnownValueCache = new WeakMap();
    var functionWithoutCapturedValueCache = new WeakMap();

    function memoizeWithWeakMap(fn, map) {
      return function (arg) {
        if (map.has(arg)) {
          // to verify cache hits:
          // console.log(arg.name)
          return map.get(arg);
        }

        var result = fn(arg);
        map.set(arg, result);
        return result;
      };
    }

    return {
      FunctionExpression: visitFunctionExpression,
      ArrowFunctionExpression: visitFunctionExpression
    };
    /**
     * Visitor for both function expressions and arrow function expressions.
     */

    function visitFunctionExpression(node) {
      // We only want to lint nodes which are reactive hook callbacks.
      if (node.type !== 'FunctionExpression' && node.type !== 'ArrowFunctionExpression' || node.parent.type !== 'CallExpression') {
        return;
      }

      var callbackIndex = getReactiveHookCallbackIndex(node.parent.callee, options);

      if (node.parent.arguments[callbackIndex] !== node) {
        return;
      } // Get the reactive hook node.


      var reactiveHook = node.parent.callee;
      var reactiveHookName = getNodeWithoutReactNamespace(reactiveHook).name;
      var isEffect = /Effect($|[^a-z])/g.test(reactiveHookName); // Get the declared dependencies for this reactive hook. If there is no
      // second argument then the reactive callback will re-run on every render.
      // So no need to check for dependency inclusion.

      var depsIndex = callbackIndex + 1;
      var declaredDependenciesNode = node.parent.arguments[depsIndex];

      if (!declaredDependenciesNode && !isEffect) {
        // These are only used for optimization.
        if (reactiveHookName === 'useMemo' || reactiveHookName === 'useCallback') {
          // TODO: Can this have a suggestion?
          context.report({
            node: node.parent.callee,
            message: "React Hook " + reactiveHookName + " does nothing when called with " + "only one argument. Did you forget to pass an array of " + "dependencies?"
          });
        }

        return;
      }

      if (isEffect && node.async) {
        context.report({
          node: node,
          message: "Effect callbacks are synchronous to prevent race conditions. " + "Put the async function inside:\n\n" + 'useEffect(() => {\n' + '  async function fetchData() {\n' + '    // You can await here\n' + '    const response = await MyAPI.getData(someId);\n' + '    // ...\n' + '  }\n' + '  fetchData();\n' + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + 'Learn more about data fetching with Hooks: https://fb.me/react-hooks-data-fetching'
        });
      } // Get the current scope.


      var scope = context.getScope(); // Find all our "pure scopes". On every re-render of a component these
      // pure scopes may have changes to the variables declared within. So all
      // variables used in our reactive hook callback but declared in a pure
      // scope need to be listed as dependencies of our reactive hook callback.
      //
      // According to the rules of React you can't read a mutable value in pure
      // scope. We can't enforce this in a lint so we trust that all variables
      // declared outside of pure scope are indeed frozen.

      var pureScopes = new Set();
      var componentScope = null;
      {
        var currentScope = scope.upper;

        while (currentScope) {
          pureScopes.add(currentScope);

          if (currentScope.type === 'function') {
            break;
          }

          currentScope = currentScope.upper;
        } // If there is no parent function scope then there are no pure scopes.
        // The ones we've collected so far are incorrect. So don't continue with
        // the lint.


        if (!currentScope) {
          return;
        }

        componentScope = currentScope;
      } // Next we'll define a few helpers that helps us
      // tell if some values don't have to be declared as deps.
      // Some are known to be static based on Hook calls.
      // const [state, setState] = useState() / React.useState()
      //               ^^^ true for this reference
      // const [state, dispatch] = useReducer() / React.useReducer()
      //               ^^^ true for this reference
      // const ref = useRef()
      //       ^^^ true for this reference
      // False for everything else.

      function isStaticKnownHookValue(resolved) {
        if (!Array.isArray(resolved.defs)) {
          return false;
        }

        var def = resolved.defs[0];

        if (def == null) {
          return false;
        } // Look for `let stuff = ...`


        if (def.node.type !== 'VariableDeclarator') {
          return false;
        }

        var init = def.node.init;

        if (init == null) {
          return false;
        } // Detect primitive constants
        // const foo = 42


        var declaration = def.node.parent;

        if (declaration == null) {
          // This might happen if variable is declared after the callback.
          // In that case ESLint won't set up .parent refs.
          // So we'll set them up manually.
          fastFindReferenceWithParent(componentScope.block, def.node.id);
          declaration = def.node.parent;

          if (declaration == null) {
            return false;
          }
        }

        if (declaration.kind === 'const' && init.type === 'Literal' && (typeof init.value === 'string' || typeof init.value === 'number' || init.value === null)) {
          // Definitely static
          return true;
        } // Detect known Hook calls
        // const [_, setState] = useState()


        if (init.type !== 'CallExpression') {
          return false;
        }

        var callee = init.callee; // Step into `= React.something` initializer.

        if (callee.type === 'MemberExpression' && callee.object.name === 'React' && callee.property != null && !callee.computed) {
          callee = callee.property;
        }

        if (callee.type !== 'Identifier') {
          return false;
        }

        var id = def.node.id;
        var _callee = callee,
            name = _callee.name;

        if (name === 'useRef' && id.type === 'Identifier') {
          // useRef() return value is static.
          return true;
        } else if (name === 'useState' || name === 'useReducer') {
          // Only consider second value in initializing tuple static.
          if (id.type === 'ArrayPattern' && id.elements.length === 2 && Array.isArray(resolved.identifiers)) {
            // Is second tuple value the same reference we're checking?
            if (id.elements[1] === resolved.identifiers[0]) {
              if (name === 'useState') {
                var references = resolved.references;

                for (var i = 0; i < references.length; i++) {
                  setStateCallSites.set(references[i].identifier, id.elements[0]);
                }
              } // Setter is static.


              return true;
            } else if (id.elements[0] === resolved.identifiers[0]) {
              if (name === 'useState') {
                var _references = resolved.references;

                for (var _i = 0; _i < _references.length; _i++) {
                  stateVariables.add(_references[_i].identifier);
                }
              } // State variable itself is dynamic.


              return false;
            }
          }
        } // By default assume it's dynamic.


        return false;
      } // Some are just functions that don't reference anything dynamic.


      function isFunctionWithoutCapturedValues(resolved) {
        if (!Array.isArray(resolved.defs)) {
          return false;
        }

        var def = resolved.defs[0];

        if (def == null) {
          return false;
        }

        if (def.node == null || def.node.id == null) {
          return false;
        } // Search the direct component subscopes for
        // top-level function definitions matching this reference.


        var fnNode = def.node;
        var childScopes = componentScope.childScopes;
        var fnScope = null;
        var i;

        for (i = 0; i < childScopes.length; i++) {
          var childScope = childScopes[i];
          var childScopeBlock = childScope.block;

          if ( // function handleChange() {}
          fnNode.type === 'FunctionDeclaration' && childScopeBlock === fnNode || // const handleChange = () => {}
          // const handleChange = function() {}
          fnNode.type === 'VariableDeclarator' && childScopeBlock.parent === fnNode) {
            // Found it!
            fnScope = childScope;
            break;
          }
        }

        if (fnScope == null) {
          return false;
        } // Does this function capture any values
        // that are in pure scopes (aka render)?


        for (i = 0; i < fnScope.through.length; i++) {
          var ref = fnScope.through[i];

          if (ref.resolved == null) {
            continue;
          }

          if (pureScopes.has(ref.resolved.scope) && // Static values are fine though,
          // although we won't check functions deeper.
          !memoizedIsStaticKnownHookValue(ref.resolved)) {
            return false;
          }
        } // If we got here, this function doesn't capture anything
        // from render--or everything it captures is known static.


        return true;
      } // Remember such values. Avoid re-running extra checks on them.


      var memoizedIsStaticKnownHookValue = memoizeWithWeakMap(isStaticKnownHookValue, staticKnownValueCache);
      var memoizedIsFunctionWithoutCapturedValues = memoizeWithWeakMap(isFunctionWithoutCapturedValues, functionWithoutCapturedValueCache); // These are usually mistaken. Collect them.

      var currentRefsInEffectCleanup = new Map(); // Is this reference inside a cleanup function for this effect node?
      // We can check by traversing scopes upwards  from the reference, and checking
      // if the last "return () => " we encounter is located directly inside the effect.

      function isInsideEffectCleanup(reference) {
        var curScope = reference.from;
        var isInReturnedFunction = false;

        while (curScope.block !== node) {
          if (curScope.type === 'function') {
            isInReturnedFunction = curScope.block.parent != null && curScope.block.parent.type === 'ReturnStatement';
          }

          curScope = curScope.upper;
        }

        return isInReturnedFunction;
      } // Get dependencies from all our resolved references in pure scopes.
      // Key is dependency string, value is whether it's static.


      var dependencies = new Map();
      gatherDependenciesRecursively(scope);

      function gatherDependenciesRecursively(currentScope) {
        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = currentScope.references[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var reference = _step.value;

            // If this reference is not resolved or it is not declared in a pure
            // scope then we don't care about this reference.
            if (!reference.resolved) {
              continue;
            }

            if (!pureScopes.has(reference.resolved.scope)) {
              continue;
            } // Narrow the scope of a dependency if it is, say, a member expression.
            // Then normalize the narrowed dependency.


            var referenceNode = fastFindReferenceWithParent(node, reference.identifier);
            var dependencyNode = getDependency(referenceNode);
            var dependency = toPropertyAccessString(dependencyNode); // Accessing ref.current inside effect cleanup is bad.

            if ( // We're in an effect...
            isEffect && // ... and this look like accessing .current...
            dependencyNode.type === 'Identifier' && dependencyNode.parent.type === 'MemberExpression' && !dependencyNode.parent.computed && dependencyNode.parent.property.type === 'Identifier' && dependencyNode.parent.property.name === 'current' && // ...in a cleanup function or below...
            isInsideEffectCleanup(reference)) {
              currentRefsInEffectCleanup.set(dependency, {
                reference: reference,
                dependencyNode: dependencyNode
              });
            }

            var def = reference.resolved.defs[0];

            if (def == null) {
              continue;
            } // Ignore references to the function itself as it's not defined yet.


            if (def.node != null && def.node.init === node.parent) {
              continue;
            } // Ignore Flow type parameters


            if (def.type === 'TypeParameter') {
              continue;
            } // Add the dependency to a map so we can make sure it is referenced
            // again in our dependencies array. Remember whether it's static.


            if (!dependencies.has(dependency)) {
              var resolved = reference.resolved;
              var isStatic = memoizedIsStaticKnownHookValue(resolved) || memoizedIsFunctionWithoutCapturedValues(resolved);
              dependencies.set(dependency, {
                isStatic: isStatic,
                references: [reference]
              });
            } else {
              dependencies.get(dependency).references.push(reference);
            }
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator.return != null) {
              _iterator.return();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }

        var _iteratorNormalCompletion2 = true;
        var _didIteratorError2 = false;
        var _iteratorError2 = undefined;

        try {
          for (var _iterator2 = currentScope.childScopes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
            var childScope = _step2.value;
            gatherDependenciesRecursively(childScope);
          }
        } catch (err) {
          _didIteratorError2 = true;
          _iteratorError2 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
              _iterator2.return();
            }
          } finally {
            if (_didIteratorError2) {
              throw _iteratorError2;
            }
          }
        }
      } // Warn about accessing .current in cleanup effects.


      currentRefsInEffectCleanup.forEach(function (_ref, dependency) {
        var reference = _ref.reference,
            dependencyNode = _ref.dependencyNode;
        var references = reference.resolved.references; // Is React managing this ref or us?
        // Let's see if we can find a .current assignment.

        var foundCurrentAssignment = false;

        for (var i = 0; i < references.length; i++) {
          var identifier = references[i].identifier;
          var parent = identifier.parent;

          if (parent != null && // ref.current
          parent.type === 'MemberExpression' && !parent.computed && parent.property.type === 'Identifier' && parent.property.name === 'current' && // ref.current = <something>
          parent.parent.type === 'AssignmentExpression' && parent.parent.left === parent) {
            foundCurrentAssignment = true;
            break;
          }
        } // We only want to warn about React-managed refs.


        if (foundCurrentAssignment) {
          return;
        }

        context.report({
          node: dependencyNode.parent.property,
          message: "The ref value '" + dependency + ".current' will likely have " + "changed by the time this effect cleanup function runs. If " + "this ref points to a node rendered by React, copy " + ("'" + dependency + ".current' to a variable inside the effect, and ") + "use that variable in the cleanup function."
        });
      }); // Warn about assigning to variables in the outer scope.
      // Those are usually bugs.

      var staleAssignments = new Set();

      function reportStaleAssignment(writeExpr, key) {
        if (staleAssignments.has(key)) {
          return;
        }

        staleAssignments.add(key);
        context.report({
          node: writeExpr,
          message: "Assignments to the '" + key + "' variable from inside React Hook " + (context.getSource(reactiveHook) + " will be lost after each ") + "render. To preserve the value over time, store it in a useRef " + "Hook and keep the mutable value in the '.current' property. " + "Otherwise, you can move this variable directly inside " + (context.getSource(reactiveHook) + ".")
        });
      } // Remember which deps are optional and report bad usage first.


      var optionalDependencies = new Set();
      dependencies.forEach(function (_ref2, key) {
        var isStatic = _ref2.isStatic,
            references = _ref2.references;

        if (isStatic) {
          optionalDependencies.add(key);
        }

        references.forEach(function (reference) {
          if (reference.writeExpr) {
            reportStaleAssignment(reference.writeExpr, key);
          }
        });
      });

      if (staleAssignments.size > 0) {
        // The intent isn't clear so we'll wait until you fix those first.
        return;
      }

      if (!declaredDependenciesNode) {
        // Check if there are any top-level setState() calls.
        // Those tend to lead to infinite loops.
        var setStateInsideEffectWithoutDeps = null;
        dependencies.forEach(function (_ref3, key) {
          var isStatic = _ref3.isStatic,
              references = _ref3.references;

          if (setStateInsideEffectWithoutDeps) {
            return;
          }

          references.forEach(function (reference) {
            if (setStateInsideEffectWithoutDeps) {
              return;
            }

            var id = reference.identifier;
            var isSetState = setStateCallSites.has(id);

            if (!isSetState) {
              return;
            }

            var fnScope = reference.from;

            while (fnScope.type !== 'function') {
              fnScope = fnScope.upper;
            }

            var isDirectlyInsideEffect = fnScope.block === node;

            if (isDirectlyInsideEffect) {
              // TODO: we could potentially ignore early returns.
              setStateInsideEffectWithoutDeps = key;
            }
          });
        });

        if (setStateInsideEffectWithoutDeps) {
          var _collectRecommendatio = collectRecommendations({
            dependencies: dependencies,
            declaredDependencies: [],
            optionalDependencies: optionalDependencies,
            externalDependencies: new Set(),
            isEffect: true
          }),
              _suggestedDependencies = _collectRecommendatio.suggestedDependencies;

          context.report({
            node: node.parent.callee,
            message: "React Hook " + reactiveHookName + " contains a call to '" + setStateInsideEffectWithoutDeps + "'. " + "Without a list of dependencies, this can lead to an infinite chain of updates. " + "To fix this, pass [" + _suggestedDependencies.join(', ') + ("] as a second argument to the " + reactiveHookName + " Hook."),
            suggest: [{
              desc: "Add dependencies array: [" + _suggestedDependencies.join(', ') + "]",
              fix: function (fixer) {
                return fixer.insertTextAfter(node, ", [" + _suggestedDependencies.join(', ') + "]");
              }
            }]
          });
        }

        return;
      }

      var declaredDependencies = [];
      var externalDependencies = new Set();

      if (declaredDependenciesNode.type !== 'ArrayExpression') {
        // If the declared dependencies are not an array expression then we
        // can't verify that the user provided the correct dependencies. Tell
        // the user this in an error.
        context.report({
          node: declaredDependenciesNode,
          message: "React Hook " + context.getSource(reactiveHook) + " was passed a " + 'dependency list that is not an array literal. This means we ' + "can't statically verify whether you've passed the correct " + 'dependencies.'
        });
      } else {
        declaredDependenciesNode.elements.forEach(function (declaredDependencyNode) {
          // Skip elided elements.
          if (declaredDependencyNode === null) {
            return;
          } // If we see a spread element then add a special warning.


          if (declaredDependencyNode.type === 'SpreadElement') {
            context.report({
              node: declaredDependencyNode,
              message: "React Hook " + context.getSource(reactiveHook) + " has a spread " + "element in its dependency array. This means we can't " + "statically verify whether you've passed the " + 'correct dependencies.'
            });
            return;
          } // Try to normalize the declared dependency. If we can't then an error
          // will be thrown. We will catch that error and report an error.


          var declaredDependency;

          try {
            declaredDependency = toPropertyAccessString(declaredDependencyNode);
          } catch (error) {
            if (/Unsupported node type/.test(error.message)) {
              if (declaredDependencyNode.type === 'Literal') {
                if (dependencies.has(declaredDependencyNode.value)) {
                  context.report({
                    node: declaredDependencyNode,
                    message: "The " + declaredDependencyNode.raw + " literal is not a valid dependency " + "because it never changes. " + ("Did you mean to include " + declaredDependencyNode.value + " in the array instead?")
                  });
                } else {
                  context.report({
                    node: declaredDependencyNode,
                    message: "The " + declaredDependencyNode.raw + " literal is not a valid dependency " + 'because it never changes. You can safely remove it.'
                  });
                }
              } else {
                context.report({
                  node: declaredDependencyNode,
                  message: "React Hook " + context.getSource(reactiveHook) + " has a " + "complex expression in the dependency array. " + 'Extract it to a separate variable so it can be statically checked.'
                });
              }

              return;
            } else {
              throw error;
            }
          }

          var maybeID = declaredDependencyNode;

          while (maybeID.type === 'MemberExpression') {
            maybeID = maybeID.object;
          }

          var isDeclaredInComponent = !componentScope.through.some(function (ref) {
            return ref.identifier === maybeID;
          }); // Add the dependency to our declared dependency map.

          declaredDependencies.push({
            key: declaredDependency,
            node: declaredDependencyNode
          });

          if (!isDeclaredInComponent) {
            externalDependencies.add(declaredDependency);
          }
        });
      }

      var _collectRecommendatio2 = collectRecommendations({
        dependencies: dependencies,
        declaredDependencies: declaredDependencies,
        optionalDependencies: optionalDependencies,
        externalDependencies: externalDependencies,
        isEffect: isEffect
      }),
          suggestedDependencies = _collectRecommendatio2.suggestedDependencies,
          unnecessaryDependencies = _collectRecommendatio2.unnecessaryDependencies,
          missingDependencies = _collectRecommendatio2.missingDependencies,
          duplicateDependencies = _collectRecommendatio2.duplicateDependencies;

      var problemCount = duplicateDependencies.size + missingDependencies.size + unnecessaryDependencies.size;

      if (problemCount === 0) {
        // If nothing else to report, check if some callbacks
        // are bare and would invalidate on every render.
        var bareFunctions = scanForDeclaredBareFunctions({
          declaredDependencies: declaredDependencies,
          declaredDependenciesNode: declaredDependenciesNode,
          componentScope: componentScope,
          scope: scope
        });
        bareFunctions.forEach(function (_ref4) {
          var fn = _ref4.fn,
              suggestUseCallback = _ref4.suggestUseCallback;
          var message = "The '" + fn.name.name + "' function makes the dependencies of " + (reactiveHookName + " Hook (at line " + declaredDependenciesNode.loc.start.line + ") ") + "change on every render.";

          if (suggestUseCallback) {
            message += " To fix this, " + ("wrap the '" + fn.name.name + "' definition into its own useCallback() Hook.");
          } else {
            message += " Move it inside the " + reactiveHookName + " callback. " + ("Alternatively, wrap the '" + fn.name.name + "' definition into its own useCallback() Hook.");
          }

          var suggest; // Only handle the simple case: arrow functions.
          // Wrapping function declarations can mess up hoisting.

          if (suggestUseCallback && fn.type === 'Variable') {
            suggest = [{
              desc: "Wrap the '" + fn.name.name + "' definition into its own useCallback() Hook.",
              fix: function (fixer) {
                return [// TODO: also add an import?
                fixer.insertTextBefore(fn.node.init, 'useCallback('), // TODO: ideally we'd gather deps here but it would require
                // restructuring the rule code. This will cause a new lint
                // error to appear immediately for useCallback. Note we're
                // not adding [] because would that changes semantics.
                fixer.insertTextAfter(fn.node.init, ')')];
              }
            }];
          } // TODO: What if the function needs to change on every render anyway?
          // Should we suggest removing effect deps as an appropriate fix too?


          context.report({
            // TODO: Why not report this at the dependency site?
            node: fn.node,
            message: message,
            suggest: suggest
          });
        });
        return;
      } // If we're going to report a missing dependency,
      // we might as well recalculate the list ignoring
      // the currently specified deps. This can result
      // in some extra deduplication. We can't do this
      // for effects though because those have legit
      // use cases for over-specifying deps.


      if (!isEffect && missingDependencies.size > 0) {
        suggestedDependencies = collectRecommendations({
          dependencies: dependencies,
          declaredDependencies: [],
          // Pretend we don't know
          optionalDependencies: optionalDependencies,
          externalDependencies: externalDependencies,
          isEffect: isEffect
        }).suggestedDependencies;
      } // Alphabetize the suggestions, but only if deps were already alphabetized.


      function areDeclaredDepsAlphabetized() {
        if (declaredDependencies.length === 0) {
          return true;
        }

        var declaredDepKeys = declaredDependencies.map(function (dep) {
          return dep.key;
        });
        var sortedDeclaredDepKeys = declaredDepKeys.slice().sort();
        return declaredDepKeys.join(',') === sortedDeclaredDepKeys.join(',');
      }

      if (areDeclaredDepsAlphabetized()) {
        suggestedDependencies.sort();
      }

      function getWarningMessage(deps, singlePrefix, label, fixVerb) {
        if (deps.size === 0) {
          return null;
        }

        return (deps.size > 1 ? '' : singlePrefix + ' ') + label + ' ' + (deps.size > 1 ? 'dependencies' : 'dependency') + ': ' + joinEnglish(Array.from(deps).sort().map(function (name) {
          return "'" + name + "'";
        })) + (". Either " + fixVerb + " " + (deps.size > 1 ? 'them' : 'it') + " or remove the dependency array.");
      }

      var extraWarning = '';

      if (unnecessaryDependencies.size > 0) {
        var badRef = null;
        Array.from(unnecessaryDependencies.keys()).forEach(function (key) {
          if (badRef !== null) {
            return;
          }

          if (key.endsWith('.current')) {
            badRef = key;
          }
        });

        if (badRef !== null) {
          extraWarning = " Mutable values like '" + badRef + "' aren't valid dependencies " + "because mutating them doesn't re-render the component.";
        } else if (externalDependencies.size > 0) {
          var dep = Array.from(externalDependencies)[0]; // Don't show this warning for things that likely just got moved *inside* the callback
          // because in that case they're clearly not referring to globals.

          if (!scope.set.has(dep)) {
            extraWarning = " Outer scope values like '" + dep + "' aren't valid dependencies " + "because mutating them doesn't re-render the component.";
          }
        }
      } // `props.foo()` marks `props` as a dependency because it has
      // a `this` value. This warning can be confusing.
      // So if we're going to show it, append a clarification.


      if (!extraWarning && missingDependencies.has('props')) {
        var propDep = dependencies.get('props');

        if (propDep == null) {
          return;
        }

        var refs = propDep.references;

        if (!Array.isArray(refs)) {
          return;
        }

        var isPropsOnlyUsedInMembers = true;

        for (var i = 0; i < refs.length; i++) {
          var ref = refs[i];
          var id = fastFindReferenceWithParent(componentScope.block, ref.identifier);

          if (!id) {
            isPropsOnlyUsedInMembers = false;
            break;
          }

          var parent = id.parent;

          if (parent == null) {
            isPropsOnlyUsedInMembers = false;
            break;
          }

          if (parent.type !== 'MemberExpression') {
            isPropsOnlyUsedInMembers = false;
            break;
          }
        }

        if (isPropsOnlyUsedInMembers) {
          extraWarning = " However, 'props' will change when *any* prop changes, so the " + "preferred fix is to destructure the 'props' object outside of " + ("the " + reactiveHookName + " call and refer to those specific props ") + ("inside " + context.getSource(reactiveHook) + ".");
        }
      }

      if (!extraWarning && missingDependencies.size > 0) {
        // See if the user is trying to avoid specifying a callable prop.
        // This usually means they're unaware of useCallback.
        var missingCallbackDep = null;
        missingDependencies.forEach(function (missingDep) {
          if (missingCallbackDep) {
            return;
          } // Is this a variable from top scope?


          var topScopeRef = componentScope.set.get(missingDep);
          var usedDep = dependencies.get(missingDep);

          if (usedDep.references[0].resolved !== topScopeRef) {
            return;
          } // Is this a destructured prop?


          var def = topScopeRef.defs[0];

          if (def == null || def.name == null || def.type !== 'Parameter') {
            return;
          } // Was it called in at least one case? Then it's a function.


          var isFunctionCall = false;
          var id;

          for (var _i2 = 0; _i2 < usedDep.references.length; _i2++) {
            id = usedDep.references[_i2].identifier;

            if (id != null && id.parent != null && id.parent.type === 'CallExpression' && id.parent.callee === id) {
              isFunctionCall = true;
              break;
            }
          }

          if (!isFunctionCall) {
            return;
          } // If it's missing (i.e. in component scope) *and* it's a parameter
          // then it is definitely coming from props destructuring.
          // (It could also be props itself but we wouldn't be calling it then.)


          missingCallbackDep = missingDep;
        });

        if (missingCallbackDep !== null) {
          extraWarning = " If '" + missingCallbackDep + "' changes too often, " + "find the parent component that defines it " + "and wrap that definition in useCallback.";
        }
      }

      if (!extraWarning && missingDependencies.size > 0) {
        var setStateRecommendation = null;
        missingDependencies.forEach(function (missingDep) {
          if (setStateRecommendation !== null) {
            return;
          }

          var usedDep = dependencies.get(missingDep);
          var references = usedDep.references;
          var id;
          var maybeCall;

          for (var _i3 = 0; _i3 < references.length; _i3++) {
            id = references[_i3].identifier;
            maybeCall = id.parent; // Try to see if we have setState(someExpr(missingDep)).

            while (maybeCall != null && maybeCall !== componentScope.block) {
              if (maybeCall.type === 'CallExpression') {
                var correspondingStateVariable = setStateCallSites.get(maybeCall.callee);

                if (correspondingStateVariable != null) {
                  if (correspondingStateVariable.name === missingDep) {
                    // setCount(count + 1)
                    setStateRecommendation = {
                      missingDep: missingDep,
                      setter: maybeCall.callee.name,
                      form: 'updater'
                    };
                  } else if (stateVariables.has(id)) {
                    // setCount(count + increment)
                    setStateRecommendation = {
                      missingDep: missingDep,
                      setter: maybeCall.callee.name,
                      form: 'reducer'
                    };
                  } else {
                    var resolved = references[_i3].resolved;

                    if (resolved != null) {
                      // If it's a parameter *and* a missing dep,
                      // it must be a prop or something inside a prop.
                      // Therefore, recommend an inline reducer.
                      var def = resolved.defs[0];

                      if (def != null && def.type === 'Parameter') {
                        setStateRecommendation = {
                          missingDep: missingDep,
                          setter: maybeCall.callee.name,
                          form: 'inlineReducer'
                        };
                      }
                    }
                  }

                  break;
                }
              }

              maybeCall = maybeCall.parent;
            }

            if (setStateRecommendation !== null) {
              break;
            }
          }
        });

        if (setStateRecommendation !== null) {
          switch (setStateRecommendation.form) {
            case 'reducer':
              extraWarning = " You can also replace multiple useState variables with useReducer " + ("if '" + setStateRecommendation.setter + "' needs the ") + ("current value of '" + setStateRecommendation.missingDep + "'.");
              break;

            case 'inlineReducer':
              extraWarning = " If '" + setStateRecommendation.setter + "' needs the " + ("current value of '" + setStateRecommendation.missingDep + "', ") + "you can also switch to useReducer instead of useState and " + ("read '" + setStateRecommendation.missingDep + "' in the reducer.");
              break;

            case 'updater':
              extraWarning = " You can also do a functional update '" + setStateRecommendation.setter + "(" + setStateRecommendation.missingDep.substring(0, 1) + " => ...)' if you only need '" + setStateRecommendation.missingDep + "'" + (" in the '" + setStateRecommendation.setter + "' call.");
              break;

            default:
              throw new Error('Unknown case.');
          }
        }
      }

      context.report({
        node: declaredDependenciesNode,
        message: "React Hook " + context.getSource(reactiveHook) + " has " + ( // To avoid a long message, show the next actionable item.
        getWarningMessage(missingDependencies, 'a', 'missing', 'include') || getWarningMessage(unnecessaryDependencies, 'an', 'unnecessary', 'exclude') || getWarningMessage(duplicateDependencies, 'a', 'duplicate', 'omit')) + extraWarning,
        suggest: [{
          desc: "Update the dependencies array to be: [" + suggestedDependencies.join(', ') + "]",
          fix: function (fixer) {
            // TODO: consider preserving the comments or formatting?
            return fixer.replaceText(declaredDependenciesNode, "[" + suggestedDependencies.join(', ') + "]");
          }
        }]
      });
    }
  }
}; // The meat of the logic.

function collectRecommendations(_ref5) {
  var dependencies = _ref5.dependencies,
      declaredDependencies = _ref5.declaredDependencies,
      optionalDependencies = _ref5.optionalDependencies,
      externalDependencies = _ref5.externalDependencies,
      isEffect = _ref5.isEffect;
  // Our primary data structure.
  // It is a logical representation of property chains:
  // `props` -> `props.foo` -> `props.foo.bar` -> `props.foo.bar.baz`
  //         -> `props.lol`
  //         -> `props.huh` -> `props.huh.okay`
  //         -> `props.wow`
  // We'll use it to mark nodes that are *used* by the programmer,
  // and the nodes that were *declared* as deps. Then we will
  // traverse it to learn which deps are missing or unnecessary.
  var depTree = createDepTree();

  function createDepTree() {
    return {
      isRequired: false,
      // True if used in code
      isSatisfiedRecursively: false,
      // True if specified in deps
      hasRequiredNodesBelow: false,
      // True if something deeper is used by code
      children: new Map() // Nodes for properties

    };
  } // Mark all required nodes first.
  // Imagine exclamation marks next to each used deep property.


  dependencies.forEach(function (_, key) {
    var node = getOrCreateNodeByPath(depTree, key);
    node.isRequired = true;
    markAllParentsByPath(depTree, key, function (parent) {
      parent.hasRequiredNodesBelow = true;
    });
  }); // Mark all satisfied nodes.
  // Imagine checkmarks next to each declared dependency.

  declaredDependencies.forEach(function (_ref6) {
    var key = _ref6.key;
    var node = getOrCreateNodeByPath(depTree, key);
    node.isSatisfiedRecursively = true;
  });
  optionalDependencies.forEach(function (key) {
    var node = getOrCreateNodeByPath(depTree, key);
    node.isSatisfiedRecursively = true;
  }); // Tree manipulation helpers.

  function getOrCreateNodeByPath(rootNode, path) {
    var keys = path.split('.');
    var node = rootNode;
    var _iteratorNormalCompletion3 = true;
    var _didIteratorError3 = false;
    var _iteratorError3 = undefined;

    try {
      for (var _iterator3 = keys[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
        var key = _step3.value;
        var child = node.children.get(key);

        if (!child) {
          child = createDepTree();
          node.children.set(key, child);
        }

        node = child;
      }
    } catch (err) {
      _didIteratorError3 = true;
      _iteratorError3 = err;
    } finally {
      try {
        if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
          _iterator3.return();
        }
      } finally {
        if (_didIteratorError3) {
          throw _iteratorError3;
        }
      }
    }

    return node;
  }

  function markAllParentsByPath(rootNode, path, fn) {
    var keys = path.split('.');
    var node = rootNode;
    var _iteratorNormalCompletion4 = true;
    var _didIteratorError4 = false;
    var _iteratorError4 = undefined;

    try {
      for (var _iterator4 = keys[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
        var key = _step4.value;
        var child = node.children.get(key);

        if (!child) {
          return;
        }

        fn(child);
        node = child;
      }
    } catch (err) {
      _didIteratorError4 = true;
      _iteratorError4 = err;
    } finally {
      try {
        if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
          _iterator4.return();
        }
      } finally {
        if (_didIteratorError4) {
          throw _iteratorError4;
        }
      }
    }
  } // Now we can learn which dependencies are missing or necessary.


  var missingDependencies = new Set();
  var satisfyingDependencies = new Set();
  scanTreeRecursively(depTree, missingDependencies, satisfyingDependencies, function (key) {
    return key;
  });

  function scanTreeRecursively(node, missingPaths, satisfyingPaths, keyToPath) {
    node.children.forEach(function (child, key) {
      var path = keyToPath(key);

      if (child.isSatisfiedRecursively) {
        if (child.hasRequiredNodesBelow) {
          // Remember this dep actually satisfied something.
          satisfyingPaths.add(path);
        } // It doesn't matter if there's something deeper.
        // It would be transitively satisfied since we assume immutability.
        // `props.foo` is enough if you read `props.foo.id`.


        return;
      }

      if (child.isRequired) {
        // Remember that no declared deps satisfied this node.
        missingPaths.add(path); // If we got here, nothing in its subtree was satisfied.
        // No need to search further.

        return;
      }

      scanTreeRecursively(child, missingPaths, satisfyingPaths, function (childKey) {
        return path + '.' + childKey;
      });
    });
  } // Collect suggestions in the order they were originally specified.


  var suggestedDependencies = [];
  var unnecessaryDependencies = new Set();
  var duplicateDependencies = new Set();
  declaredDependencies.forEach(function (_ref7) {
    var key = _ref7.key;

    // Does this declared dep satisfy a real need?
    if (satisfyingDependencies.has(key)) {
      if (suggestedDependencies.indexOf(key) === -1) {
        // Good one.
        suggestedDependencies.push(key);
      } else {
        // Duplicate.
        duplicateDependencies.add(key);
      }
    } else {
      if (isEffect && !key.endsWith('.current') && !externalDependencies.has(key)) {
        // Effects are allowed extra "unnecessary" deps.
        // Such as resetting scroll when ID changes.
        // Consider them legit.
        // The exception is ref.current which is always wrong.
        if (suggestedDependencies.indexOf(key) === -1) {
          suggestedDependencies.push(key);
        }
      } else {
        // It's definitely not needed.
        unnecessaryDependencies.add(key);
      }
    }
  }); // Then add the missing ones at the end.

  missingDependencies.forEach(function (key) {
    suggestedDependencies.push(key);
  });
  return {
    suggestedDependencies: suggestedDependencies,
    unnecessaryDependencies: unnecessaryDependencies,
    duplicateDependencies: duplicateDependencies,
    missingDependencies: missingDependencies
  };
} // Finds functions declared as dependencies
// that would invalidate on every render.


function scanForDeclaredBareFunctions(_ref8) {
  var declaredDependencies = _ref8.declaredDependencies,
      declaredDependenciesNode = _ref8.declaredDependenciesNode,
      componentScope = _ref8.componentScope,
      scope = _ref8.scope;
  var bareFunctions = declaredDependencies.map(function (_ref9) {
    var key = _ref9.key;
    var fnRef = componentScope.set.get(key);

    if (fnRef == null) {
      return null;
    }

    var fnNode = fnRef.defs[0];

    if (fnNode == null) {
      return null;
    } // const handleChange = function () {}
    // const handleChange = () => {}


    if (fnNode.type === 'Variable' && fnNode.node.type === 'VariableDeclarator' && fnNode.node.init != null && (fnNode.node.init.type === 'ArrowFunctionExpression' || fnNode.node.init.type === 'FunctionExpression')) {
      return fnRef;
    } // function handleChange() {}


    if (fnNode.type === 'FunctionName' && fnNode.node.type === 'FunctionDeclaration') {
      return fnRef;
    }

    return null;
  }).filter(Boolean);

  function isUsedOutsideOfHook(fnRef) {
    var foundWriteExpr = false;

    for (var i = 0; i < fnRef.references.length; i++) {
      var reference = fnRef.references[i];

      if (reference.writeExpr) {
        if (foundWriteExpr) {
          // Two writes to the same function.
          return true;
        } else {
          // Ignore first write as it's not usage.
          foundWriteExpr = true;
          continue;
        }
      }

      var currentScope = reference.from;

      while (currentScope !== scope && currentScope != null) {
        currentScope = currentScope.upper;
      }

      if (currentScope !== scope) {
        // This reference is outside the Hook callback.
        // It can only be legit if it's the deps array.
        if (!isAncestorNodeOf(declaredDependenciesNode, reference.identifier)) {
          return true;
        }
      }
    }

    return false;
  }

  return bareFunctions.map(function (fnRef) {
    return {
      fn: fnRef.defs[0],
      suggestUseCallback: isUsedOutsideOfHook(fnRef)
    };
  });
}
/**
 * Assuming () means the passed/returned node:
 * (props) => (props)
 * props.(foo) => (props.foo)
 * props.foo.(bar) => (props).foo.bar
 * props.foo.bar.(baz) => (props).foo.bar.baz
 */


function getDependency(node) {
  if (node.parent.type === 'MemberExpression' && node.parent.object === node && node.parent.property.name !== 'current' && !node.parent.computed && !(node.parent.parent != null && node.parent.parent.type === 'CallExpression' && node.parent.parent.callee === node.parent)) {
    return getDependency(node.parent);
  } else {
    return node;
  }
}
/**
 * Assuming () means the passed node.
 * (foo) -> 'foo'
 * foo.(bar) -> 'foo.bar'
 * foo.bar.(baz) -> 'foo.bar.baz'
 * Otherwise throw.
 */


function toPropertyAccessString(node) {
  if (node.type === 'Identifier') {
    return node.name;
  } else if (node.type === 'MemberExpression' && !node.computed) {
    var object = toPropertyAccessString(node.object);
    var property = toPropertyAccessString(node.property);
    return object + "." + property;
  } else {
    throw new Error("Unsupported node type: " + node.type);
  }
}

function getNodeWithoutReactNamespace(node, options) {
  if (node.type === 'MemberExpression' && node.object.type === 'Identifier' && node.object.name === 'React' && node.property.type === 'Identifier' && !node.computed) {
    return node.property;
  }

  return node;
} // What's the index of callback that needs to be analyzed for a given Hook?
// -1 if it's not a Hook we care about (e.g. useState).
// 0 for useEffect/useMemo/useCallback(fn).
// 1 for useImperativeHandle(ref, fn).
// For additionally configured Hooks, assume that they're like useEffect (0).


function getReactiveHookCallbackIndex(calleeNode, options) {
  var node = getNodeWithoutReactNamespace(calleeNode);

  if (node.type !== 'Identifier') {
    return null;
  }

  switch (node.name) {
    case 'useEffect':
    case 'useLayoutEffect':
    case 'useCallback':
    case 'useMemo':
      // useEffect(fn)
      return 0;

    case 'useImperativeHandle':
      // useImperativeHandle(ref, fn)
      return 1;

    default:
      if (node === calleeNode && options && options.additionalHooks) {
        // Allow the user to provide a regular expression which enables the lint to
        // target custom reactive hooks.
        var name;

        try {
          name = toPropertyAccessString(node);
        } catch (error) {
          if (/Unsupported node type/.test(error.message)) {
            return 0;
          } else {
            throw error;
          }
        }

        return options.additionalHooks.test(name) ? 0 : -1;
      } else {
        return -1;
      }

  }
}
/**
 * ESLint won't assign node.parent to references from context.getScope()
 *
 * So instead we search for the node from an ancestor assigning node.parent
 * as we go. This mutates the AST.
 *
 * This traversal is:
 * - optimized by only searching nodes with a range surrounding our target node
 * - agnostic to AST node types, it looks for `{ type: string, ... }`
 */


function fastFindReferenceWithParent(start, target) {
  var queue = [start];
  var item = null;

  while (queue.length) {
    item = queue.shift();

    if (isSameIdentifier(item, target)) {
      return item;
    }

    if (!isAncestorNodeOf(item, target)) {
      continue;
    }

    for (var _i4 = 0, _Object$entries = Object.entries(item); _i4 < _Object$entries.length; _i4++) {
      var _Object$entries$_i = _Object$entries[_i4],
          key = _Object$entries$_i[0],
          value = _Object$entries$_i[1];

      if (key === 'parent') {
        continue;
      }

      if (isNodeLike(value)) {
        value.parent = item;
        queue.push(value);
      } else if (Array.isArray(value)) {
        value.forEach(function (val) {
          if (isNodeLike(val)) {
            val.parent = item;
            queue.push(val);
          }
        });
      }
    }
  }

  return null;
}

function joinEnglish(arr) {
  var s = '';

  for (var i = 0; i < arr.length; i++) {
    s += arr[i];

    if (i === 0 && arr.length === 2) {
      s += ' and ';
    } else if (i === arr.length - 2 && arr.length > 2) {
      s += ', and ';
    } else if (i < arr.length - 1) {
      s += ', ';
    }
  }

  return s;
}

function isNodeLike(val) {
  return typeof val === 'object' && val !== null && !Array.isArray(val) && typeof val.type === 'string';
}

function isSameIdentifier(a, b) {
  return a.type === 'Identifier' && a.name === b.name && a.range[0] === b.range[0] && a.range[1] === b.range[1];
}

function isAncestorNodeOf(a, b) {
  return a.range[0] <= b.range[0] && a.range[1] >= b.range[1];
}

var configs = {
  recommended: {
    plugins: ['react-hooks'],
    rules: {
      'react-hooks/rules-of-hooks': 'error',
      'react-hooks/exhaustive-deps': 'warn'
    }
  }
};
var rules = {
  'rules-of-hooks': RuleOfHooks,
  'exhaustive-deps': ExhaustiveDeps
};

exports.configs = configs;
exports.rules = rules;
  })();
}