1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2025 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#include "tokenlist.h"
#include "astutils.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "keywords.h"
#include "library.h"
#include "path.h"
#include "platform.h"
#include "settings.h"
#include "standards.h"
#include "token.h"
#include <cctype>
#include <cstdint>
#include <exception>
#include <functional>
#include <iostream>
#include <utility>
#include <set>
#include <stack>
#include <unordered_set>
#include <simplecpp.h>
//#define N_ASSERT_LANG
#ifndef N_ASSERT_LANG
#include <cassert>
#define ASSERT_LANG(x) assert(x)
#else
#define ASSERT_LANG(x)
#endif
// How many compileExpression recursions are allowed?
// For practical code this could be endless. But in some special torture test
// there needs to be a limit.
static constexpr int AST_MAX_DEPTH = 150;
TokenList::TokenList(const Settings* settings)
: mTokensFrontBack(*this)
, mSettings(settings)
{
if (mSettings && (mSettings->enforcedLang != Standards::Language::None)) {
mLang = mSettings->enforcedLang;
}
}
TokenList::~TokenList()
{
deallocateTokens();
}
//---------------------------------------------------------------------------
const std::string& TokenList::getSourceFilePath() const
{
if (getFiles().empty()) {
static const std::string s_empty_string;
return s_empty_string;
}
return getFiles()[0];
}
//---------------------------------------------------------------------------
// Deallocate lists..
void TokenList::deallocateTokens()
{
deleteTokens(mTokensFrontBack.front);
mTokensFrontBack.front = nullptr;
mTokensFrontBack.back = nullptr;
mFiles.clear();
}
void TokenList::determineCppC()
{
// only try to determine if it wasn't enforced
if (mLang == Standards::Language::None) {
ASSERT_LANG(!getSourceFilePath().empty());
mLang = Path::identify(getSourceFilePath(), mSettings ? mSettings->cppHeaderProbe : false);
// TODO: cannot enable assert as this might occur for unknown extensions
//ASSERT_LANG(mLang != Standards::Language::None);
if (mLang == Standards::Language::None) {
// TODO: should default to C instead like we do for headers
// default to C++
mLang = Standards::Language::CPP;
}
}
}
int TokenList::appendFileIfNew(std::string fileName)
{
// Has this file been tokenized already?
for (int i = 0; i < mFiles.size(); ++i)
if (Path::sameFileName(mFiles[i], fileName))
return i;
// The "mFiles" vector remembers what files have been tokenized..
mFiles.push_back(std::move(fileName));
// Update mIsC and mIsCpp properties
if (mFiles.size() == 1) { // Update only useful if first file added to _files
determineCppC();
}
return mFiles.size() - 1;
}
void TokenList::clangSetOrigFiles()
{
mOrigFiles = mFiles;
}
void TokenList::deleteTokens(Token *tok)
{
while (tok) {
Token *next = tok->next();
delete tok;
tok = next;
}
}
//---------------------------------------------------------------------------
// add a token.
//---------------------------------------------------------------------------
void TokenList::addtoken(const std::string& str, const nonneg int lineno, const nonneg int column, const nonneg int fileno, bool split)
{
if (str.empty())
return;
// If token contains # characters, split it up
if (split) {
size_t begin = 0;
size_t end = 0;
while ((end = str.find("##", begin)) != std::string::npos) {
addtoken(str.substr(begin, end - begin), lineno, fileno, false);
addtoken("##", lineno, column, fileno, false);
begin = end+2;
}
if (begin != 0) {
addtoken(str.substr(begin), lineno, column, fileno, false);
return;
}
}
if (mTokensFrontBack.back) {
mTokensFrontBack.back->insertToken(str);
} else {
mTokensFrontBack.front = new Token(mTokensFrontBack);
mTokensFrontBack.back = mTokensFrontBack.front;
mTokensFrontBack.back->str(str);
}
mTokensFrontBack.back->linenr(lineno);
mTokensFrontBack.back->column(column);
mTokensFrontBack.back->fileIndex(fileno);
}
void TokenList::addtoken(const std::string& str, const Token *locationTok)
{
if (str.empty())
return;
if (mTokensFrontBack.back) {
mTokensFrontBack.back->insertToken(str);
} else {
mTokensFrontBack.front = new Token(mTokensFrontBack);
mTokensFrontBack.back = mTokensFrontBack.front;
mTokensFrontBack.back->str(str);
}
mTokensFrontBack.back->linenr(locationTok->linenr());
mTokensFrontBack.back->column(locationTok->column());
mTokensFrontBack.back->fileIndex(locationTok->fileIndex());
}
void TokenList::addtoken(const Token * tok, const nonneg int lineno, const nonneg int column, const nonneg int fileno)
{
if (tok == nullptr)
return;
if (mTokensFrontBack.back) {
mTokensFrontBack.back->insertToken(tok->str(), tok->originalName());
} else {
mTokensFrontBack.front = new Token(mTokensFrontBack);
mTokensFrontBack.back = mTokensFrontBack.front;
mTokensFrontBack.back->str(tok->str());
if (!tok->originalName().empty())
mTokensFrontBack.back->originalName(tok->originalName());
}
mTokensFrontBack.back->linenr(lineno);
mTokensFrontBack.back->column(column);
mTokensFrontBack.back->fileIndex(fileno);
mTokensFrontBack.back->flags(tok->flags());
}
void TokenList::addtoken(const Token *tok, const Token *locationTok)
{
if (tok == nullptr || locationTok == nullptr)
return;
if (mTokensFrontBack.back) {
mTokensFrontBack.back->insertToken(tok->str(), tok->originalName());
} else {
mTokensFrontBack.front = new Token(mTokensFrontBack);
mTokensFrontBack.back = mTokensFrontBack.front;
mTokensFrontBack.back->str(tok->str());
if (!tok->originalName().empty())
mTokensFrontBack.back->originalName(tok->originalName());
}
mTokensFrontBack.back->flags(tok->flags());
mTokensFrontBack.back->linenr(locationTok->linenr());
mTokensFrontBack.back->column(locationTok->column());
mTokensFrontBack.back->fileIndex(locationTok->fileIndex());
}
void TokenList::addtoken(const Token *tok)
{
if (tok == nullptr)
return;
if (mTokensFrontBack.back) {
mTokensFrontBack.back->insertToken(tok->str(), tok->originalName(), tok->getMacroName());
} else {
mTokensFrontBack.front = new Token(mTokensFrontBack);
mTokensFrontBack.back = mTokensFrontBack.front;
mTokensFrontBack.back->str(tok->str());
mTokensFrontBack.back->originalName(tok->originalName());
mTokensFrontBack.back->setMacroName(tok->getMacroName());
}
mTokensFrontBack.back->flags(tok->flags());
mTokensFrontBack.back->linenr(tok->linenr());
mTokensFrontBack.back->column(tok->column());
mTokensFrontBack.back->fileIndex(tok->fileIndex());
}
//---------------------------------------------------------------------------
// copyTokens - Copy and insert tokens
//---------------------------------------------------------------------------
Token *TokenList::copyTokens(Token *dest, const Token *first, const Token *last, bool one_line)
{
std::stack<Token *> links;
Token *tok2 = dest;
int linenr = dest->linenr();
const int commonFileIndex = dest->fileIndex();
for (const Token *tok = first; tok != last->next(); tok = tok->next()) {
tok2->insertToken(tok->str());
tok2 = tok2->next();
tok2->fileIndex(commonFileIndex);
tok2->linenr(linenr);
tok2->tokType(tok->tokType());
tok2->flags(tok->flags());
tok2->varId(tok->varId());
tok2->setTokenDebug(tok->getTokenDebug());
// Check for links and fix them up
if (Token::Match(tok2, "(|[|{"))
links.push(tok2);
else if (Token::Match(tok2, ")|]|}")) {
if (links.empty())
return tok2;
Token * link = links.top();
tok2->link(link);
link->link(tok2);
links.pop();
}
if (!one_line && tok->next())
linenr += tok->next()->linenr() - tok->linenr();
}
return tok2;
}
//---------------------------------------------------------------------------
// InsertTokens - Copy and insert tokens
//---------------------------------------------------------------------------
void TokenList::insertTokens(Token *dest, const Token *src, nonneg int n)
{
// TODO: put the linking in a helper?
std::stack<Token *> link;
while (n > 0) {
dest->insertToken(src->str(), src->originalName());
dest = dest->next();
// Set links
if (Token::Match(dest, "(|[|{"))
link.push(dest);
else if (!link.empty() && Token::Match(dest, ")|]|}")) {
Token::createMutualLinks(dest, link.top());
link.pop();
}
dest->fileIndex(src->fileIndex());
dest->linenr(src->linenr());
dest->column(src->column());
dest->varId(src->varId());
dest->tokType(src->tokType());
dest->flags(src->flags());
dest->setMacroName(src->getMacroName());
src = src->next();
--n;
}
}
//---------------------------------------------------------------------------
// Tokenize - tokenizes a given file.
//---------------------------------------------------------------------------
bool TokenList::createTokens(std::istream &code, const std::string& file0)
{
ASSERT_LANG(!file0.empty());
appendFileIfNew(file0);
return createTokensInternal(code, file0);
}
//---------------------------------------------------------------------------
bool TokenList::createTokens(std::istream &code, Standards::Language lang)
{
ASSERT_LANG(lang != Standards::Language::None);
if (mLang == Standards::Language::None) {
mLang = lang;
} else {
ASSERT_LANG(lang == mLang);
}
return createTokensInternal(code, "");
}
//---------------------------------------------------------------------------
bool TokenList::createTokensInternal(std::istream &code, const std::string& file0)
{
simplecpp::OutputList outputList;
simplecpp::TokenList tokens(code, mFiles, file0, &outputList);
createTokens(std::move(tokens));
return outputList.empty();
}
//---------------------------------------------------------------------------
// NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved)
void TokenList::createTokens(simplecpp::TokenList&& tokenList)
{
// TODO: what to do if the list has been filled already? clear mTokensFrontBack?
// tokenList.cfront() might be NULL if the file contained nothing to tokenize so we need to check the files instead
if (!tokenList.getFiles().empty()) {
// this is a copy
// TODO: this points to mFiles when called from createTokens(std::istream &, const std::string&)
mOrigFiles = mFiles = tokenList.getFiles();
}
else
mFiles.clear();
determineCppC();
for (const simplecpp::Token *tok = tokenList.cfront(); tok;) {
// TODO: move from TokenList
std::string str = tok->str();
// Float literal
if (str.size() > 1 && str[0] == '.' && std::isdigit(str[1]))
str = '0' + str;
if (mTokensFrontBack.back) {
mTokensFrontBack.back->insertToken(str);
} else {
mTokensFrontBack.front = new Token(mTokensFrontBack);
mTokensFrontBack.back = mTokensFrontBack.front;
mTokensFrontBack.back->str(str);
}
mTokensFrontBack.back->fileIndex(tok->location.fileIndex);
mTokensFrontBack.back->linenr(tok->location.line);
mTokensFrontBack.back->column(tok->location.col);
mTokensFrontBack.back->setMacroName(tok->macro);
tok = tok->next;
if (tok)
tokenList.deleteToken(tok->previous);
}
if (mSettings && mSettings->relativePaths) {
for (std::string & mFile : mFiles)
mFile = Path::getRelativePath(mFile, mSettings->basePaths);
}
Token::assignProgressValues(mTokensFrontBack.front);
}
//---------------------------------------------------------------------------
std::size_t TokenList::calculateHash() const
{
std::string hashData;
for (const Token* tok = front(); tok; tok = tok->next()) {
hashData += std::to_string(tok->flags());
hashData += std::to_string(tok->varId());
hashData += std::to_string(tok->tokType());
hashData += tok->str();
hashData += tok->originalName();
}
return (std::hash<std::string>{})(hashData);
}
//---------------------------------------------------------------------------
namespace {
struct AST_state {
std::stack<Token*> op;
int depth{};
int inArrayAssignment{};
bool cpp;
int assign{};
bool inCase{}; // true from case to :
bool inGeneric{};
bool stopAtColon{}; // help to properly parse ternary operators
const Token* functionCallEndPar{};
explicit AST_state(bool cpp) : cpp(cpp) {}
};
}
static Token* skipDecl(Token* tok, std::vector<Token*>* inner = nullptr)
{
auto isDecltypeFuncParam = [](const Token* tok) -> bool {
if (!Token::simpleMatch(tok, ")"))
return false;
tok = tok->next();
while (Token::Match(tok, "*|&|&&|const"))
tok = tok->next();
if (Token::simpleMatch(tok, "("))
tok = tok->link()->next();
return Token::Match(tok, "%name%| ,|)");
};
if (!Token::Match(tok->previous(), "( %name%"))
return tok;
Token *vartok = tok;
while (Token::Match(vartok, "%name%|*|&|::|<")) {
if (vartok->str() == "<") {
if (vartok->link())
vartok = vartok->link();
else
return tok;
} else if (Token::Match(vartok, "%var% [:=({]")) {
return vartok;
} else if (Token::Match(vartok, "decltype|typeof (") && !isDecltypeFuncParam(tok->linkAt(1))) {
if (inner)
inner->push_back(vartok->tokAt(2));
return vartok->linkAt(1)->next();
}
vartok = vartok->next();
}
return tok;
}
static bool iscast(const Token *tok, bool cpp)
{
if (!Token::Match(tok, "( ::| %name%"))
return false;
if (Token::simpleMatch(tok->link(), ") ( )"))
return false;
if (Token::Match(tok->link(), ") %assign%|,|..."))
return false;
if (tok->previous() && tok->previous()->isName() && tok->strAt(-1) != "return" &&
(!cpp || !Token::Match(tok->previous(), "delete|throw")))
return false;
if (Token::simpleMatch(tok->previous(), ">") && tok->linkAt(-1))
return false;
if (Token::Match(tok, "( (| typeof (") && Token::Match(tok->link(), ") %num%"))
return true;
if (Token::Match(tok->link(), ") }|)|]|;"))
return false;
if (Token::Match(tok->link(), ") ++|-- [;)]"))
return false;
if (Token::Match(tok->link(), ") %cop%") && !Token::Match(tok->link(), ") [&*+-~!]"))
return false;
if (Token::Match(tok->previous(), "= ( %name% ) {") && tok->next()->varId() == 0)
return true;
bool type = false;
for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) {
if (tok2->varId() != 0)
return false;
if (cpp && !type && tok2->str() == "new")
return false;
while (tok2->link() && Token::Match(tok2, "(|[|<"))
tok2 = tok2->link()->next();
if (tok2->str() == ")") {
if (Token::simpleMatch(tok2, ") (") && Token::simpleMatch(tok2->linkAt(1), ") ."))
return true;
if (Token::simpleMatch(tok2, ") {") && !type) {
const Token *tok3 = tok2->linkAt(1);
while (tok3 != tok2 && Token::Match(tok3, "[{}]"))
tok3 = tok3->previous();
return tok3->str() != ";";
}
const bool res = type || tok2->strAt(-1) == "*" || Token::simpleMatch(tok2, ") ~") ||
(Token::Match(tok2, ") %any%") &&
(!tok2->next()->isOp() || Token::Match(tok2->next(), "!|~|++|--")) &&
!Token::Match(tok2->next(), "[[]);,?:.]"));
return res;
}
if (Token::Match(tok2, "&|&& )"))
return true;
if (!Token::Match(tok2, "%name%|*|::"))
return false;
if (tok2->isStandardType() && (tok2->strAt(1) != "(" || Token::Match(tok2->next(), "( * *| )")))
type = true;
}
return false;
}
// int(1), int*(2), ..
static Token * findCppTypeInitPar(Token *tok)
{
if (!tok || !Token::Match(tok->previous(), "[,()] %name%"))
return nullptr;
bool istype = false;
while (Token::Match(tok, "%name%|::|<")) {
if (tok->str() == "<") {
tok = tok->link();
if (!tok)
return nullptr;
}
istype |= tok->isStandardType();
tok = tok->next();
}
if (!istype)
return nullptr;
if (!Token::Match(tok, "[*&]"))
return nullptr;
while (Token::Match(tok, "[*&]"))
tok = tok->next();
return (tok && tok->str() == "(") ? tok : nullptr;
}
// X{} X<Y>{} etc
static bool iscpp11init_impl(const Token * tok);
static bool iscpp11init(const Token * const tok)
{
if (tok->isCpp11init() == TokenImpl::Cpp11init::UNKNOWN)
tok->setCpp11init(iscpp11init_impl(tok));
return tok->isCpp11init() == TokenImpl::Cpp11init::CPP11INIT;
}
static bool iscpp11init_impl(const Token * const tok)
{
if (Token::simpleMatch(tok, "{") && Token::simpleMatch(tok->link()->previous(), "; }"))
return false;
const Token *nameToken = tok;
while (nameToken && nameToken->str() == "{") {
if (nameToken->isCpp11init() != TokenImpl::Cpp11init::UNKNOWN)
return nameToken->isCpp11init() == TokenImpl::Cpp11init::CPP11INIT;
nameToken = nameToken->previous();
if (nameToken && nameToken->str() == "," && Token::simpleMatch(nameToken->previous(), "} ,"))
nameToken = nameToken->linkAt(-1);
}
if (!nameToken)
return false;
if (nameToken->str() == ")" && Token::simpleMatch(nameToken->link()->previous(), "decltype (") &&
!Token::simpleMatch(nameToken->link()->tokAt(-2), "."))
nameToken = nameToken->link()->previous();
if (Token::simpleMatch(nameToken, ", {"))
return true;
if (nameToken->str() == ">" && nameToken->link())
nameToken = nameToken->link()->previous();
if (Token::Match(nameToken, "]|*")) {
const Token* newTok = nameToken->link() ? nameToken->link()->previous() : nameToken->previous();
while (Token::Match(newTok, "%type%|::|*") && !newTok->isKeyword())
newTok = newTok->previous();
if (Token::simpleMatch(newTok, "new"))
return true;
}
auto isCaseStmt = [](const Token* colonTok) {
if (!Token::Match(colonTok->tokAt(-1), "%name%|%num%|%char%|) :"))
return false;
if (const Token* castTok = colonTok->linkAt(-1)) {
if (Token::simpleMatch(castTok->astParent(), "case"))
return true;
}
const Token* caseTok = colonTok->tokAt(-2);
while (caseTok && Token::Match(caseTok->tokAt(-1), "::|%name%"))
caseTok = caseTok->tokAt(-1);
return Token::simpleMatch(caseTok, "case");
};
const Token *endtok = nullptr;
if (Token::Match(nameToken, "%name%|return|: {") && !isCaseStmt(nameToken) &&
(!Token::simpleMatch(nameToken->tokAt(2), "[") || findLambdaEndScope(nameToken->tokAt(2))))
endtok = nameToken->linkAt(1);
else if (Token::Match(nameToken,"%name% <") && Token::simpleMatch(nameToken->linkAt(1),"> {"))
endtok = nameToken->linkAt(1)->linkAt(1);
else if (Token::Match(nameToken->previous(), "%name%|> ( {"))
endtok = nameToken->linkAt(1);
else if (Token::simpleMatch(nameToken, "decltype") && nameToken->linkAt(1))
endtok = nameToken->linkAt(1)->linkAt(1);
else
return false;
if (Token::Match(nameToken, "else|try|do|const|constexpr|override|volatile|&|&&"))
return false;
if (Token::simpleMatch(nameToken->previous(), ". void {") && nameToken->previous()->originalName() == "->")
return false; // trailing return type. The only function body that can contain no semicolon is a void function.
if (Token::simpleMatch(nameToken->previous(), "namespace") || Token::simpleMatch(nameToken, "namespace") /*anonymous namespace*/)
return false;
if (precedes(nameToken->next(), endtok) && !Token::Match(nameToken, "return|:")) {
// If there is semicolon between {..} this is not a initlist
for (const Token *tok2 = nameToken->next(); tok2 != endtok; tok2 = tok2->next()) {
if (tok2->str() == ";")
return false;
const Token * lambdaEnd = findLambdaEndScope(tok2);
if (lambdaEnd)
tok2 = lambdaEnd;
}
}
// There is no initialisation for example here: 'class Fred {};'
if (!Token::simpleMatch(endtok, "} ;"))
return true;
const Token *prev = nameToken;
while (Token::Match(prev, "%name%|::|:|<|>|(|)|,|%num%|%cop%|...")) {
if (Token::Match(prev, "class|struct|union|enum"))
return false;
prev = prev->previous();
}
return true;
}
static bool isQualifier(const Token* tok)
{
while (Token::Match(tok, "&|&&|*"))
tok = tok->next();
return Token::Match(tok, "{|;");
}
static void compileUnaryOp(Token *&tok, AST_state& state, void (*f)(Token *&tok, AST_state& state))
{
Token *unaryop = tok;
if (f) {
tok = tok->next();
state.depth++;
if (state.depth > AST_MAX_DEPTH)
throw InternalError(tok, "maximum AST depth exceeded", InternalError::AST);
if (tok)
f(tok, state);
state.depth--;
}
if (!state.op.empty() && (!precedes(state.op.top(), unaryop) || unaryop->isIncDecOp() || Token::Match(unaryop, "[({[]"))) { // nullary functions, empty lists/arrays
unaryop->astOperand1(state.op.top());
state.op.pop();
}
state.op.push(unaryop);
}
static void skipGenericType(Token *&tok)
{
Token *skip = tok;
while (Token::Match(skip, "%name%|*|:|(")) {
if (skip->link()) {
skip = skip->link()->next();
continue;
}
if (Token::simpleMatch(skip, ":")) {
tok = skip->next();
return;
}
skip = skip->next();
}
}
static void compileBinOp(Token *&tok, AST_state& state, void (*f)(Token *&tok, AST_state& state))
{
Token *binop = tok;
if (f) {
tok = tok->next();
if (Token::simpleMatch(binop, ",") && state.inGeneric)
skipGenericType(tok);
const bool inGenericSaved = state.inGeneric;
state.inGeneric = false;
if (Token::Match(binop, "::|. ~"))
tok = tok->next();
state.depth++;
if (tok && state.depth <= AST_MAX_DEPTH)
f(tok, state);
if (state.depth > AST_MAX_DEPTH)
throw InternalError(tok, "maximum AST depth exceeded", InternalError::AST);
state.depth--;
state.inGeneric = inGenericSaved;
}
// TODO: Should we check if op is empty.
// * Is it better to add assertion that it isn't?
// * Write debug warning if it's empty?
if (!state.op.empty()) {
binop->astOperand2(state.op.top());
state.op.pop();
}
if (!state.op.empty()) {
binop->astOperand1(state.op.top());
state.op.pop();
}
state.op.push(binop);
}
static void compileExpression(Token *&tok, AST_state& state);
static void compileTerm(Token *&tok, AST_state& state)
{
if (!tok)
return;
if (Token::Match(tok, "L %str%|%char%"))
tok = tok->next();
if (state.inArrayAssignment && Token::Match(tok->previous(), "[{,] . %name%")) { // Jump over . in C style struct initialization
state.op.push(tok);
tok->astOperand1(tok->next());
tok = tok->tokAt(2);
}
if (state.inArrayAssignment && Token::Match(tok->previous(), "[{,] [ %num%|%name% ]")) {
state.op.push(tok);
tok->astOperand1(tok->next());
tok = tok->tokAt(3);
}
if (tok->isLiteral()) {
state.op.push(tok);
do {
tok = tok->next();
} while (Token::Match(tok, "%name%|%str%"));
} else if (tok->isName()) {
if (Token::Match(tok, "return|case") || (state.cpp && (tok->str() == "throw"))) {
if (tok->str() == "case")
state.inCase = true;
const bool tokIsReturn = tok->str() == "return";
const bool stopAtColon = state.stopAtColon;
state.stopAtColon=true;
compileUnaryOp(tok, state, compileExpression);
state.stopAtColon=stopAtColon;
if (tokIsReturn)
state.op.pop();
if (state.inCase && Token::simpleMatch(tok, ": ;")) {
state.inCase = false;
tok = tok->next();
}
} else if (Token::Match(tok, "sizeof !!(")) {
compileUnaryOp(tok, state, compileExpression);
state.op.pop();
} else if (state.cpp && findCppTypeInitPar(tok)) { // int(0), int*(123), ..
tok = findCppTypeInitPar(tok);
state.op.push(tok);
tok = tok->tokAt(2);
} else if (state.cpp && iscpp11init(tok)) { // X{} X<Y>{} etc
state.op.push(tok);
tok = tok->next();
if (tok->str() == "<")
tok = tok->link()->next();
if (Token::Match(tok, "{ . %name% =|{")) {
const Token* end = tok->link();
const int inArrayAssignment = state.inArrayAssignment;
state.inArrayAssignment = 1;
compileBinOp(tok, state, compileExpression);
state.inArrayAssignment = inArrayAssignment;
if (tok == end)
tok = tok->next();
else
throw InternalError(tok, "Syntax error. Unexpected tokens in designated initializer.", InternalError::AST);
}
} else if (!state.cpp || !Token::Match(tok, "new|delete %name%|*|&|::|(|[")) {
std::vector<Token*> inner;
tok = skipDecl(tok, &inner);
for (Token* tok3 : inner) {
AST_state state1(state.cpp);
compileExpression(tok3, state1);
}
bool repeat = true;
while (repeat) {
repeat = false;
if (Token::Match(tok->next(), "%name%")) {
tok = tok->next();
repeat = true;
}
if (Token::simpleMatch(tok->next(), "<") && Token::Match(tok->linkAt(1), "> %name%")) {
tok = tok->linkAt(1)->next();
repeat = true;
}
}
state.op.push(tok);
if (Token::Match(tok, "%name% <") && tok->linkAt(1))
tok = tok->linkAt(1);
else if (Token::Match(tok, "%name% ...") || (state.op.size() == 1 && state.depth == 0 && Token::Match(tok->tokAt(-3), "!!& ) ( %name% ) =")))
tok = tok->next();
tok = tok->next();
if (Token::Match(tok, "%str%")) {
while (Token::Match(tok, "%name%|%str%"))
tok = tok->next();
}
if (Token::Match(tok, "%name% %assign%"))
tok = tok->next();
}
} else if (tok->str() == "{") {
const Token *prev = tok->previous();
if (Token::simpleMatch(prev, ") {") && iscast(prev->link(), state.cpp))
prev = prev->link()->previous();
if (Token::simpleMatch(tok->link(),"} [")) {
tok = tok->next();
} else if ((state.cpp && iscpp11init(tok)) || Token::simpleMatch(tok->previous(), "] {")) {
Token *const end = tok->link();
if (state.op.empty() || Token::Match(tok->previous(), "[{,]") || Token::Match(tok->tokAt(-2), "%name% (")) {
if (Token::Match(tok->tokAt(-1), "!!, { . %name% =|{")) {
const int inArrayAssignment = state.inArrayAssignment;
state.inArrayAssignment = 1;
compileBinOp(tok, state, compileExpression);
state.inArrayAssignment = inArrayAssignment;
} else if (Token::simpleMatch(tok, "{ }")) {
state.op.push(tok);
tok = tok->next();
} else {
compileUnaryOp(tok, state, compileExpression);
if (precedes(tok,end)) // typically for something like `MACRO(x, { if (c) { ... } })`, where end is the last curly, and tok is the open curly for the if
tok = end;
}
} else
compileBinOp(tok, state, compileExpression);
if (tok != end)
throw InternalError(tok, "Syntax error. Unexpected tokens in initializer.", InternalError::AST);
if (tok->next())
tok = tok->next();
} else if (state.cpp && Token::Match(tok->tokAt(-2), "%name% ( {") && !Token::findsimplematch(tok, ";", tok->link())) {
if (Token::simpleMatch(tok, "{ }"))
tok = tok->tokAt(2);
else {
Token *tok1 = tok;
state.inArrayAssignment++;
compileUnaryOp(tok, state, compileExpression);
state.inArrayAssignment--;
tok = tok1->link()->next();
}
} else if (!state.inArrayAssignment && !Token::simpleMatch(prev, "=")) {
state.op.push(tok);
tok = tok->link()->next();
} else {
if (tok->link() != tok->next()) {
state.inArrayAssignment++;
compileUnaryOp(tok, state, compileExpression);
if (Token::Match(tok, "} [,};]") && state.inArrayAssignment > 0) {
tok = tok->next();
state.inArrayAssignment--;
}
} else {
state.op.push(tok);
tok = tok->tokAt(2);
}
}
}
}
static void compileScope(Token *&tok, AST_state& state)
{
compileTerm(tok, state);
while (tok) {
if (tok->str() == "::") {
const Token *lastOp = state.op.empty() ? nullptr : state.op.top();
if (Token::Match(lastOp, ":: %name%"))
lastOp = lastOp->next();
if (Token::Match(lastOp, "%name%") &&
(lastOp->next() == tok || (Token::Match(lastOp, "%name% <") && lastOp->linkAt(1) && tok == lastOp->linkAt(1)->next())))
compileBinOp(tok, state, compileTerm);
else
compileUnaryOp(tok, state, compileTerm);
} else break;
}
}
static bool isPrefixUnary(const Token* tok, bool cpp)
{
if (cpp && Token::simpleMatch(tok->previous(), "* [") && Token::simpleMatch(tok->link(), "] {")) {
for (const Token* prev = tok->previous(); Token::Match(prev, "%name%|::|*|&|>|>>"); prev = prev->previous()) {
if (Token::Match(prev, ">|>>")) {
if (!prev->link())
break;
prev = prev->link();
}
if (prev->str() == "new")
return false;
}
}
if (!tok->previous()
|| ((Token::Match(tok->previous(), "(|[|{|%op%|;|?|:|,|.|case|return|::") || (cpp && tok->strAt(-1) == "throw"))
&& (tok->previous()->tokType() != Token::eIncDecOp || tok->tokType() == Token::eIncDecOp)))
return true;
if (tok->strAt(-1) == "}") {
const Token* parent = tok->linkAt(-1)->tokAt(-1);
return !Token::Match(parent, "%type%") || parent->isKeyword();
}
if (tok->str() == "*" && tok->previous()->tokType() == Token::eIncDecOp && isPrefixUnary(tok->previous(), cpp))
return true;
return tok->strAt(-1) == ")" && iscast(tok->linkAt(-1), cpp);
}
static void compilePrecedence2(Token *&tok, AST_state& state)
{
auto doCompileScope = [&](const Token* tok) -> bool {
const bool isStartOfCpp11Init = state.cpp && tok && tok->str() == "{" && iscpp11init(tok);
if (isStartOfCpp11Init || Token::simpleMatch(tok, "(")) {
tok = tok->previous();
while (Token::simpleMatch(tok, "*"))
tok = tok->previous();
while (tok && Token::Match(tok->previous(), ":: %type%"))
tok = tok->tokAt(-2);
if (tok && !tok->isKeyword())
tok = tok->previous();
return !Token::Match(tok, "new ::| %type%");
}
return !findLambdaEndTokenWithoutAST(tok);
};
bool isNew = true;
if (doCompileScope(tok)) {
compileScope(tok, state);
isNew = false;
}
while (tok) {
if (tok->tokType() == Token::eIncDecOp && !isPrefixUnary(tok, state.cpp)) {
compileUnaryOp(tok, state, compileScope);
} else if (tok->str() == "...") {
if (!Token::simpleMatch(tok->previous(), ")"))
state.op.push(tok);
tok = tok->next();
break;
} else if (tok->str() == "." && tok->strAt(1) != "*") {
if (tok->strAt(1) == ".") {
state.op.push(tok);
tok = tok->tokAt(3);
break;
}
if (!Token::Match(tok->tokAt(-1), "[{,]"))
compileBinOp(tok, state, compileScope);
else
compileUnaryOp(tok, state, compileScope);
} else if (tok->str() == "[") {
if (state.cpp && isPrefixUnary(tok, /*cpp*/ true) && Token::Match(tok->link(), "] (|{|<")) { // Lambda
// What we do here:
// - Nest the round bracket under the square bracket.
// - Nest what follows the lambda (if anything) with the lambda opening [
// - Compile the content of the lambda function as separate tree (this is done later)
// this must be consistent with isLambdaCaptureList
Token* const squareBracket = tok;
// Parse arguments in the capture list
if (tok->strAt(1) != "]") {
Token* tok2 = tok->next();
AST_state state2(state.cpp);
compileExpression(tok2, state2);
if (!state2.op.empty()) {
squareBracket->astOperand2(state2.op.top());
}
}
const bool hasTemplateArg = Token::simpleMatch(squareBracket->link(), "] <") &&
Token::simpleMatch(squareBracket->link()->linkAt(1), "> (");
if (Token::simpleMatch(squareBracket->link(), "] (") || hasTemplateArg) {
Token* const roundBracket = hasTemplateArg ? squareBracket->link()->linkAt(1)->next() : squareBracket->link()->next();
Token* curlyBracket = roundBracket->link()->next();
while (Token::Match(curlyBracket, "mutable|const|constexpr|consteval"))
curlyBracket = curlyBracket->next();
if (Token::simpleMatch(curlyBracket, "noexcept")) {
if (Token::simpleMatch(curlyBracket->next(), "(")) {
AST_state state2(state.cpp);
Token *tok2 = curlyBracket->tokAt(2);
compileExpression(tok2, state2);
curlyBracket = curlyBracket->linkAt(1)->next();
} else
curlyBracket = curlyBracket->next();
}
if (curlyBracket && curlyBracket->originalName() == "->") {
if (Token::simpleMatch(curlyBracket->next(), "decltype (")) {
AST_state state2(state.cpp);
Token *tok2 = curlyBracket->tokAt(3);
compileExpression(tok2, state2);
}
curlyBracket = findTypeEnd(curlyBracket->next());
}
if (curlyBracket && curlyBracket->str() == "{") {
squareBracket->astOperand1(roundBracket);
roundBracket->astOperand1(curlyBracket);
state.op.push(squareBracket);
tok = curlyBracket->link()->next();
continue;
}
} else {
Token* const curlyBracket = squareBracket->link()->next();
squareBracket->astOperand1(curlyBracket);
state.op.push(squareBracket);
tok = curlyBracket->link() ? curlyBracket->link()->next() : nullptr;
continue;
}
}
Token* const tok2 = tok;
if (tok->strAt(1) != "]") {
compileBinOp(tok, state, compileExpression);
if (Token::Match(tok2->previous(), "%type%|* [") && Token::Match(tok, "] { !!}")) {
tok = tok->next();
Token* const tok3 = tok;
compileBinOp(tok, state, compileExpression);
if (tok != tok3->link())
throw InternalError(tok, "Syntax error in {..}", InternalError::AST);
tok = tok->next();
continue;
}
}
else
compileUnaryOp(tok, state, compileExpression);
tok = tok2->link()->next();
} else if (Token::simpleMatch(tok->previous(), "requires {")) {
state.op.push(tok);
tok = tok->link()->next();
continue;
} else if (Token::simpleMatch(tok, "( {") && Token::simpleMatch(tok->linkAt(1)->previous(), "; } )") &&
!Token::Match(tok->previous(), "%name% (")) {
state.op.push(tok->next());
tok = tok->link()->next();
continue;
} else if (tok->str() == "(" &&
(!iscast(tok, state.cpp) || Token::Match(tok->previous(), "if|while|for|switch|catch"))) {
const bool inGenericSaved = state.inGeneric;
if (Token::simpleMatch(tok->previous(), "_Generic"))
state.inGeneric = true;
Token* tok2 = tok;
tok = tok->next();
const bool opPrevTopSquare = !state.op.empty() && state.op.top() && state.op.top()->str() == "[";
const std::size_t oldOpSize = state.op.size();
compileExpression(tok, state);
tok = tok2;
if ((oldOpSize > 0 && (isNew || Token::simpleMatch(tok->previous(), "} (")))
|| (tok->previous() && tok->previous()->isName() && !Token::Match(tok->previous(), "return|case") && (!state.cpp || !Token::Match(tok->previous(), "throw|delete")))
|| (tok->strAt(-1) == "]" && (!state.cpp || !Token::Match(tok->linkAt(-1)->previous(), "new|delete")))
|| (tok->strAt(-1) == ">" && tok->linkAt(-1))
|| (tok->strAt(-1) == ")" && !iscast(tok->linkAt(-1), state.cpp)) // Don't treat brackets to clarify precedence as function calls
|| (tok->strAt(-1) == "}" && opPrevTopSquare)) {
const bool operandInside = oldOpSize < state.op.size();
if (operandInside)
compileBinOp(tok, state, nullptr);
else
compileUnaryOp(tok, state, nullptr);
}
state.inGeneric = inGenericSaved;
tok = tok->link()->next();
if (Token::simpleMatch(tok, "::"))
compileBinOp(tok, state, compileTerm);
} else if (iscast(tok, state.cpp) && Token::simpleMatch(tok->link(), ") {") &&
Token::simpleMatch(tok->link()->linkAt(1), "} [")) {
Token *cast = tok;
tok = tok->link()->next();
Token *tok1 = tok;
compileUnaryOp(tok, state, compileExpression);
cast->astOperand1(tok1);
tok = tok1->link()->next();
} else if (state.cpp && tok->str() == "{" && iscpp11init(tok)) {
Token* end = tok->link();
if (Token::simpleMatch(tok, "{ }"))
{
compileUnaryOp(tok, state, nullptr);
tok = tok->next();
}
else
{
compileBinOp(tok, state, compileExpression);
}
if (tok == end)
tok = end->next();
else
throw InternalError(tok, "Syntax error. Unexpected tokens in initializer.", InternalError::AST);
} else
break;
}
}
static void compilePrecedence3(Token *&tok, AST_state& state)
{
compilePrecedence2(tok, state);
while (tok) {
if ((Token::Match(tok, "[+-!~*&]") || tok->tokType() == Token::eIncDecOp) &&
isPrefixUnary(tok, state.cpp)) {
if (Token::Match(tok, "* [*,)]")) {
Token* tok2 = tok->next();
while (tok2->next() && tok2->str() == "*")
tok2 = tok2->next();
if (Token::Match(tok2, "[>),]")) {
tok = tok2;
continue;
}
}
compileUnaryOp(tok, state, compilePrecedence3);
} else if (tok->str() == "(" && iscast(tok, state.cpp)) {
Token* castTok = tok;
castTok->isCast(true);
tok = tok->link()->next();
const int inArrayAssignment = state.inArrayAssignment;
if (tok && tok->str() == "{")
state.inArrayAssignment = 1;
compilePrecedence3(tok, state);
state.inArrayAssignment = inArrayAssignment;
compileUnaryOp(castTok, state, nullptr);
} else if (state.cpp && Token::Match(tok, "new %name%|::|(")) {
Token* newtok = tok;
tok = tok->next();
bool innertype = false;
if (tok->str() == "(") {
if (Token::Match(tok, "( &| %name%") && Token::Match(tok->link(), ") ( %type%") && Token::simpleMatch(tok->link()->linkAt(1), ") ("))
tok = tok->link()->next();
if (Token::Match(tok->link(), ") ::| %type%")) {
if (Token::Match(tok, "( !!)")) {
Token *innerTok = tok->next();
AST_state innerState(true);
compileExpression(innerTok, innerState);
}
tok = tok->link()->next();
} else if (Token::Match(tok, "( %type%") && Token::Match(tok->link(), ") [();,[]")) {
tok = tok->next();
innertype = true;
} else if (Token::Match(tok, "( &| %name%") && Token::simpleMatch(tok->link(), ") (")) {
tok = tok->next();
innertype = true;
} else {
/* bad code */
continue;
}
}
Token* leftToken = tok;
if (Token::simpleMatch(tok, "::")) {
tok->astOperand1(tok->next());
tok = tok->next();
}
else {
while (Token::Match(tok->next(), ":: %name%")) {
Token* scopeToken = tok->next(); //The ::
scopeToken->astOperand1(leftToken);
scopeToken->astOperand2(scopeToken->next());
leftToken = scopeToken;
tok = scopeToken->next();
}
}
state.op.push(tok);
while (Token::Match(tok, "%name%|*|&|<|::")) {
if (tok->link())
tok = tok->link();
tok = tok->next();
}
if (Token::Match(tok, "( const| %type% ) (")) {
state.op.push(tok->next());
tok = tok->link()->next();
compileBinOp(tok, state, compilePrecedence2);
} else if (Token::Match(tok, "(|{|["))
compilePrecedence2(tok, state);
else if (innertype && Token::simpleMatch(tok, ") [")) {
tok = tok->next();
compilePrecedence2(tok, state);
}
compileUnaryOp(newtok, state, nullptr);
if (Token::simpleMatch(newtok->previous(), ":: new")) {
newtok->previous()->astOperand1(newtok);
state.op.pop();
}
if (innertype && Token::simpleMatch(tok, ") ,"))
tok = tok->next();
} else if (state.cpp && Token::Match(tok, "delete %name%|*|&|::|(|[")) {
Token* tok2 = tok;
tok = tok->next();
if (tok && tok->str() == "[")
tok = tok->link()->next();
compilePrecedence3(tok, state);
compileUnaryOp(tok2, state, nullptr);
if (Token::simpleMatch(tok2->previous(), ":: delete")) {
tok2->previous()->astOperand1(tok2);
state.op.pop();
}
}
// TODO: Handle sizeof
else break;
}
}
static void compilePointerToElem(Token *&tok, AST_state& state)
{
compilePrecedence3(tok, state);
while (tok) {
if (Token::simpleMatch(tok, ". *")) {
compileBinOp(tok, state, compilePrecedence3);
} else break;
}
}
static void compileMulDiv(Token *&tok, AST_state& state)
{
compilePointerToElem(tok, state);
while (tok) {
if (Token::Match(tok, "[/%]") || (tok->str() == "*" && !tok->astOperand1() && !isQualifier(tok))) {
if (Token::Match(tok, "* [*,)]")) {
Token* tok2 = tok->next();
while (tok2->next() && tok2->str() == "*")
tok2 = tok2->next();
if (Token::Match(tok2, "[>),]")) {
tok = tok2;
break;
}
}
compileBinOp(tok, state, compilePointerToElem);
} else break;
}
}
static void compileAddSub(Token *&tok, AST_state& state)
{
compileMulDiv(tok, state);
while (tok) {
if (Token::Match(tok, "+|-") && !tok->astOperand1()) {
compileBinOp(tok, state, compileMulDiv);
} else break;
}
}
static void compileShift(Token *&tok, AST_state& state)
{
compileAddSub(tok, state);
while (tok) {
if (Token::Match(tok, "<<|>>")) {
compileBinOp(tok, state, compileAddSub);
} else break;
}
}
static void compileThreewayComp(Token *&tok, AST_state& state)
{
compileShift(tok, state);
while (tok) {
if (tok->str() == "<=>") {
compileBinOp(tok, state, compileShift);
} else break;
}
}
static void compileRelComp(Token *&tok, AST_state& state)
{
compileThreewayComp(tok, state);
while (tok) {
if (Token::Match(tok, "<|<=|>=|>") && !tok->link()) {
compileBinOp(tok, state, compileThreewayComp);
} else break;
}
}
static void compileEqComp(Token *&tok, AST_state& state)
{
compileRelComp(tok, state);
while (tok) {
if (Token::Match(tok, "==|!=")) {
compileBinOp(tok, state, compileRelComp);
} else break;
}
}
static void compileAnd(Token *&tok, AST_state& state)
{
compileEqComp(tok, state);
while (tok) {
if (tok->str() == "&" && !tok->astOperand1() && !isQualifier(tok)) {
Token* tok2 = tok->next();
if (!tok2)
break;
if (tok2->str() == "&")
tok2 = tok2->next();
if (state.cpp && Token::Match(tok2, ",|)")) {
tok = tok2;
break; // rValue reference
}
compileBinOp(tok, state, compileEqComp);
} else break;
}
}
static void compileXor(Token *&tok, AST_state& state)
{
compileAnd(tok, state);
while (tok) {
if (tok->str() == "^") {
compileBinOp(tok, state, compileAnd);
} else break;
}
}
static void compileOr(Token *&tok, AST_state& state)
{
compileXor(tok, state);
while (tok) {
if (tok->str() == "|") {
compileBinOp(tok, state, compileXor);
} else break;
}
}
static void compileLogicAnd(Token *&tok, AST_state& state)
{
compileOr(tok, state);
while (tok) {
if (tok->str() == "&&" && !isQualifier(tok)) {
if (!tok->astOperand1()) {
Token* tok2 = tok->next();
if (!tok2)
break;
if (state.cpp && Token::Match(tok2, ",|)")) {
tok = tok2;
break; // rValue reference
}
}
compileBinOp(tok, state, compileOr);
} else break;
}
}
static void compileLogicOr(Token *&tok, AST_state& state)
{
compileLogicAnd(tok, state);
while (tok) {
if (tok->str() == "||") {
compileBinOp(tok, state, compileLogicAnd);
} else break;
}
}
static void compileAssignTernary(Token *&tok, AST_state& state)
{
compileLogicOr(tok, state);
while (tok) {
if (tok->isAssignmentOp()) {
state.assign++;
const Token *tok1 = tok->next();
compileBinOp(tok, state, compileAssignTernary);
if (Token::simpleMatch(tok1, "{") && tok == tok1->link() && tok->next())
tok = tok->next();
if (state.assign > 0)
state.assign--;
} else if (tok->str() == "?") {
// http://en.cppreference.com/w/cpp/language/operator_precedence says about ternary operator:
// "The expression in the middle of the conditional operator (between ? and :) is parsed as if parenthesized: its precedence relative to ?: is ignored."
// Hence, we rely on Tokenizer::prepareTernaryOpForAST() to add such parentheses where necessary.
const bool stopAtColon = state.stopAtColon;
state.stopAtColon = false;
if (tok->strAt(1) == ":") {
state.op.push(nullptr);
}
const int assign = state.assign;
state.assign = 0;
compileBinOp(tok, state, compileAssignTernary);
state.assign = assign;
state.stopAtColon = stopAtColon;
} else if (tok->str() == ":") {
if (state.depth == 1U && state.inCase) {
state.inCase = false;
tok = tok->next();
break;
}
if (state.stopAtColon)
break;
if (state.assign > 0)
break;
compileBinOp(tok, state, compileAssignTernary);
} else break;
}
}
static void compileComma(Token *&tok, AST_state& state)
{
compileAssignTernary(tok, state);
while (tok) {
if (tok->str() == ",") {
if (Token::simpleMatch(tok, ", }"))
tok = tok->next();
else
compileBinOp(tok, state, compileAssignTernary);
} else if (tok->str() == ";" && state.functionCallEndPar && tok->index() < state.functionCallEndPar->index()) {
compileBinOp(tok, state, compileAssignTernary);
} else break;
}
}
static void compileExpression(Token *&tok, AST_state& state)
{
if (state.depth > AST_MAX_DEPTH)
throw InternalError(tok, "maximum AST depth exceeded", InternalError::AST); // ticket #5592
if (tok)
compileComma(tok, state);
}
const Token* isLambdaCaptureList(const Token * tok)
{
// a lambda expression '[x](y){}' is compiled as:
// [
// `-( <<-- optional
// `-{
// see compilePrecedence2
if (!Token::simpleMatch(tok, "["))
return nullptr;
if (!Token::Match(tok->link(), "] (|{"))
return nullptr;
if (Token::simpleMatch(tok->astOperand1(), "{") && tok->astOperand1() == tok->link()->next())
return tok->astOperand1();
if (!tok->astOperand1() || tok->astOperand1()->str() != "(")
return nullptr;
const Token * params = tok->astOperand1();
if (!Token::simpleMatch(params->astOperand1(), "{"))
return nullptr;
return params->astOperand1();
}
const Token* findLambdaEndTokenWithoutAST(const Token* tok) {
if (!(Token::simpleMatch(tok, "[") && tok->link()))
return nullptr;
tok = tok->link()->next();
if (Token::simpleMatch(tok, "(") && tok->link())
tok = tok->link()->next();
if (Token::simpleMatch(tok, "mutable"))
tok = tok->next();
if (Token::Match(tok, ".|->")) { // trailing return type
tok = tok->next();
while (Token::Match(tok, "%type%|%name%|::|&|&&|*|<|(")) {
if (tok->link())
tok = tok->link()->next();
else
tok = tok->next();
}
}
if (!(Token::simpleMatch(tok, "{") && tok->link()))
return nullptr;
return tok->link()->next();
}
static Token * createAstAtToken(Token *tok);
// Compile inner expressions inside inner ({..}) and lambda bodies
static void createAstAtTokenInner(Token * const tok1, const Token *endToken, bool cpp)
{
for (Token* tok = tok1; precedes(tok, endToken); tok = tok ? tok->next() : nullptr) {
if (tok->str() == "{" && !iscpp11init(tok)) {
const Token * const endToken2 = tok->link();
bool hasAst = false;
for (const Token *inner = tok->next(); inner != endToken2; inner = inner->next()) {
if (inner->astOperand1()) {
hasAst = true;
break;
}
if (tok->isConstOp())
break;
if (inner->str() == "{")
inner = inner->link();
}
if (!hasAst) {
for (; tok && tok != endToken && tok != endToken2; tok = tok ? tok->next() : nullptr)
tok = createAstAtToken(tok);
}
} else if (cpp && tok->str() == "[") {
if (isLambdaCaptureList(tok)) {
tok = tok->astOperand1();
if (tok->str() == "(")
tok = tok->astOperand1();
const Token * const endToken2 = tok->link();
tok = tok->next();
for (; tok && tok != endToken && tok != endToken2; tok = tok ? tok->next() : nullptr)
tok = createAstAtToken(tok);
}
}
else if (Token::simpleMatch(tok, "( * ) [")) {
bool hasAst = false;
for (const Token* tok2 = tok->linkAt(3); tok2 != tok; tok2 = tok2->previous()) {
if (tok2->astParent() || tok2->astOperand1() || tok2->astOperand2()) {
hasAst = true;
break;
}
}
if (!hasAst) {
Token *const startTok = tok = tok->tokAt(4);
const Token* const endtok = startTok->linkAt(-1);
AST_state state(cpp);
compileExpression(tok, state);
createAstAtTokenInner(startTok, endtok, cpp);
}
}
}
}
static Token * findAstTop(Token *tok1, const Token *tok2)
{
for (Token *tok = tok1; tok && (tok != tok2); tok = tok->next()) {
if (tok->astParent() || tok->astOperand1() || tok->astOperand2()) {
while (tok->astParent() && tok->astParent()->index() >= tok1->index() && tok->astParent()->index() <= tok2->index())
tok = tok->astParent();
return tok;
}
if (Token::simpleMatch(tok, "( {"))
tok = tok->link();
}
for (Token *tok = tok1; tok && (tok != tok2); tok = tok->next()) {
if (tok->isName() || tok->isNumber())
return tok;
if (Token::simpleMatch(tok, "( {"))
tok = tok->link();
}
return nullptr;
}
static Token *skipMethodDeclEnding(Token *tok)
{
if (tok->str() != ")")
tok = tok->previous();
if (!tok || tok->str() != ")")
return nullptr;
Token *const tok2 = const_cast<Token*>(TokenList::isFunctionHead(tok, ";{"));
if (tok2 && tok->next() != tok2)
return tok2;
return nullptr;
}
static Token * createAstAtToken(Token *tok)
{
const bool cpp = tok->isCpp();
// skip function pointer declaration
if (Token::Match(tok, "%type% %type%") && !Token::Match(tok, "return|throw|new|delete")) {
Token* tok2 = tok->tokAt(2);
// skip type tokens and qualifiers etc
while (Token::Match(tok2, "%type%|*|&"))
tok2 = tok2->next();
if (Token::Match(tok2, "%var% [;,)]"))
return tok2;
}
if (Token *const endTok = skipMethodDeclEnding(tok)) {
Token *tok2 = tok;
do {
tok2 = tok2->next();
tok2->setCpp11init(false);
if (Token::Match(tok2, "decltype|noexcept (")) {
AST_state state(cpp);
Token *tok3 = tok2->tokAt(2);
compileExpression(tok3, state);
tok2 = tok2->linkAt(1);
}
} while (tok2 != endTok && !precedes(endTok, tok2));
return endTok;
}
if (Token::Match(tok, "%type%") && !Token::Match(tok, "return|throw|if|while|new|delete")) {
bool isStandardTypeOrQualifier = false;
Token* type = tok;
while (Token::Match(type, "%type%|*|&|<")) {
if (type->isName() && (type->isStandardType() || Token::Match(type, "const|mutable|static|volatile")))
isStandardTypeOrQualifier = true;
if (type->str() == "<") {
if (type->link())
type = type->link();
else
break;
}
type = type->next();
}
if (isStandardTypeOrQualifier && Token::Match(type, "%var% [;,)]"))
return type;
if (Token::Match(type, "( * *| %var%") &&
Token::Match(type->link()->previous(), "%var%|] ) (") &&
Token::Match(type->link()->linkAt(1), ") [;,)]"))
return type->link()->linkAt(1)->next();
}
if (Token::simpleMatch(tok, "for (")) {
if (cpp && Token::Match(tok, "for ( const| auto &|&&| [")) {
Token *decl = Token::findsimplematch(tok, "[");
if (Token::simpleMatch(decl->link(), "] :")) {
AST_state state1(cpp);
while (decl->str() != "]") {
if (Token::Match(decl, "%name% ,|]")) {
state1.op.push(decl);
} else if (decl->str() == ",") {
if (!state1.op.empty()) {
decl->astOperand1(state1.op.top());
state1.op.pop();
}
if (!state1.op.empty()) {
state1.op.top()->astOperand2(decl);
state1.op.pop();
}
state1.op.push(decl);
}
decl = decl->next();
}
if (state1.op.size() > 1) {
Token *lastName = state1.op.top();
state1.op.pop();
state1.op.top()->astOperand2(lastName);
}
decl = decl->next();
Token *colon = decl;
compileExpression(decl, state1);
tok->next()->astOperand1(tok);
tok->next()->astOperand2(colon);
return decl;
}
}
std::vector<Token*> inner;
Token* tok2 = skipDecl(tok->tokAt(2), &inner);
for (Token* tok3 : inner) {
AST_state state1(cpp);
compileExpression(tok3, state1);
}
Token *init1 = nullptr;
Token * const endPar = tok->linkAt(1);
if (tok2 == tok->tokAt(2) && Token::Match(tok2, "%op%|(")) {
init1 = tok2;
AST_state state1(cpp);
compileExpression(tok2, state1);
if (Token::Match(init1, "( !!{")) {
for (Token *tok3 = init1; tok3 && tok3 != tok3->link(); tok3 = tok3->next()) {
if (tok3->astParent()) {
while (tok3->astParent())
tok3 = tok3->astParent();
init1 = tok3;
break;
}
if (!Token::Match(tok3, "%op%|(|["))
init1 = tok3;
}
}
} else {
while (tok2 && tok2 != endPar && tok2->str() != ";") {
if (tok2->str() == "<" && tok2->link()) {
tok2 = tok2->link();
} else if (Token::Match(tok2, "%name% )| %op%|(|[|{|.|:|::") || Token::Match(tok2->previous(), "[(;{}] %cop%|(")) {
init1 = tok2;
AST_state state1(cpp);
compileExpression(tok2, state1);
if (Token::Match(tok2, ";|)"))
break;
init1 = nullptr;
}
if (!tok2) // #7109 invalid code
return nullptr;
tok2 = tok2->next();
}
}
if (!tok2 || tok2->str() != ";") {
if (tok2 == endPar && init1) {
createAstAtTokenInner(init1->next(), endPar, cpp);
tok->next()->astOperand2(init1);
tok->next()->astOperand1(tok);
}
return tok2;
}
Token * const init = init1 ? init1 : tok2;
Token * const semicolon1 = tok2;
tok2 = tok2->next();
AST_state state2(cpp);
compileExpression(tok2, state2);
Token * const semicolon2 = tok2;
if (!semicolon2)
return nullptr; // invalid code #7235
if (semicolon2->str() == ";") {
tok2 = tok2->next();
AST_state state3(cpp);
if (Token::simpleMatch(tok2, "( {")) {
state3.op.push(tok2->next());
tok2 = tok2->link()->next();
}
compileExpression(tok2, state3);
tok2 = findAstTop(semicolon1->next(), semicolon2);
if (tok2)
semicolon2->astOperand1(tok2);
tok2 = findAstTop(semicolon2->next(), endPar);
if (tok2)
semicolon2->astOperand2(tok2);
else if (!state3.op.empty())
semicolon2->astOperand2(state3.op.top());
semicolon1->astOperand2(semicolon2);
} else {
if (!cpp || state2.op.empty() || !Token::simpleMatch(state2.op.top(), ":"))
throw InternalError(tok, "syntax error", InternalError::SYNTAX);
semicolon1->astOperand2(state2.op.top());
}
if (init != semicolon1)
semicolon1->astOperand1(init->astTop());
tok->next()->astOperand1(tok);
tok->next()->astOperand2(semicolon1);
createAstAtTokenInner(endPar->link(), endPar, cpp);
return endPar;
}
if (Token::simpleMatch(tok, "( {"))
return tok;
if (Token::Match(tok, "%type% <") && tok->linkAt(1) && !Token::Match(tok->linkAt(1), "> [({]"))
return tok->linkAt(1);
if (cpp && !tok->isKeyword() && Token::Match(tok, "%type% ::|<|%name%")) {
Token *tok2 = tok;
while (true) {
if (Token::Match(tok2, "%name%|> :: %name%"))
tok2 = tok2->tokAt(2);
else if (Token::Match(tok2, "%name% <") && tok2->linkAt(1))
tok2 = tok2->linkAt(1);
else
break;
}
if (Token::Match(tok2, "%name%|> %name% {") && tok2->next()->varId() && iscpp11init(tok2->tokAt(2))) {
Token *const tok1 = tok = tok2->next();
AST_state state(cpp);
compileExpression(tok, state);
createAstAtTokenInner(tok1->next(), tok1->linkAt(1), cpp);
return tok;
}
}
if (Token::Match(tok, "%type% %name%|*|&|::") && !Token::Match(tok, "return|new|delete")) {
int typecount = 0;
Token *typetok = tok;
while (Token::Match(typetok, "%type%|::|*|&")) {
if (typetok->isName() && !Token::simpleMatch(typetok->previous(), "::"))
typecount++;
typetok = typetok->next();
}
if (Token::Match(typetok, "%var% =") && typetok->varId())
tok = typetok;
// Do not create AST for function declaration
if (typetok &&
typecount >= 2 &&
!Token::Match(tok, "return|throw") &&
Token::Match(typetok->previous(), "%name% ( !!*") &&
typetok->previous()->varId() == 0 &&
!typetok->previous()->isKeyword() &&
(skipMethodDeclEnding(typetok->link()) || Token::Match(typetok->link(), ") ;|{")))
return typetok;
}
if (Token::Match(tok, "return|case") ||
(cpp && tok->str() == "throw") ||
!tok->previous() ||
Token::Match(tok, "%name% %op%|(|[|.|::|<|?|;") ||
(cpp && Token::Match(tok, "%name% {") && iscpp11init(tok->next())) ||
Token::Match(tok->previous(), "[;{}:] %cop%|++|--|( !!{") ||
Token::Match(tok->previous(), "[;{}] %num%|%str%|%char%") ||
Token::Match(tok->previous(), "[;{}] delete new") ||
(cpp && Token::Match(tok->previous(), "[;{}] ["))) {
if (cpp && (Token::Match(tok->tokAt(-2), "[;{}] new|delete %name%") || Token::Match(tok->tokAt(-3), "[;{}] :: new|delete %name%")))
tok = tok->previous();
Token * const tok1 = tok;
AST_state state(cpp);
if (Token::Match(tok, "%name% ("))
state.functionCallEndPar = tok->linkAt(1);
if (Token::simpleMatch(tok->tokAt(-1), "::") && (!tok->tokAt(-2) || !tok->tokAt(-2)->isName()))
tok = tok->tokAt(-1);
compileExpression(tok, state);
Token * const endToken = tok;
if (endToken == tok1 || !endToken)
return tok1;
createAstAtTokenInner(tok1->next(), endToken, cpp);
return endToken->previous();
}
if (cpp && tok->str() == "{" && iscpp11init(tok)) {
Token * const tok1 = tok;
AST_state state(cpp);
compileExpression(tok, state);
Token* const endToken = tok;
if (endToken == tok1 || !endToken)
return tok1;
createAstAtTokenInner(tok1->next(), endToken, cpp);
return endToken->previous();
}
return tok;
}
void TokenList::createAst() const
{
for (Token *tok = mTokensFrontBack.front; tok; tok = tok ? tok->next() : nullptr) {
Token* const nextTok = createAstAtToken(tok);
if (precedes(nextTok, tok))
throw InternalError(tok, "Syntax Error: Infinite loop when creating AST.", InternalError::AST);
tok = nextTok;
}
}
namespace {
struct OnException {
std::function<void()> f;
~OnException() {
#ifndef _MSC_VER
if (std::uncaught_exception())
f();
#endif
}
};
}
void TokenList::validateAst(bool print) const
{
OnException oe{[&] {
if (print)
mTokensFrontBack.front->printOut(std::cout);
}};
// Check for some known issues in AST to avoid crash/hang later on
std::set<const Token*> safeAstTokens; // list of "safe" AST tokens without endless recursion
for (const Token *tok = mTokensFrontBack.front; tok; tok = tok->next()) {
// Syntax error if binary operator only has 1 operand
if ((tok->isAssignmentOp() || tok->isComparisonOp() || Token::Match(tok,"[|^/%]")) && tok->astOperand1() && !tok->astOperand2())
throw InternalError(tok, "Syntax Error: AST broken, binary operator has only one operand.", InternalError::AST);
// Syntax error if we encounter "?" with operand2 that is not ":"
if (tok->str() == "?") {
if (!tok->astOperand1() || !tok->astOperand2())
throw InternalError(tok, "AST broken, ternary operator missing operand(s)", InternalError::AST);
if (tok->astOperand2()->str() != ":")
throw InternalError(tok, "Syntax Error: AST broken, ternary operator lacks ':'.", InternalError::AST);
}
// Check for endless recursion
const Token* parent = tok->astParent();
if (parent) {
std::set<const Token*> astTokens; // list of ancestors
astTokens.insert(tok);
do {
if (safeAstTokens.find(parent) != safeAstTokens.end())
break;
if (astTokens.find(parent) != astTokens.end())
throw InternalError(tok, "AST broken: endless recursion from '" + tok->str() + "'", InternalError::AST);
astTokens.insert(parent);
} while ((parent = parent->astParent()) != nullptr);
safeAstTokens.insert(astTokens.cbegin(), astTokens.cend());
} else if (tok->str() == ";") {
safeAstTokens.clear();
} else {
safeAstTokens.insert(tok);
}
// Don't check templates
if (tok->str() == "<" && tok->link()) {
tok = tok->link();
continue;
}
if (tok->isCast()) {
if (!tok->astOperand2() && precedes(tok->astOperand1(), tok))
throw InternalError(tok, "AST broken: '" + tok->str() + "' has improper operand.", InternalError::AST);
if (tok->astOperand1() && tok->link()) { // skip casts (not part of the AST)
tok = tok->link();
continue;
}
}
if (findLambdaEndToken(tok)) { // skip lambda captures
tok = tok->link();
continue;
}
// Check binary operators
if (Token::Match(tok, "%or%|%oror%|%assign%|%comp%")) {
// Skip pure virtual functions
if (Token::simpleMatch(tok->previous(), ") = 0"))
continue;
// Skip operator definitions
if (Token::simpleMatch(tok->previous(), "operator"))
continue;
// Skip incomplete code
if (!tok->astOperand1() && !tok->astOperand2() && !tok->astParent())
continue;
// Skip lambda assignment and/or initializer
if (Token::Match(tok, "= {|^|["))
continue;
// FIXME: Workaround broken AST assignment in type aliases
if (Token::Match(tok->previous(), "%name% = %name%"))
continue;
if (!tok->astOperand1() || !tok->astOperand2())
throw InternalError(tok, "Syntax Error: AST broken, binary operator '" + tok->str() + "' doesn't have two operands.", InternalError::AST);
}
if (Token::Match(tok, "++|--") && !tok->astOperand1()) {
throw InternalError(tok, "Syntax Error: AST broken, operator '" + tok->str() + "' doesn't have an operand.", InternalError::AST);
}
// Check control blocks and asserts
if (Token::Match(tok->previous(), "if|while|for|switch|assert|ASSERT (")) {
if (!tok->astOperand1() || !tok->astOperand2())
throw InternalError(tok,
"Syntax Error: AST broken, '" + tok->strAt(-1) +
"' doesn't have two operands.",
InternalError::AST);
}
if (tok->str() == "case" && !tok->astOperand1()) {
throw InternalError(tok,
"Syntax Error: AST broken, 'case' doesn't have an operand.",
InternalError::AST);
}
// Check member access
if (Token::Match(tok, "%var% .")) {
if (!tok->astParent()) {
throw InternalError(
tok, "Syntax Error: AST broken, '" + tok->str() + "' doesn't have a parent.", InternalError::AST);
}
if (!tok->next()->astOperand1() || !tok->next()->astOperand2()) {
const std::string& op =
tok->next()->originalName().empty() ? tok->strAt(1) : tok->next()->originalName();
throw InternalError(
tok, "Syntax Error: AST broken, '" + op + "' doesn't have two operands.", InternalError::AST);
}
}
}
}
std::string TokenList::getOrigFile(const Token *tok) const
{
return mOrigFiles.at(tok->fileIndex());
}
const std::string& TokenList::file(const Token *tok) const
{
return mFiles.at(tok->fileIndex());
}
std::string TokenList::fileLine(const Token *tok) const
{
return ErrorMessage::FileLocation(tok, this).stringify();
}
bool TokenList::validateToken(const Token* tok) const
{
if (!tok)
return true;
for (const Token *t = mTokensFrontBack.front; t; t = t->next()) {
if (tok==t)
return true;
}
return false;
}
void TokenList::simplifyPlatformTypes()
{
if (!mSettings)
return;
const bool isCPP11 = isCPP() && (mSettings->standards.cpp >= Standards::CPP11);
enum : std::uint8_t { isLongLong, isLong, isInt } type;
/** @todo This assumes a flat address space. Not true for segmented address space (FAR *). */
if (mSettings->platform.sizeof_size_t == mSettings->platform.sizeof_long)
type = isLong;
else if (mSettings->platform.sizeof_size_t == mSettings->platform.sizeof_long_long)
type = isLongLong;
else if (mSettings->platform.sizeof_size_t == mSettings->platform.sizeof_int)
type = isInt;
else
return;
for (Token *tok = front(); tok; tok = tok->next()) {
// pre-check to reduce unneeded match calls
if (!Token::Match(tok, "std| ::| %type%"))
continue;
bool isUnsigned;
if (Token::Match(tok, "std| ::| size_t|uintptr_t|uintmax_t")) {
if (isCPP11 && tok->strAt(-1) == "using" && tok->strAt(1) == "=")
continue;
isUnsigned = true;
} else if (Token::Match(tok, "std| ::| ssize_t|ptrdiff_t|intptr_t|intmax_t")) {
if (isCPP11 && tok->strAt(-1) == "using" && tok->strAt(1) == "=")
continue;
isUnsigned = false;
} else
continue;
bool inStd = false;
if (tok->str() == "::") {
tok->deleteThis();
} else if (tok->str() == "std") {
if (tok->strAt(1) != "::")
continue;
inStd = true;
tok->deleteNext();
tok->deleteThis();
}
if (inStd)
tok->originalName("std::" + tok->str());
else
tok->originalName(tok->str());
if (isUnsigned)
tok->isUnsigned(true);
switch (type) {
case isLongLong:
tok->isLong(true);
tok->str("long");
break;
case isLong:
tok->str("long");
break;
case isInt:
tok->str("int");
break;
}
}
const std::string platform_type(mSettings->platform.toString());
for (Token *tok = front(); tok; tok = tok->next()) {
if (tok->tokType() != Token::eType && tok->tokType() != Token::eName)
continue;
const Library::PlatformType * const platformtype = mSettings->library.platform_type(tok->str(), platform_type);
if (platformtype) {
// check for namespace
if (tok->strAt(-1) == "::") {
const Token * tok1 = tok->tokAt(-2);
// skip when non-global namespace defined
if (tok1 && tok1->tokType() == Token::eName)
continue;
tok = tok->previous();
tok->deleteThis();
}
tok->originalName(tok->str());
const bool isFunctionalPtrCast = (platformtype->mConstPtr || platformtype->mPointer || platformtype->mPtrPtr) &&
Token::Match(tok, "%name% [({]") && !Token::simpleMatch(tok->linkAt(1), ") (");
Token* start = isFunctionalPtrCast ? tok->tokAt(1) : nullptr;
Token* end = isFunctionalPtrCast ? tok->linkAt(1) : nullptr;
Token *typeToken;
if (platformtype->mConstPtr) {
tok->str("const");
tok->isSimplifiedTypedef(true);
tok->insertToken("*")->isSimplifiedTypedef(true);
tok->insertToken(platformtype->mType)->isSimplifiedTypedef(true);
typeToken = tok;
} else if (platformtype->mPointer) {
tok->str(platformtype->mType);
tok->isSimplifiedTypedef(true);
typeToken = tok;
tok->insertToken("*")->isSimplifiedTypedef(true);
} else if (platformtype->mPtrPtr) {
tok->str(platformtype->mType);
tok->isSimplifiedTypedef(true);
typeToken = tok;
tok->insertToken("*")->isSimplifiedTypedef(true);
tok->insertToken("*")->isSimplifiedTypedef(true);
} else {
tok->str(platformtype->mType);
tok->isSimplifiedTypedef(true);
typeToken = tok;
}
if (platformtype->mSigned)
typeToken->isSigned(true);
if (platformtype->mUnsigned)
typeToken->isUnsigned(true);
if (platformtype->mLong)
typeToken->isLong(true);
if (isFunctionalPtrCast) {
start->str("(");
end->str(")");
if (end == start->tokAt(1))
end->insertTokenBefore("0");
end = start->insertTokenBefore(")");
start = tok->insertTokenBefore("(");
start->isSimplifiedTypedef(true);
Token::createMutualLinks(start, end);
}
}
}
}
void TokenList::simplifyStdType()
{
auto isVarDeclC = [](const Token* tok) -> bool {
if (!Token::simpleMatch(tok, "}"))
return false;
tok = tok->link()->previous();
while (Token::Match(tok, "%name%")) {
if (Token::Match(tok, "struct|union|enum"))
return true;
tok = tok->previous();
}
return false;
};
for (Token *tok = front(); tok; tok = tok->next()) {
if (isC() && Token::Match(tok, "const|extern *|&|%name%") && (!tok->previous() || Token::Match(tok->previous(), "[;{}]"))) {
if (Token::Match(tok->next(), "%name% !!;"))
continue;
if (isVarDeclC(tok->previous()))
continue;
tok->insertToken("int");
tok->next()->isImplicitInt(true);
continue;
}
if (Token::Match(tok, "char|short|int|long|unsigned|signed|double|float") || (isC() && (!mSettings || (mSettings->standards.c >= Standards::C99)) && Token::Match(tok, "complex|_Complex"))) {
bool isFloat= false;
bool isSigned = false;
bool isUnsigned = false;
bool isComplex = false;
int countLong = 0;
Token* typeSpec = nullptr;
Token* tok2 = tok;
for (; tok2->next(); tok2 = tok2->next()) {
if (tok2->str() == "long") {
countLong++;
if (!isFloat)
typeSpec = tok2;
} else if (tok2->str() == "short") {
typeSpec = tok2;
} else if (tok2->str() == "unsigned")
isUnsigned = true;
else if (tok2->str() == "signed")
isSigned = true;
else if (Token::Match(tok2, "float|double")) {
isFloat = true;
typeSpec = tok2;
} else if (isC() && (!mSettings || (mSettings->standards.c >= Standards::C99)) && Token::Match(tok2, "complex|_Complex"))
isComplex = !isFloat || tok2->str() == "_Complex" || Token::Match(tok2->next(), "*|&|%name%"); // Ensure that "complex" is not the variables name
else if (Token::Match(tok2, "char|int")) {
if (!typeSpec)
typeSpec = tok2;
} else
break;
}
if (!typeSpec) { // unsigned i; or similar declaration
if (!isComplex) { // Ensure that "complex" is not the variables name
tok->str("int");
tok->isSigned(isSigned);
tok->isUnsigned(isUnsigned);
tok->isImplicitInt(true);
}
} else {
typeSpec->isLong(typeSpec->isLong() || (isFloat && countLong == 1) || countLong > 1);
typeSpec->isComplex(typeSpec->isComplex() || (isFloat && isComplex));
typeSpec->isSigned(typeSpec->isSigned() || isSigned);
typeSpec->isUnsigned(typeSpec->isUnsigned() || isUnsigned);
// Remove specifiers
const Token* tok3 = tok->previous();
tok2 = tok2->previous();
while (tok3 != tok2) {
if (tok2 != typeSpec &&
(isComplex || !Token::Match(tok2, "complex|_Complex"))) // Ensure that "complex" is not the variables name
tok2->deleteThis();
tok2 = tok2->previous();
}
}
}
}
}
bool TokenList::isKeyword(const std::string &str) const
{
if (isCPP()) {
// TODO: integrate into keywords?
// types and literals are not handled as keywords
static const std::unordered_set<std::string> cpp_types = {"bool", "false", "true"};
if (cpp_types.find(str) != cpp_types.end())
return false;
if (mSettings) {
const auto &cpp_keywords = Keywords::getAll(mSettings->standards.cpp);
return cpp_keywords.find(str) != cpp_keywords.end();
}
static const auto& latest_cpp_keywords = Keywords::getAll(Standards::cppstd_t::CPPLatest);
return latest_cpp_keywords.find(str) != latest_cpp_keywords.end();
}
// TODO: integrate into Keywords?
// types are not handled as keywords
static const std::unordered_set<std::string> c_types = {"char", "double", "float", "int", "long", "short"};
if (c_types.find(str) != c_types.end())
return false;
if (mSettings) {
const auto &c_keywords = Keywords::getAll(mSettings->standards.c);
return c_keywords.find(str) != c_keywords.end();
}
static const auto& latest_c_keywords = Keywords::getAll(Standards::cstd_t::CLatest);
return latest_c_keywords.find(str) != latest_c_keywords.end();
}
bool TokenList::isC() const
{
ASSERT_LANG(mLang != Standards::Language::None);
// TODO: remove the fallback
if (mLang == Standards::Language::None)
return false; // treat as C++ by default
return mLang == Standards::Language::C;
}
bool TokenList::isCPP() const
{
ASSERT_LANG(mLang != Standards::Language::None);
// TODO: remove the fallback
if (mLang == Standards::Language::None)
return true; // treat as C++ by default
return mLang == Standards::Language::CPP;
}
void TokenList::setLang(Standards::Language lang, bool force)
{
ASSERT_LANG(lang != Standards::Language::None);
if (!force)
{
ASSERT_LANG(mLang == Standards::Language::None);
}
mLang = lang;
}
const Token * TokenList::isFunctionHead(const Token *tok, const std::string &endsWith)
{
if (!tok)
return nullptr;
if (tok->str() == "(")
tok = tok->link();
if (tok->str() != ")")
return nullptr;
if (!tok->isCpp() && !Token::Match(tok->link()->previous(), "%name%|(|)"))
return nullptr;
if (Token::Match(tok, ") ;|{|[")) {
tok = tok->next();
while (tok && tok->str() == "[" && tok->link()) {
if (endsWith.find(tok->str()) != std::string::npos)
return tok;
tok = tok->link()->next();
}
return (tok && endsWith.find(tok->str()) != std::string::npos) ? tok : nullptr;
}
if (tok->isCpp() && tok->str() == ")") {
tok = tok->next();
while (Token::Match(tok, "const|noexcept|override|final|volatile|mutable|&|&& !!(") ||
(Token::Match(tok, "%name% !!(") && tok->isUpperCaseName()))
tok = tok->next();
if (tok && tok->str() == ")")
tok = tok->next();
while (tok && tok->str() == "[")
tok = tok->link()->next();
if (Token::Match(tok, "throw|noexcept ("))
tok = tok->linkAt(1)->next();
if (Token::Match(tok, "%name% (") && tok->isUpperCaseName())
tok = tok->linkAt(1)->next();
if (tok && tok->originalName() == "->") { // trailing return type
for (tok = tok->next(); tok && !Token::Match(tok, ";|{|override|final|}|)|]"); tok = tok->next())
if (tok->link() && Token::Match(tok, "<|[|("))
tok = tok->link();
}
while (Token::Match(tok, "override|final !!(") ||
(Token::Match(tok, "%name% !!(") && tok->isUpperCaseName()))
tok = tok->next();
if (Token::Match(tok, "= 0|default|delete ;"))
tok = tok->tokAt(2);
if (Token::simpleMatch(tok, "requires")) {
for (tok = tok->next(); tok && !Token::Match(tok, ";|{|}|)|]"); tok = tok->next()) {
if (tok->link() && Token::Match(tok, "<|[|("))
tok = tok->link();
if (Token::simpleMatch(tok, "bool {"))
tok = tok->linkAt(1);
}
}
if (tok && tok->str() == ":" && !Token::Match(tok->next(), "%name%|::"))
return nullptr;
return (tok && endsWith.find(tok->str()) != std::string::npos) ? tok : nullptr;
}
return nullptr;
}
|