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
|
/****************************************************************************
**
** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Script Generator project on Qt Labs.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "classgenerator.h"
#include "fileout.h"
#include <QtCore/QDir>
#include <QtCore/QMetaType>
#include <qdebug.h>
#define GENERATOR_NO_PROTECTED_FUNCTIONS
ClassGenerator::ClassGenerator(PriGenerator *pri, SetupGenerator *setup) :
priGenerator(pri),
setupGenerator(setup)
{}
QString ClassGenerator::fileNameForClass(const AbstractMetaClass *meta_class) const
{
return QString("qtscript_%1.cpp").arg(meta_class->name());
}
bool ClassGenerator::shouldGenerate(const AbstractMetaClass *meta_class) const
{
uint cg = meta_class->typeEntry()->codeGeneration();
return (cg & TypeEntry::GenerateCode) != 0;
}
static QString normalizedType(const AbstractMetaType *type)
{
QString str = QString::fromLatin1(QMetaObject::normalizedType(type->cppSignature().toLatin1()));
if (str.endsWith(QLatin1Char('&')))
str.chop(1);
else if (str.startsWith("const ")) {
if (str.endsWith('*') || type->hasInstantiations() || type->typeEntry()->isValue())
str.remove(0, 6);
}
if (str == QLatin1String("QBool")) // ### hack
str = QLatin1String("bool");
return str;
}
/*!
Returns true if the class \a meta_class inherits from QObject,
otherwise returns false.
*/
static bool isQObjectBased(const AbstractMetaClass *meta_class)
{
while (meta_class) {
if (meta_class->name() == QLatin1String("QObject"))
return true;
meta_class = meta_class->baseClass();
}
return false;
}
/*!
Returns true if any of the given \a enums has been declared with
Q_ENUMS.
*/
static bool hasQEnums(const AbstractMetaEnumList &enums)
{
for (int i = 0; i < enums.size(); ++i) {
if (enums.at(i)->hasQEnumsDeclaration())
return true;
}
return false;
}
/*!
Returns true if any of the given \a enums has a QFlags class
associated with it.
*/
static bool hasFlags(const AbstractMetaEnumList &enums)
{
for (int i = 0; i < enums.size(); ++i) {
FlagsTypeEntry *flags = enums.at(i)->typeEntry()->flags();
if (flags)
return true;
}
return false;
}
static bool isSequenceType(const AbstractMetaType *tp)
{
return tp->isContainer() && (tp->instantiations().size() == 1);
}
static AbstractMetaFunction *findDefaultConstructor(const AbstractMetaFunctionList &ctors)
{
for (int i = 0; i < ctors.size(); ++i) {
if (ctors.at(i)->actualMinimumArgumentCount() == 0)
return ctors.at(i);
}
return 0;
}
static AbstractMetaFunctionList findConstructors(const AbstractMetaClass *meta_class)
{
return meta_class->queryFunctions(AbstractMetaClass::Constructors
| AbstractMetaClass::WasPublic
| AbstractMetaClass::NotRemovedFromTargetLang);
}
/*!
Returns true if \a meta_class has a default constructor, false
otherwise.
*/
bool hasDefaultConstructor(const AbstractMetaClass *meta_class)
{
return findDefaultConstructor(findConstructors(meta_class)) != 0;
}
/*!
Given the list of \a functions, creates a mapping from # of
arguments to list of functions.
*/
static QMap<int, AbstractMetaFunctionList> createArgcToFunctionsMap(
const AbstractMetaFunctionList &functions)
{
QMap<int, AbstractMetaFunctionList> result;
for (int i = 0; i < functions.size(); ++i) {
AbstractMetaFunction *func = functions.at(i);
int argc = func->arguments().size();
for (int k = argc; k > 0; --k) {
if (func->argumentRemoved(k))
--argc;
}
for (int j = func->actualMinimumArgumentCount(); j <= argc; ++j)
result[j].append(func);
}
return result;
}
/*!
Returns the name of the QScriptValue function to use to test if
a value is of the given \a typeName, or an empty string if there
is no such function.
*/
static QString builtinTypeTesterFunction(const QString &typeName)
{
if (typeName == QLatin1String("QString"))
return QLatin1String("isString");
else if (typeName == QLatin1String("double"))
return QLatin1String("isNumber");
else if (typeName == QLatin1String("float"))
return QLatin1String("isNumber");
else if (typeName == QLatin1String("int"))
return QLatin1String("isNumber");
else if (typeName == QLatin1String("uint"))
return QLatin1String("isNumber");
else if (typeName == QLatin1String("short"))
return QLatin1String("isNumber");
else if (typeName == QLatin1String("unsigned short"))
return QLatin1String("isNumber");
else if (typeName == QLatin1String("bool"))
return QLatin1String("isBoolean");
else if (typeName == QLatin1String("QVariant"))
return QLatin1String("isVariant");
// else if (typeName == QLatin1String("QDateTime"))
// return QLatin1String("isDate");
else if (typeName == QLatin1String("QRegExp"))
return QLatin1String("isRegExp");
else if (typeName == QLatin1String("QObject*"))
return QLatin1String("isQObject");
return QString();
}
/*!
Writes the code injections for the class \a meta_class that should
be injected at position \a pos.
*/
static void writeInjectedCode(QTextStream &s, const AbstractMetaClass *meta_class,
CodeSnip::Position pos)
{
CodeSnipList code_snips = meta_class->typeEntry()->codeSnips();
foreach (const CodeSnip &cs, code_snips) {
if ((cs.language == TypeSystem::NativeCode) && (cs.position == pos)) {
s << cs.code() << endl;
}
}
}
/*!
Writes the code injections for the function \a fun of the class \a
meta_class that should be injected at position \a pos.
*/
static void writeInjectedCode(QTextStream &s, const AbstractMetaClass *meta_class,
const AbstractMetaFunction *fun, CodeSnip::Position pos)
{
FunctionModificationList mods = fun->modifications(meta_class);
foreach (const FunctionModification &mod, mods) {
if (!mod.isCodeInjection())
continue;
foreach (const CodeSnip &cs, mod.snips) {
if ((cs.language == TypeSystem::NativeCode) && (cs.position == pos)) {
s << cs.code() << endl;
}
}
}
}
/*!
Writes a boolean expression that checks if the actual arguments are
compatible with what the function expects. This is used to resolve
ambiguous calls.
*/
static void writeArgumentTypeTests(QTextStream &stream, const AbstractMetaFunction *fun,
const AbstractMetaArgumentList &arguments, int argc, int indent)
{
QString indentStr(indent, QLatin1Char(' '));
int j = 0;
for (int i = 0; i < argc; ++j) {
if (fun->argumentRemoved(j+1))
continue;
if (i > 0)
stream << endl << indentStr << "&& ";
const AbstractMetaType *argType = 0;
QString typeName = fun->typeReplaced(j+1);
if (typeName.isEmpty()) {
AbstractMetaArgument *arg = arguments.at(j);
argType = arg->type();
typeName = normalizedType(argType);
}
QString scriptArg = QString::fromLatin1("context->argument(%0)").arg(i);
if (argType && isSequenceType(argType)) {
stream << scriptArg << ".isArray()";
} else if (typeName == "QVariant") {
stream << "true";
} else {
QString tester = builtinTypeTesterFunction(typeName);
if (!tester.isEmpty()) {
stream << scriptArg << "." << tester << "()";
} else if (typeName.endsWith('*')) {
stream << "qscriptvalue_cast<" << typeName << ">(" << scriptArg << ")";
} else {
// typeid-based test
stream << "(qMetaTypeId<" << typeName;
if (typeName.endsWith(QLatin1Char('>')))
stream << " ";
stream << ">() == " << scriptArg << ".toVariant().userType())";
}
}
++i;
}
}
/*!
Returns the name of the QScriptValue function to use to convert a
value is of the given \a typeName, or an empty string if there is no
such function.
*/
static QString builtinConversionFunction(const QString &typeName)
{
if (typeName == QLatin1String("QString"))
return QLatin1String("toString");
else if (typeName == QLatin1String("double"))
return QLatin1String("toNumber");
else if (typeName == QLatin1String("int"))
return QLatin1String("toInt32");
else if (typeName == QLatin1String("uint"))
return QLatin1String("toUInt32");
else if (typeName == QLatin1String("bool"))
return QLatin1String("toBoolean");
else if (typeName == QLatin1String("QVariant"))
return QLatin1String("toVariant");
else if (typeName == QLatin1String("QDateTime"))
return QLatin1String("toDateTime");
else if (typeName == QLatin1String("QRegExp"))
return QLatin1String("toRegExp");
else if (typeName == QLatin1String("QObject*"))
return QLatin1String("toQObject");
return QString();
}
/*!
Generates script arguments --> C++ types conversion, in preparation
for calling the native function we are binding.
*/
static int writePrepareArguments(QTextStream &stream, const AbstractMetaFunction *fun,
const AbstractMetaArgumentList &arguments,
int scriptArgc, int indent)
{
if (arguments.size() == 0) {
Q_ASSERT(scriptArgc == 0);
return 0; // nothing to do
}
QString indentStr(indent, QLatin1Char(' '));
int j = 0;
for (int scriptArgIndex = 0; j < arguments.size(); ++j) {
const AbstractMetaArgument *arg = arguments.at(j);
bool isOptional = !arg->defaultValueExpression().isEmpty();
if (isOptional && (scriptArgIndex == scriptArgc))
break;
QString conv = fun->conversionRule(TypeSystem::NativeCode, j+1);
QString actualIn = QString::fromLatin1("context->argument(%0)").arg(scriptArgIndex);
QString actualOut = QString::fromLatin1("_q_arg%0").arg(j);
if (!conv.isEmpty()) {
// custom conversion
conv.replace(QString::fromLatin1("%in%"), actualIn);
conv.replace(QString::fromLatin1("%out%"), actualOut);
conv.replace(QString::fromLatin1("%this%"), QString::fromLatin1("_q_self"));
stream << conv;
} else {
const AbstractMetaType *argType = 0;
QString typeName = fun->typeReplaced(j+1);
if (typeName.isEmpty()) {
argType = arg->type();
typeName = normalizedType(argType);
}
stream << indentStr << typeName << " " << actualOut;
QString converter;
// ### generalize the QSet check (we should check if the type has push_back())
bool useToSequence = argType && isSequenceType(argType) && !argType->name().startsWith("Set");
if (useToSequence) {
stream << ";" << endl;
stream << indentStr << "qScriptValueToSequence(";
} else {
stream << " = ";
converter = builtinConversionFunction(typeName);
if (converter.isEmpty()) {
// generic conversion
stream << "qscriptvalue_cast<" << typeName;
if (typeName.endsWith(QLatin1Char('>')))
stream << " ";
stream << ">(";
}
}
stream << actualIn;
if (useToSequence) {
stream << ", " << actualOut << ")";
} else {
if (converter.isEmpty()) {
stream << ")"; // close qscriptvalue_cast
} else {
stream << "." << converter << "()";
}
}
stream << ";" << endl;
}
if (!fun->argumentRemoved(j+1))
++scriptArgIndex;
}
return j;
}
/*!
Writes the arguments that are passed to the native function we are
binding. Those arguments must have been prepared already in variables
_q_arg0, _q_arg1, .. in the generated code.
*/
static void writeArguments(QTextStream &stream, int count)
{
for (int i = 0; i < count; ++i) {
if (i > 0)
stream << ", ";
stream << "_q_arg" << i;
}
}
/*!
Writes a constructor call.
*/
static void writeConstructorCallAndReturn(QTextStream &stream, const AbstractMetaFunction *fun,
int scriptArgc, const AbstractMetaClass *meta_class,
int indent)
{
QString indentStr(indent, QLatin1Char(' '));
writeInjectedCode(stream, meta_class, fun, CodeSnip::Beginning);
AbstractMetaArgumentList arguments = fun->arguments();
Q_ASSERT(arguments.size() >= scriptArgc);
int nativeArgc = writePrepareArguments(stream, fun, arguments, scriptArgc, indent);
stream << indentStr;
if (meta_class->generateShellClass()) {
stream << "QtScriptShell_" << meta_class->name();
} else {
stream << meta_class->qualifiedCppName();
}
bool useNew = meta_class->typeEntry()->isObject() || !hasDefaultConstructor(meta_class);
if (useNew)
stream << "*";
stream << " _q_cpp_result";
if (useNew) {
stream << " = new ";
if (meta_class->generateShellClass())
stream << "QtScriptShell_" << meta_class->name();
else
stream << meta_class->qualifiedCppName();
}
if (useNew || (nativeArgc != 0)) {
stream << "(";
writeArguments(stream, nativeArgc);
stream << ")";
}
stream << ";" << endl;
stream << indentStr << "QScriptValue _q_result = context->engine()->new";
if (isQObjectBased(meta_class))
stream << "QObject";
else
stream << "Variant";
stream << "(context->thisObject(), ";
if (!isQObjectBased(meta_class))
stream << "qVariantFromValue(";
if (meta_class->generateShellClass()) {
stream << "(" << meta_class->qualifiedCppName();
if (useNew)
stream << "*";
stream << ")";
}
stream << "_q_cpp_result";
if (isQObjectBased(meta_class))
stream << ", QScriptEngine::AutoOwnership";
else
stream << ")";
stream << ");" << endl;
if (meta_class->generateShellClass()) {
stream << indentStr << "_q_cpp_result";
if (useNew)
stream << "->";
else
stream << ".";
stream << "__qtscript_self = _q_result;" << endl;
}
writeInjectedCode(stream, meta_class, fun, CodeSnip::End);
stream << indentStr << "return _q_result;" << endl;
}
/*!
Returns true if the given \a typeName has a QScriptValue constructor
we can use, false otherwise.
*/
static bool hasScriptValueConstructor(const QString &typeName)
{
return (typeName == QLatin1String("bool"))
|| (typeName == QLatin1String("int"))
|| (typeName == QLatin1String("uint"))
|| (typeName == QLatin1String("double"))
|| (typeName == QLatin1String("QString"));
}
/*!
Writes a function call.
*/
static void writeFunctionCallAndReturn(QTextStream &stream, const AbstractMetaFunction *fun,
int scriptArgc, const AbstractMetaClass *meta_class,
int indent)
{
QString indentStr(indent, QLatin1Char(' '));
AbstractMetaArgumentList arguments = fun->arguments();
Q_ASSERT(arguments.size() >= scriptArgc);
writeInjectedCode(stream, meta_class, fun, CodeSnip::Beginning);
int nativeArgc = writePrepareArguments(stream, fun, arguments, scriptArgc, indent);
bool returnThisObject = fun->shouldReturnThisObject();
bool ignoreReturnValue = returnThisObject || fun->shouldIgnoreReturnValue();
stream << indentStr;
AbstractMetaType *retType = fun->type();
bool constCastResult = false;
if (retType && !ignoreReturnValue) {
QString rsig = retType->cppSignature();
QString typeName = normalizedType(retType);
stream << typeName << " _q_result = ";
constCastResult = rsig.endsWith('*') && rsig.startsWith("const ");
if (constCastResult)
stream << "const_cast<" << typeName << ">(";
}
if (!fun->isStatic()) {
// ### the friendly check should be enough...
if (fun->isFriendly()
|| ((fun->name() == QLatin1String("operator_equal"))
&& ((meta_class->name() == QLatin1String("QPoint"))
|| (meta_class->name() == QLatin1String("QPointF"))
|| (meta_class->name() == QLatin1String("QRect"))
|| (meta_class->name() == QLatin1String("QRectF"))
|| (meta_class->name() == QLatin1String("QSize"))
|| (meta_class->name() == QLatin1String("QSizeF"))
|| (meta_class->name() == QLatin1String("QQuaternion"))
|| (meta_class->name() == QLatin1String("QMargins"))
|| (meta_class->name() == QLatin1String("QVector2D"))
|| (meta_class->name() == QLatin1String("QVector3D"))
|| (meta_class->name() == QLatin1String("QVector4D"))))) {
stream << fun->originalName() << "(";
stream << "*_q_self, ";
} else {
stream << "_q_self->";
stream << fun->originalName() << "(";
}
} else {
stream << meta_class->qualifiedCppName() << "::";
stream << fun->originalName() << "(";
}
writeArguments(stream, nativeArgc);
if (constCastResult)
stream << ")";
stream << ");" << endl;
writeInjectedCode(stream, meta_class, fun, CodeSnip::End);
// write return statement
stream << indentStr;
if (returnThisObject) {
stream << "return context->thisObject();";
} else {
QString conv = fun->conversionRule(TypeSystem::NativeCode, 0);
if (!conv.isEmpty()) {
// custom conversion
conv.replace(QString::fromLatin1("%in%"), "_q_result");
conv.replace(QString::fromLatin1("%out%"), "_q_convertedResult");
stream << conv;
stream << "return qScriptValueFromValue(context->engine(), _q_convertedResult);";
} else {
stream << "return ";
if (retType) {
if (isSequenceType(retType))
stream << "qScriptValueFromSequence";
else if (hasScriptValueConstructor(normalizedType(retType)))
stream << "QScriptValue";
else
stream << "qScriptValueFromValue";
stream << "(context->engine(), _q_result);";
} else {
stream << "context->engine()->undefinedValue();";
}
}
}
stream << endl;
}
/*!
Returns true if the given function \a fun is operator>>() or
operator<<() that streams from/to a Q{Data,Text}Stream, false
otherwise.
*/
static bool isSpecialStreamingOperator(const AbstractMetaFunction *fun)
{
return ((fun->functionType() == AbstractMetaFunction::GlobalScopeFunction)
&& (fun->arguments().size() == 1)
&& (((fun->originalName() == "operator>>") && (fun->modifiedName() == "readFrom"))
|| ((fun->originalName() == "operator<<") && (fun->modifiedName() == "writeTo"))));
}
/*!
Generates code that uses Q{Data,Text}Stream operator>>() or
operator<<() to read/write an instance of meta_class.
*/
static void writeStreamingOperatorCall(QTextStream &stream, const AbstractMetaFunction *fun,
const AbstractMetaClass * /*meta_class*/, int indent)
{
QString indentStr(indent, QLatin1Char(' '));
QString streamClassName = fun->arguments().at(0)->type()->name();
stream << indentStr << streamClassName << "* _q_arg0 = qscriptvalue_cast<"
<< streamClassName << "*>(context->argument(0));" << endl;
stream << indentStr << "operator";
if (fun->modifiedName() == "readFrom")
stream << ">>";
else
stream << "<<";
stream << "(*_q_arg0, *_q_self);" << endl;
stream << indentStr << "return context->engine()->undefinedValue();" << endl;
}
/*!
Writes the constructor forwarding for \a meta_class.
*/
static void writeConstructorForwarding(QTextStream &stream,
const AbstractMetaFunctionList &functions,
const AbstractMetaClass *meta_class)
{
#if 0
stream << "/** signatures:" << endl;
foreach (const AbstractMetaFunction *fun, functions) {
stream << " * " << fun->signature() << endl;
}
stream << " */" << endl;
#endif
if (/*meta_class->isAbstract() ||*/ (functions.size() == 0)) {
stream << " return context->throwError(QScriptContext::TypeError," << endl
<< " QString::fromLatin1(\"" << meta_class->name()
<< " cannot be constructed\"));" << endl;
} else {
stream << " if (context->thisObject().strictlyEquals(context->engine()->globalObject())) {" << endl
<< " return context->throwError(QString::fromLatin1(\""
<< meta_class->name() << "(): Did you forget to construct with 'new'?\"));" << endl
<< " }" << endl;
writeInjectedCode(stream, meta_class, CodeSnip::Constructor);
QMap<int, AbstractMetaFunctionList> argcToFunctions;
argcToFunctions = createArgcToFunctionsMap(functions);
int argcMin = argcToFunctions.keys().first();
int argcMax = argcToFunctions.keys().last();
bool needElse = false;
for (int i = argcMin; i <= argcMax; ++i) {
AbstractMetaFunctionList funcs = argcToFunctions.value(i);
if (funcs.isEmpty())
continue;
if (needElse)
stream << " else ";
else
stream << " ";
needElse = true;
stream << "if (context->argumentCount() == " << i << ") {" << endl;
if ((funcs.size() == 1) || (i == 0)) {
AbstractMetaFunction *fun = funcs.at(0);
const int indent = 8;
writeConstructorCallAndReturn(stream, fun, i, meta_class, indent);
} else {
// handle overloads
for (int j = 0; j < funcs.size(); ++j) {
AbstractMetaFunction *fun = funcs.at(j);
stream << " ";
if (j > 0)
stream << "} else ";
stream << "if (";
AbstractMetaArgumentList arguments = fun->arguments();
const int indent = 12;
writeArgumentTypeTests(stream, fun, arguments, i, indent);
stream << ") {" << endl;
writeConstructorCallAndReturn(stream, fun, i, meta_class, indent);
}
stream << " }" << endl;
}
stream << " }";
}
stream << endl;
// writeThrowAmbiguityError(stream, meta_class, 0, signatures.toList());
}
}
/*!
Returns a list of enum \a values that are actually unique.
*/
QList<int> uniqueEnumValueIndexes(const AbstractMetaEnumValueList &values)
{
QMap<int, int> map;
for (int i = 0; i < values.count(); ++i) {
AbstractMetaEnumValue *val = values.at(i);
if (!map.contains(val->value()))
map.insert(val->value(), i);
}
return map.values();
}
/*!
*/
static bool isContiguousEnum(const QList<int> &indexes, const AbstractMetaEnumValueList &values)
{
if (indexes.isEmpty())
return false;
int prev = values.at(indexes.at(0))->value();
for (int i = 1; i < indexes.size(); ++i) {
int curr = values.at(indexes.at(i))->value();
if (curr != prev + 1)
return false;
prev = curr;
}
return true;
}
static void writeCreateEnumClassHelper(QTextStream &stream)
{
stream << "static QScriptValue qtscript_create_enum_class_helper(" << endl
<< " QScriptEngine *engine," << endl
<< " QScriptEngine::FunctionSignature construct," << endl
<< " QScriptEngine::FunctionSignature valueOf," << endl
<< " QScriptEngine::FunctionSignature toString)" << endl
<< "{" << endl
<< " QScriptValue proto = engine->newObject();" << endl
<< " proto.setProperty(QString::fromLatin1(\"valueOf\")," << endl
<< " engine->newFunction(valueOf), QScriptValue::SkipInEnumeration);" << endl
<< " proto.setProperty(QString::fromLatin1(\"toString\")," << endl
<< " engine->newFunction(toString), QScriptValue::SkipInEnumeration);" << endl
<< " return engine->newFunction(construct, proto, 1);" << endl
<< "}" << endl << endl;
}
static void writeCreateFlagsClassHelper(QTextStream &stream)
{
stream << "static QScriptValue qtscript_create_flags_class_helper(" << endl
<< " QScriptEngine *engine," << endl
<< " QScriptEngine::FunctionSignature construct," << endl
<< " QScriptEngine::FunctionSignature valueOf," << endl
<< " QScriptEngine::FunctionSignature toString," << endl
<< " QScriptEngine::FunctionSignature equals)" << endl
<< "{" << endl
<< " QScriptValue proto = engine->newObject();" << endl
<< " proto.setProperty(QString::fromLatin1(\"valueOf\")," << endl
<< " engine->newFunction(valueOf), QScriptValue::SkipInEnumeration);" << endl
<< " proto.setProperty(QString::fromLatin1(\"toString\")," << endl
<< " engine->newFunction(toString), QScriptValue::SkipInEnumeration);" << endl
<< " proto.setProperty(QString::fromLatin1(\"equals\")," << endl
<< " engine->newFunction(equals), QScriptValue::SkipInEnumeration);" << endl
<< " return engine->newFunction(construct, proto);" << endl
<< "}" << endl << endl;
}
/*!
Writes the enum \a enom belonging to the class \a meta_class to the
given \a stream.
*/
static void writeEnumClass(QTextStream &stream, const AbstractMetaClass *meta_class,
const AbstractMetaEnum *enom)
{
QString qualifiedCppNameColons;
if (meta_class->name() != "Global")
qualifiedCppNameColons = meta_class->qualifiedCppName() + "::";
QString qualifiedEnumName = qualifiedCppNameColons + enom->name();
QString qtScriptEnumName = meta_class->name() + "_" + enom->name();
stream << "//" << endl;
stream << "// " << qualifiedEnumName << endl;
stream << "//" << endl << endl;
// determine unique values (aliases will cause switch statement to not compile)
AbstractMetaEnumValueList values = enom->values();
QList<int> uniqueIndexes = uniqueEnumValueIndexes(values);
bool contiguous = isContiguousEnum(uniqueIndexes, values);
// write arrays of values and keys
stream << "static const " << qualifiedEnumName
<< " qtscript_" << qtScriptEnumName << "_values[] = {" << endl;
for (int i = 0; i < uniqueIndexes.size(); ++i) {
stream << " ";
if (i > 0)
stream << ", ";
stream << qualifiedCppNameColons << values.at(uniqueIndexes.at(i))->name() << endl;
}
stream << "};" << endl << endl;
stream << "static const char * const qtscript_" << qtScriptEnumName << "_keys[] = {" << endl;
for (int i = 0; i < uniqueIndexes.size(); ++i) {
stream << " ";
if (i > 0)
stream << ", ";
stream << "\"" << values.at(uniqueIndexes.at(i))->name() << "\"" << endl;
}
stream << "};" << endl << endl;
// write toString helper
stream << "static QString qtscript_"
<< qtScriptEnumName << "_toStringHelper"
<< "(" << qualifiedEnumName << " value)" << endl;
stream << "{" << endl;
if (enom->hasQEnumsDeclaration() && (meta_class->qualifiedCppName() != "QTransform")) {
stream << " const QMetaObject *meta = qtscript_" << meta_class->name() << "_metaObject();" << endl;
stream << " int idx = meta->indexOfEnumerator(\"" << enom->name() << "\");" << endl;
stream << " Q_ASSERT(idx != -1);" << endl;
stream << " QMetaEnum menum = meta->enumerator(idx);" << endl;
stream << " return QString::fromLatin1(menum.valueToKey(value));" << endl;
} else {
if (contiguous) {
stream << " if ((value >= " << qualifiedCppNameColons
<< values.at(uniqueIndexes.first())->name() << ")"
<< " && (value <= " << qualifiedCppNameColons
<< values.at(uniqueIndexes.last())->name() << "))" << endl
<< " return qtscript_" << qtScriptEnumName
<< "_keys[static_cast<int>(value)-static_cast<int>("
<< qualifiedCppNameColons
<< values.at(uniqueIndexes.first())->name() << ")];" << endl;
} else {
stream << " for (int i = 0; i < " << uniqueIndexes.size() << "; ++i) {" << endl
<< " if (qtscript_" << qtScriptEnumName << "_values[i] == value)" << endl
<< " return QString::fromLatin1(qtscript_" << qtScriptEnumName << "_keys[i]);" << endl
<< " }" << endl;
}
stream << " return QString();" << endl;
}
stream << "}" << endl << endl;
// write QScriptValue <--> C++ conversion functions
stream << "static QScriptValue qtscript_"
<< qtScriptEnumName << "_toScriptValue("
<< "QScriptEngine *engine, const " << qualifiedEnumName << " &value)" << endl
<< "{" << endl
<< " QScriptValue clazz = engine->globalObject().property(QString::fromLatin1(\""
<< meta_class->name() << "\"));" << endl
// << " QScriptValue enumClazz = clazz.property(QString::fromLatin1(\""
// << enom->name() << "\"));" << endl
<< " return clazz.property(qtscript_" << qtScriptEnumName << "_toStringHelper(value));" << endl
<< "}" << endl << endl;
stream << "static void qtscript_"
<< qtScriptEnumName << "_fromScriptValue("
<< "const QScriptValue &value, " << qualifiedEnumName << " &out)" << endl
<< "{" << endl
<< " out = qvariant_cast<" << qualifiedEnumName << ">(value.toVariant());" << endl
<< "}" << endl << endl;
// write constructor
stream << "static QScriptValue qtscript_construct_"
<< qtScriptEnumName
<< "(QScriptContext *context, QScriptEngine *engine)" << endl;
stream << "{" << endl;
stream << " int arg = context->argument(0).toInt32();" << endl;
if (enom->hasQEnumsDeclaration() && (meta_class->qualifiedCppName() != "QTransform")) {
stream << " const QMetaObject *meta = qtscript_" << meta_class->name() << "_metaObject();" << endl;
stream << " int idx = meta->indexOfEnumerator(\"" << enom->name() << "\");" << endl;
stream << " Q_ASSERT(idx != -1);" << endl;
stream << " QMetaEnum menum = meta->enumerator(idx);" << endl;
stream << " if (menum.valueToKey(arg) != 0)" << endl;
stream << " return qScriptValueFromValue(engine, static_cast<"
<< qualifiedEnumName << ">(arg));" << endl;
} else {
if (contiguous) {
stream << " if ((arg >= " << qualifiedCppNameColons
<< values.at(uniqueIndexes.first())->name() << ")"
<< " && (arg <= " << qualifiedCppNameColons
<< values.at(uniqueIndexes.last())->name() << "))" << endl;
stream << " return qScriptValueFromValue(engine, static_cast<"
<< qualifiedEnumName << ">(arg));" << endl;
} else {
stream << " for (int i = 0; i < " << uniqueIndexes.size() << "; ++i) {" << endl
<< " if (qtscript_" << qtScriptEnumName << "_values[i] == arg)" << endl;
stream << " return qScriptValueFromValue(engine, static_cast<"
<< qualifiedEnumName << ">(arg));" << endl;
stream << " }" << endl;
}
}
stream << " return context->throwError(QString::fromLatin1(\""
<< enom->name() << "(): invalid enum value (%0)\").arg(arg));" << endl;
stream << "}" << endl;
stream << endl;
// write prototype.valueOf()
stream << "static QScriptValue qtscript_" << qtScriptEnumName
<< "_valueOf(QScriptContext *context, QScriptEngine *engine)" << endl;
stream << "{" << endl;
stream << " " << qualifiedEnumName << " value = "
<< "qscriptvalue_cast<" << qualifiedEnumName
<< ">(context->thisObject());" << endl;
stream << " return QScriptValue(engine, static_cast<int>(value));" << endl;
stream << "}" << endl;
stream << endl;
// write prototype.toString()
stream << "static QScriptValue qtscript_" << qtScriptEnumName
<< "_toString(QScriptContext *context, QScriptEngine *engine)" << endl;
stream << "{" << endl;
stream << " " << qualifiedEnumName << " value = "
<< "qscriptvalue_cast<" << qualifiedEnumName
<< ">(context->thisObject());" << endl;
stream << " return QScriptValue(engine, qtscript_" << qtScriptEnumName << "_toStringHelper(value));" << endl;
stream << "}" << endl;
stream << endl;
// write class creation function
stream << "static QScriptValue qtscript_create_"
<< qtScriptEnumName
<< "_class(QScriptEngine *engine, QScriptValue &clazz)" << endl;
stream << "{" << endl;
stream << " QScriptValue ctor = qtscript_create_enum_class_helper(" << endl
<< " engine, qtscript_construct_" << qtScriptEnumName << "," << endl
<< " qtscript_" << qtScriptEnumName << "_valueOf, qtscript_"
<< qtScriptEnumName << "_toString);" << endl;
stream << " qScriptRegisterMetaType<" << qualifiedEnumName << ">(engine, "
<< "qtscript_" << qtScriptEnumName << "_toScriptValue," << endl
<< " qtscript_" << qtScriptEnumName << "_fromScriptValue,"
<< " ctor.property(QString::fromLatin1(\"prototype\")));" << endl;
// enum values are properties of the constructor
stream << " for (int i = 0; i < " << uniqueIndexes.size() << "; ++i) {" << endl
<< " clazz.setProperty(QString::fromLatin1(qtscript_"
<< qtScriptEnumName << "_keys[i])," << endl
<< " engine->newVariant(qVariantFromValue(qtscript_"
<< qtScriptEnumName << "_values[i]))," << endl
<< " QScriptValue::ReadOnly | QScriptValue::Undeletable);" << endl
<< " }" << endl;
stream << " return ctor;" << endl;
stream << "}" << endl;
stream << endl;
// write flags class too, if any
FlagsTypeEntry *flags = enom->typeEntry()->flags();
if (!flags)
return;
QString qualifiedFlagsName = qualifiedCppNameColons + flags->targetLangName();
QString qtScriptFlagsName = meta_class->name() + "_" + flags->targetLangName();
stream << "//" << endl;
stream << "// " << qualifiedFlagsName << endl;
stream << "//" << endl << endl;
// write QScriptValue <--> C++ conversion functions
stream << "static QScriptValue qtscript_"
<< qtScriptFlagsName << "_toScriptValue("
<< "QScriptEngine *engine, const " << qualifiedFlagsName << " &value)" << endl
<< "{" << endl
<< " return engine->newVariant(qVariantFromValue(value));" << endl
<< "}" << endl << endl;
stream << "static void qtscript_"
<< qtScriptFlagsName << "_fromScriptValue("
<< "const QScriptValue &value, " << qualifiedFlagsName << " &out)" << endl
<< "{" << endl
<< " QVariant var = value.toVariant();" << endl
<< " if (var.userType() == qMetaTypeId<" << qualifiedFlagsName << ">())" << endl
<< " out = qvariant_cast<" << qualifiedFlagsName << ">(var);" << endl
<< " else if (var.userType() == qMetaTypeId<" << qualifiedEnumName << ">())" << endl
<< " out = qvariant_cast<" << qualifiedEnumName << ">(var);" << endl
<< " else" << endl
<< " out = 0;" << endl
<< "}" << endl << endl;
// write constructor
stream << "static QScriptValue qtscript_construct_"
<< qtScriptFlagsName
<< "(QScriptContext *context, QScriptEngine *engine)" << endl;
stream << "{" << endl;
stream << " " << qualifiedFlagsName << " result = 0;" << endl;
stream << " if ((context->argumentCount() == 1) && context->argument(0).isNumber()) {" << endl;
stream << " result = static_cast<" << qualifiedFlagsName << ">(context->argument(0).toInt32());" << endl;
stream << " } else {" << endl;
stream << " for (int i = 0; i < context->argumentCount(); ++i) {" << endl;
stream << " QVariant v = context->argument(i).toVariant();" << endl;
stream << " if (v.userType() != qMetaTypeId<" << qualifiedEnumName << ">()) {" << endl;
stream << " return context->throwError(QScriptContext::TypeError," << endl
<< " QString::fromLatin1(\"" << flags->targetLangName()
<< "(): argument %0 is not of type " << enom->name() << "\").arg(i));" << endl;
stream << " }" << endl;
stream << " result |= qvariant_cast<" << qualifiedEnumName
<< ">(v);" << endl;
stream << " }" << endl;
stream << " }" << endl;
stream << " return engine->newVariant(qVariantFromValue(result));" << endl;
stream << "}" << endl;
stream << endl;
// write prototype.valueOf()
stream << "static QScriptValue qtscript_" << qtScriptFlagsName
<< "_valueOf(QScriptContext *context, QScriptEngine *engine)" << endl;
stream << "{" << endl;
stream << " " << qualifiedFlagsName << " value = "
<< "qscriptvalue_cast<" << qualifiedFlagsName
<< ">(context->thisObject());" << endl;
stream << " return QScriptValue(engine, static_cast<int>(value));" << endl;
stream << "}" << endl;
stream << endl;
// write prototype.toString()
stream << "static QScriptValue qtscript_" << qtScriptFlagsName
<< "_toString(QScriptContext *context, QScriptEngine *engine)" << endl;
stream << "{" << endl;
stream << " " << qualifiedFlagsName << " value = "
<< "qscriptvalue_cast<" << qualifiedFlagsName
<< ">(context->thisObject());" << endl;
stream << " QString result;" << endl;
stream << " for (int i = 0; i < " << uniqueIndexes.size() << "; ++i) {" << endl
<< " if ((value & qtscript_" << qtScriptEnumName << "_values[i])"
<< " == qtscript_" << qtScriptEnumName << "_values[i]) {" << endl
<< " if (!result.isEmpty())" << endl
<< " result.append(QString::fromLatin1(\",\"));" << endl
<< " result.append(QString::fromLatin1(qtscript_" << qtScriptEnumName << "_keys[i]));" << endl
<< " }" << endl
<< " }" << endl
<< " return QScriptValue(engine, result);" << endl
<< "}" << endl
<< endl;
// write prototype.equals()
stream << "static QScriptValue qtscript_" << qtScriptFlagsName
<< "_equals(QScriptContext *context, QScriptEngine *engine)" << endl
<< "{" << endl
<< " QVariant thisObj = context->thisObject().toVariant();" << endl
<< " QVariant otherObj = context->argument(0).toVariant();" << endl
<< " return QScriptValue(engine, ((thisObj.userType() == otherObj.userType()) &&" << endl
<< " (thisObj.value<" << qualifiedFlagsName << ">() == otherObj.value<" << qualifiedFlagsName << ">())));" << endl
<< "}" << endl << endl;
// write class creation function
stream << "static QScriptValue qtscript_create_" << qtScriptFlagsName << "_class(QScriptEngine *engine)" << endl;
stream << "{" << endl;
stream << " QScriptValue ctor = qtscript_create_flags_class_helper(" << endl
<< " engine, qtscript_construct_" << qtScriptFlagsName
<< ", qtscript_" << qtScriptFlagsName << "_valueOf," << endl
<< " qtscript_" << qtScriptFlagsName << "_toString, qtscript_"
<< qtScriptFlagsName << "_equals);" << endl;
stream << " qScriptRegisterMetaType<" << qualifiedFlagsName << ">(engine, "
<< "qtscript_" << qtScriptFlagsName << "_toScriptValue," << endl
<< " qtscript_" << qtScriptFlagsName << "_fromScriptValue,"
<< " ctor.property(QString::fromLatin1(\"prototype\")));" << endl;
stream << " return ctor;" << endl;
stream << "}" << endl;
stream << endl;
}
/*!
Declares the given \a typeName if it hasn't been declared already,
and adds it to the set of registered type names.
*/
void maybeDeclareMetaType(QTextStream &stream, const QString &typeName,
QSet<QString> ®isteredTypeNames)
{
QString name = typeName;
if (name.endsWith(QLatin1Char('&')))
name.chop(1);
if (registeredTypeNames.contains(name) || (QMetaType::type(typeName.toLatin1()) != 0))
return;
if (name.contains(QLatin1Char(','))) {
// need to expand the Q_DECLARE_METATYPE macro manually,
// otherwise the compiler will choke
stream << "template <> \\" << endl
<< "struct QMetaTypeId< " << name << " > \\" << endl
<< "{ \\" << endl
<< " enum { Defined = 1 }; \\" << endl
<< " static int qt_metatype_id() \\" << endl
<< " { \\" << endl
<< " static QBasicAtomicInt metatype_id = Q_BASIC_ATOMIC_INITIALIZER(0); \\" << endl
<< " if (!metatype_id) \\" << endl
<< " metatype_id = qRegisterMetaType< " << name << " >(\"" << name << "\"); \\" << endl
<< " return metatype_id; \\" << endl
<< " } \\" << endl
<< "};" << endl;
} else {
stream << "Q_DECLARE_METATYPE(" << name << ")" << endl;
}
registeredTypeNames << name;
}
/*!
Declares the given \a type recursively (i.e. subtypes of a composite
type are also declared).
*/
static void declareTypeRecursive(QTextStream &stream, const AbstractMetaType *type,
QSet<QString> ®isteredTypeNames)
{
if (!type)
return;
QList<AbstractMetaType *> subTypes = type->instantiations();
for (int i = 0; i < subTypes.size(); ++i)
declareTypeRecursive(stream, subTypes.at(i), registeredTypeNames);
QString typeName = normalizedType(type);
if (typeName == QLatin1String("QStringList<QString>"))
return; // ### wtf...
maybeDeclareMetaType(stream, typeName, registeredTypeNames);
}
/*!
Declares the types associated with the given \a functions.
*/
void declareFunctionMetaTypes(QTextStream &stream, const AbstractMetaFunctionList &functions,
QSet<QString> ®isteredTypeNames)
{
for (int i = 0; i < functions.size(); ++i) {
AbstractMetaFunction *fun = functions.at(i);
if (isSpecialStreamingOperator(fun)) {
maybeDeclareMetaType(stream, fun->arguments().at(0)->type()->name() + "*",
registeredTypeNames);
continue;
}
AbstractMetaArgumentList arguments = fun->arguments();
for (int j = 0; j < arguments.size(); ++j) {
if (fun->argumentRemoved(j+1))
continue;
QString repl = fun->typeReplaced(j+1);
if (!repl.isEmpty()) {
maybeDeclareMetaType(stream, repl, registeredTypeNames);
} else {
const AbstractMetaArgument *arg = arguments.at(j);
declareTypeRecursive(stream, arg->type(), registeredTypeNames);
}
}
QString retRepl = fun->typeReplaced(0);
if (!retRepl.isEmpty())
maybeDeclareMetaType(stream, retRepl, registeredTypeNames);
else
declareTypeRecursive(stream, fun->type(), registeredTypeNames);
}
}
/*!
Returns true if we don't care about the given enum \a enom,
false otherwise.
*/
static bool shouldIgnoreEnum(const AbstractMetaEnum *enom)
{
return !enom->wasPublic() || (enom->name() == "enum_1");
}
/*!
Declares the types associated with the enums of the given \a
meta_class.
*/
void declareEnumMetaTypes(QTextStream &stream, const AbstractMetaClass *meta_class,
QSet<QString> ®isteredTypeNames)
{
AbstractMetaEnumList enums = meta_class->enums();
for (int i = 0; i < enums.size(); ++i) {
const AbstractMetaEnum *enom = enums.at(i);
if (shouldIgnoreEnum(enom))
continue;
if (meta_class->name() == "Global")
maybeDeclareMetaType(stream, enom->name(), registeredTypeNames);
else
maybeDeclareMetaType(stream, QString::fromLatin1("%0::%1")
.arg(meta_class->qualifiedCppName()).arg(enom->name()),
registeredTypeNames);
FlagsTypeEntry *flags = enom->typeEntry()->flags();
if (flags) {
maybeDeclareMetaType(stream, QString::fromLatin1("QFlags<%0::%1>")
.arg(meta_class->qualifiedCppName()).arg(enom->name()),
registeredTypeNames);
}
}
}
/*!
Returns the maximum function length among \a functions.
*/
static int maxFunctionLength(const AbstractMetaFunctionList &functions)
{
int result = 0;
for (int i = 0; i < functions.size(); ++i)
result = qMax(result, functions.at(i)->arguments().size());
return result;
}
/*!
Writes a prototype/static function.
*/
static void writeFunctionForwarding(QTextStream &stream, const AbstractMetaClass *meta_class,
const AbstractMetaFunctionList &functions)
{
#if 0
stream << "/** signatures:" << endl;
foreach (const AbstractMetaFunction *fun, functions) {
stream << " * " << fun->signature() << endl;
}
stream << " */" << endl;
#endif
QMap<int, AbstractMetaFunctionList> argcToFunctions;
argcToFunctions = createArgcToFunctionsMap(functions);
QSet<QString> signatures;
int argcMin = argcToFunctions.keys().first();
int argcMax = argcToFunctions.keys().last();
for (int i = argcMin; i <= argcMax; ++i) {
AbstractMetaFunctionList funcs = argcToFunctions.value(i);
if (funcs.isEmpty())
continue;
stream << " if (context->argumentCount() == " << i << ") {" << endl;
if (funcs.size() == 1 || i == 0) {
AbstractMetaFunction *fun = funcs.at(0);
const int indent = 8;
// special case for Q{Data,Text}Stream streaming operators
if (isSpecialStreamingOperator(fun))
writeStreamingOperatorCall(stream, fun, meta_class, indent);
else
writeFunctionCallAndReturn(stream, fun, i, meta_class, indent);
signatures.insert(fun->targetLangSignature());
} else {
// handle overloads
QStringList sigs;
for (int j = 0; j < funcs.size(); ++j) {
AbstractMetaFunction *fun = funcs.at(j);
sigs.append(fun->signature());
stream << " ";
if (j > 0)
stream << "} else ";
stream << "if (";
AbstractMetaArgumentList arguments = fun->arguments();
const int indent = 12;
writeArgumentTypeTests(stream, fun, arguments, i, indent);
stream << ") {" << endl;
writeFunctionCallAndReturn(stream, fun, i, meta_class, indent);
signatures.insert(fun->targetLangSignature());
}
stream << " }" << endl;
}
stream << " }" << endl;
}
}
static void writePrototypeCall(QTextStream &s, const AbstractMetaClass *meta_class,
const QMap<QString, AbstractMetaFunctionList> &nameToFunctions,
int prototypeFunctionsOffset)
{
s << "static QScriptValue qtscript_" << meta_class->name()
<< "_prototype_call(QScriptContext *context, QScriptEngine *)" << endl
<< "{" << endl;
s << "#if QT_VERSION > 0x040400" << endl;
s << " Q_ASSERT(context->callee().isFunction());" << endl
<< " uint _id = context->callee().data().toUInt32();" << endl;
s << "#else" << endl
<< " uint _id;" << endl
<< " if (context->callee().isFunction())" << endl
<< " _id = context->callee().data().toUInt32();" << endl
<< " else" << endl
<< " _id = 0xBABE0000 + " << nameToFunctions.size() << ";" << endl;
s << "#endif" << endl;
s << " Q_ASSERT((_id & 0xFFFF0000) == 0xBABE0000);" << endl
<< " _id &= 0x0000FFFF;" << endl;
// cast the thisObject to C++ type
s << " ";
#ifndef GENERATOR_NO_PROTECTED_FUNCTIONS
if (meta_class->hasProtectedFunctions())
s << "qtscript_";
#endif
s << meta_class->qualifiedCppName() << "* _q_self = ";
#ifndef GENERATOR_NO_PROTECTED_FUNCTIONS
if (meta_class->hasProtectedFunctions())
s << "reinterpret_cast<qtscript_" << meta_class->name() << "*>(";
#endif
s << "qscriptvalue_cast<" << meta_class->qualifiedCppName()
<< "*>(context->thisObject())";
#ifndef GENERATOR_NO_PROTECTED_FUNCTIONS
if (meta_class->hasProtectedFunctions())
s << ")";
#endif
s << ";" << endl
<< " if (!_q_self) {" << endl
<< " return context->throwError(QScriptContext::TypeError," << endl
<< " QString::fromLatin1(\"" << meta_class->name()
<< ".%0(): this object is not a " << meta_class->name() << "\")" << endl
<< " .arg(qtscript_" << meta_class->name()
<< "_function_names[_id+" << prototypeFunctionsOffset <<"]));" << endl
<< " }" << endl << endl;
s << " switch (_id) {" << endl;
QMap<QString, AbstractMetaFunctionList>::const_iterator it;
int index = 0;
for (it = nameToFunctions.constBegin(); it != nameToFunctions.constEnd(); ++it) {
s << " case " << index << ":" << endl;
writeFunctionForwarding(s, meta_class, it.value());
s << " break;" << endl << endl;
++index;
}
if (!meta_class->hasDefaultToStringFunction()) {
s << " case " << index << ": {" << endl;
s << " QString result";
FunctionModelItem fun = meta_class->hasToStringCapability();
if (fun) {
int indirections = fun->arguments().at(1)->type().indirections();
QString deref = QLatin1String(indirections == 0 ? "*" : "");
s << ";" << endl
<< " QDebug d(&result);" << endl
<< " d << " << deref << "_q_self;" << endl;
} else {
// ### FIXME: can cause compile error
// s << "=QString(\"" << meta_class->name() << "(0x%1)\").arg((int)_q_self, 0, 16);" << endl;
s << " = QString::fromLatin1(\"" << meta_class->name() << "\");" << endl;
}
s << " return QScriptValue(context->engine(), result);" << endl
<< " }" << endl << endl;
}
s << " default:" << endl
<< " Q_ASSERT(false);" << endl
<< " }" << endl;
s << " return qtscript_" << meta_class->name() << "_throw_ambiguity_error_helper(context," << endl
<< " qtscript_" << meta_class->name()
<< "_function_names[_id+" << prototypeFunctionsOffset << "]," << endl
<< " qtscript_" << meta_class->name()
<< "_function_signatures[_id+" << prototypeFunctionsOffset << "]);" << endl;
s << "}" << endl << endl;
}
static void writeStaticCall(QTextStream &s, const AbstractMetaClass *meta_class,
const AbstractMetaFunctionList &constructors,
const QMap<QString, AbstractMetaFunctionList> &nameToFunctions)
{
s << "static QScriptValue qtscript_" << meta_class->name()
<< "_static_call(QScriptContext *context, QScriptEngine *)" << endl
<< "{" << endl;
s << " uint _id = context->callee().data().toUInt32();" << endl
<< " Q_ASSERT((_id & 0xFFFF0000) == 0xBABE0000);" << endl
<< " _id &= 0x0000FFFF;" << endl;
s << " switch (_id) {" << endl;
s << " case 0:" << endl;
writeConstructorForwarding(s, constructors, meta_class);
s << " break;" << endl << endl;
QMap<QString, AbstractMetaFunctionList>::const_iterator it;
int index = 1;
for (it = nameToFunctions.constBegin(); it != nameToFunctions.constEnd(); ++it) {
s << " case " << index << ":" << endl;
writeFunctionForwarding(s, meta_class, it.value());
s << " break;" << endl << endl;
++index;
}
s << " default:" << endl
<< " Q_ASSERT(false);" << endl
<< " }" << endl;
s << " return qtscript_" << meta_class->name() << "_throw_ambiguity_error_helper(context," << endl
<< " qtscript_" << meta_class->name() << "_function_names[_id]," << endl
<< " qtscript_" << meta_class->name() << "_function_signatures[_id]);" << endl;
s << "}" << endl << endl;
}
/*!
Writes the include defined by \a inc to \a stream.
*/
void writeInclude(QTextStream &stream, const Include &inc)
{
if (inc.name.isEmpty())
return;
if (inc.type == Include::TargetLangImport)
return;
stream << "#include ";
if (inc.type == Include::IncludePath)
stream << "<";
else
stream << "\"";
stream << inc.name;
if (inc.type == Include::IncludePath)
stream << ">";
else
stream << "\"";
stream << endl;
}
static void writeHelperFunctions(QTextStream &stream, const AbstractMetaClass *meta_class)
{
stream << "static QScriptValue qtscript_" << meta_class->name() << "_throw_ambiguity_error_helper(" << endl
<< " QScriptContext *context, const char *functionName, const char *signatures)" << endl
<< "{" << endl
<< " QStringList lines = QString::fromLatin1(signatures).split(QLatin1Char('\\n'));" << endl
<< " QStringList fullSignatures;" << endl
<< " for (int i = 0; i < lines.size(); ++i)" << endl
<< " fullSignatures.append(QString::fromLatin1(\"%0(%1)\").arg(functionName).arg(lines.at(i)));" << endl
<< " return context->throwError(QString::fromLatin1(\"" << meta_class->name()
<< "::%0(): could not find a function match; candidates are:\\n%1\")" << endl
<< " .arg(functionName).arg(fullSignatures.join(QLatin1String(\"\\n\"))));" << endl
<< "}" << endl << endl;
}
void writeQtScriptQtBindingsLicense(QTextStream &stream)
{
stream
<< "/****************************************************************************" << endl
<< "**" << endl
<< "** Copyright (C) 2008 Trolltech ASA. All rights reserved." << endl
<< "**" << endl
<< "** This file is part of the Qt Script Qt Bindings project on Trolltech Labs." << endl
<< "**" << endl
<< "** This file may be used under the terms of the GNU General Public" << endl
<< "** License version 2.0 as published by the Free Software Foundation" << endl
<< "** and appearing in the file LICENSE.GPL included in the packaging of" << endl
<< "** this file. Please review the following information to ensure GNU" << endl
<< "** General Public Licensing requirements will be met:" << endl
<< "** http://www.trolltech.com/products/qt/opensource.html" << endl
<< "**" << endl
<< "** If you are unsure which license is appropriate for your use, please" << endl
<< "** review the following information:" << endl
<< "** http://www.trolltech.com/products/qt/licensing.html or contact the" << endl
<< "** sales department at sales@trolltech.com." << endl
<< "**" << endl
<< "** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE" << endl
<< "** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE." << endl
<< "**" << endl
<< "****************************************************************************/" << endl
<< endl;
}
/*!
Finds the functions in \a meta_class that we actually want to
generate bindings for.
*/
void findPrototypeAndStaticFunctions(
const AbstractMetaClass *meta_class,
QMap<QString, AbstractMetaFunctionList> &nameToPrototypeFunctions,
QMap<QString, AbstractMetaFunctionList> &nameToStaticFunctions)
{
AbstractMetaFunctionList functions = meta_class->functionsInTargetLang();
for (int i = 0; i < functions.size(); ++i) {
AbstractMetaFunction* func = functions.at(i);
if (!func->isNormal())
continue;
#ifdef GENERATOR_NO_PROTECTED_FUNCTIONS
if (func->wasProtected())
continue;
#endif
if (func->declaringClass() != meta_class)
continue; // function inherited through prototype
if (func->isPropertyReader() || func->isPropertyWriter())
continue; // no point in including property accessors
if (func->isSlot() || func->isSignal() || func->isInvokable())
continue; // no point in including signals and slots
QMap<QString, AbstractMetaFunctionList> &map =
func->isStatic() ? nameToStaticFunctions : nameToPrototypeFunctions;
map[func->modifiedName()].append(func);
}
}
static void writeFunctionSignaturesString(QTextStream &s, const AbstractMetaFunctionList &functions)
{
s << "\"";
for (int i = 0; i < functions.size(); ++i) {
if (i > 0)
s << "\\n";
QString sig = functions.at(i)->targetLangSignature();
sig = sig.mid(sig.indexOf('(') + 1);
sig.chop(1);
s << sig;
}
s << "\"";
}
/*!
Writes the whole native binding for the class \a meta_class.
*/
void ClassGenerator::write(QTextStream &stream, const AbstractMetaClass *meta_class)
{
if (FileOut::license)
writeQtScriptQtBindingsLicense(stream);
// write common includes
stream << "#include <QtScript/QScriptEngine>" << endl;
stream << "#include <QtScript/QScriptContext>" << endl;
stream << "#include <QtScript/QScriptValue>" << endl;
stream << "#include <QtCore/QStringList>" << endl;
stream << "#include <QtCore/QDebug>" << endl;
stream << "#include <qmetaobject.h>" << endl;
stream << endl;
// write class-specific includes
{
Include inc = meta_class->typeEntry()->include();
writeInclude(stream, inc);
}
{
IncludeList includes = meta_class->typeEntry()->extraIncludes();
qSort(includes.begin(), includes.end());
foreach (const Include &i, includes) {
writeInclude(stream, i);
}
}
stream << endl;
if (meta_class->generateShellClass()) {
stream << "#include \"qtscriptshell_" << meta_class->name() << ".h\"" << endl;
stream << endl;
}
AbstractMetaEnumList enums = meta_class->enums();
{
// kill the enums we don't care about
AbstractMetaEnumList::iterator it;
for (it = enums.begin(); it != enums.end(); ) {
if (shouldIgnoreEnum(*it))
it = enums.erase(it);
else
++it;
}
}
if (meta_class->isNamespace() || meta_class->name() == "Global") {
QMap<QString, Include> includes;
foreach (AbstractMetaEnum *enom, enums) {
Include include = enom->typeEntry()->include();
includes.insert(include.toString(), include);
}
foreach (const Include &i, includes) {
writeInclude(stream, i);
}
stream << endl;
}
if (meta_class->name() == "Global") {
stream << "class Global {};" << endl;
stream << endl;
}
// find constructors
AbstractMetaFunctionList ctors = findConstructors(meta_class);
bool hasDefaultCtor = findDefaultConstructor(ctors) != 0;
// find interesting functions
QMap<QString, AbstractMetaFunctionList> nameToPrototypeFunctions;
QMap<QString, AbstractMetaFunctionList> nameToStaticFunctions;
findPrototypeAndStaticFunctions(meta_class, nameToPrototypeFunctions, nameToStaticFunctions);
int staticFunctionsOffset = 1;
int prototypeFunctionsOffset = staticFunctionsOffset + nameToStaticFunctions.size();
// write table of function names
stream << "static const char * const qtscript_"
<< meta_class->name() << "_function_names[] = {" << endl;
stream << " \"" << meta_class->name() << "\"" << endl;
{
QMap<QString, AbstractMetaFunctionList>::const_iterator it;
stream << " // static" << endl;
for (it = nameToStaticFunctions.constBegin(); it != nameToStaticFunctions.constEnd(); ++it) {
stream << " , ";
stream << "\"" << it.key() << "\"" << endl;
}
stream << " // prototype" << endl;
for (it = nameToPrototypeFunctions.constBegin(); it != nameToPrototypeFunctions.constEnd(); ++it) {
QString functionName = it.key();
QString scriptName = functionName;
if (functionName == QLatin1String("operator_equal"))
scriptName = QLatin1String("equals");
stream << " , ";
stream << "\"" << scriptName << "\"" << endl;
}
if (!meta_class->hasDefaultToStringFunction())
stream << " , \"toString\"" << endl;
}
stream << "};" << endl << endl;
// write table of function signatures
stream << "static const char * const qtscript_"
<< meta_class->name() << "_function_signatures[] = {" << endl;
stream << " ";
writeFunctionSignaturesString(stream, ctors);
stream << endl;
{
QMap<QString, AbstractMetaFunctionList>::const_iterator it;
stream << " // static" << endl;
for (it = nameToStaticFunctions.constBegin(); it != nameToStaticFunctions.constEnd(); ++it) {
stream << " , ";
writeFunctionSignaturesString(stream, it.value());
stream << endl;
}
stream << " // prototype" << endl;
for (it = nameToPrototypeFunctions.constBegin(); it != nameToPrototypeFunctions.constEnd(); ++it) {
stream << " , ";
writeFunctionSignaturesString(stream, it.value());
stream << endl;
}
if (!meta_class->hasDefaultToStringFunction())
stream << "\"\"" << endl;
}
stream << "};" << endl << endl;
// write table of function lengths
stream << "static const int qtscript_" << meta_class->name() << "_function_lengths[] = {" << endl;
stream << " " << maxFunctionLength(ctors) << endl;
{
QMap<QString, AbstractMetaFunctionList>::const_iterator it;
stream << " // static" << endl;
for (it = nameToStaticFunctions.constBegin(); it != nameToStaticFunctions.constEnd(); ++it) {
stream << " , " << maxFunctionLength(it.value()) << endl;
}
stream << " // prototype" << endl;
for (it = nameToPrototypeFunctions.constBegin(); it != nameToPrototypeFunctions.constEnd(); ++it) {
stream << " , " << maxFunctionLength(it.value()) << endl;
}
if (!meta_class->hasDefaultToStringFunction())
stream << " , 0" << endl;
}
stream << "};" << endl << endl;
#ifndef GENERATOR_NO_PROTECTED_FUNCTIONS
if (meta_class->hasProtectedFunctions()) {
// write a friendly class
stream << "class qtscript_" << meta_class->name()
<< " : public " << meta_class->qualifiedCppName() << endl;
stream << "{" << endl;
for (int x = 0; x < 2; ++x) {
QMap<QString, AbstractMetaFunctionList> &map =
x ? nameToStaticFunctions : nameToPrototypeFunctions;
QMap<QString, AbstractMetaFunctionList>::const_iterator it;
for (it = map.constBegin(); it != map.constEnd(); ++it) {
AbstractMetaFunctionList functions = it.value();
for (int i = 0; i < functions.size(); ++i) {
if (functions.at(i)->isProtected()) {
stream << " friend QScriptValue qtscript_" << meta_class->name()
<< "_" << it.key();
if (functions.at(i)->isStatic())
stream << "_static";
stream << "(QScriptContext *, QScriptEngine *);" << endl;
break;
}
}
}
}
stream << "};" << endl;
stream << endl;
}
#endif
writeHelperFunctions(stream, meta_class);
// write metaobject getter if we need it
if (hasQEnums(enums) && (meta_class->qualifiedCppName() != "QTransform")) {
if (meta_class->qualifiedCppName() == "Qt") {
stream << "struct qtscript_Qt_metaObject_helper : private QObject" << endl
<< "{" << endl
<< " static const QMetaObject *get()" << endl
<< " { return &static_cast<qtscript_Qt_metaObject_helper*>(0)->staticQtMetaObject; }" << endl
<< "};" << endl << endl;
}
stream << "static const QMetaObject *qtscript_" << meta_class->name() << "_metaObject()" << endl
<< "{" << endl
<< " return ";
if (meta_class->qualifiedCppName() == "Qt")
stream << "qtscript_Qt_metaObject_helper::get()";
else
stream << "&" << meta_class->qualifiedCppName() << "::staticMetaObject";
stream << ";" << endl
<< "}" << endl << endl;
}
// write metatype declarations
{
QSet<QString> registeredTypeNames = m_qmetatype_declared_typenames;
if (!meta_class->isNamespace()) {
if (meta_class->typeEntry()->isValue() && hasDefaultCtor)
maybeDeclareMetaType(stream, meta_class->qualifiedCppName(), registeredTypeNames);
else
registeredTypeNames << meta_class->qualifiedCppName();
maybeDeclareMetaType(stream, meta_class->qualifiedCppName() + "*", registeredTypeNames);
}
if (meta_class->generateShellClass()) {
if (meta_class->typeEntry()->isValue()) {
maybeDeclareMetaType(stream, "QtScriptShell_" + meta_class->name(),
registeredTypeNames);
}
maybeDeclareMetaType(stream, "QtScriptShell_" + meta_class->name() + "*",
registeredTypeNames);
}
declareEnumMetaTypes(stream, meta_class, registeredTypeNames);
for (int x = 0; x < 2; ++x) {
QMap<QString, AbstractMetaFunctionList> &map =
x ? nameToStaticFunctions : nameToPrototypeFunctions;
QMap<QString, AbstractMetaFunctionList>::const_iterator it;
for (it = map.constBegin(); it != map.constEnd(); ++it) {
declareFunctionMetaTypes(stream, it.value(), registeredTypeNames);
}
}
declareFunctionMetaTypes(stream, ctors, registeredTypeNames);
if (meta_class->baseClass() != 0) {
maybeDeclareMetaType(stream, meta_class->baseClass()->qualifiedCppName()
+ QLatin1String("*"), registeredTypeNames);
}
foreach (AbstractMetaClass *iface, meta_class->interfaces()) {
AbstractMetaClass *impl = iface->primaryInterfaceImplementor();
maybeDeclareMetaType(stream, impl->qualifiedCppName() + QLatin1String("*"),
registeredTypeNames);
}
// ### hackety hack
if (meta_class->name().endsWith("Gradient"))
maybeDeclareMetaType(stream, "QGradient", registeredTypeNames);
stream << endl;
}
writeInjectedCode(stream, meta_class, CodeSnip::Beginning);
// write enum classes
if (!enums.isEmpty()) {
writeCreateEnumClassHelper(stream);
if (hasFlags(enums))
writeCreateFlagsClassHelper(stream);
for (int i = 0; i < enums.size(); ++i) {
const AbstractMetaEnum *enom = enums.at(i);
writeEnumClass(stream, meta_class, enom);
}
}
stream << "//" << endl;
stream << "// " << meta_class->name() << endl;
stream << "//" << endl << endl;
if (!meta_class->isNamespace()) {
if (!nameToPrototypeFunctions.isEmpty() || !meta_class->hasDefaultToStringFunction())
writePrototypeCall(stream, meta_class, nameToPrototypeFunctions, prototypeFunctionsOffset);
}
writeStaticCall(stream, meta_class, ctors, nameToStaticFunctions);
if (isQObjectBased(meta_class)) {
// write C++ <--> script conversion functions
stream << "static QScriptValue qtscript_" << meta_class->name() << "_toScriptValue(QScriptEngine *engine, "
<< meta_class->qualifiedCppName() << "* const &in)" << endl
<< "{" << endl
<< " return engine->newQObject(in, QScriptEngine::QtOwnership, QScriptEngine::PreferExistingWrapperObject);" << endl
<< "}" << endl << endl;
stream << "static void qtscript_" << meta_class->name() << "_fromScriptValue(const QScriptValue &value, "
<< meta_class->qualifiedCppName() << "* &out)" << endl
<< "{" << endl
<< " out = qobject_cast<" << meta_class->qualifiedCppName() << "*>(value.toQObject());" << endl
<< "}" << endl << endl;
}
//
// write exported function that creates the QtScript class
//
stream << "QScriptValue qtscript_create_" << meta_class->name()
<< "_class(QScriptEngine *engine)" << endl;
stream << "{" << endl;
// setup prototype
if (!meta_class->isNamespace()) {
stream << " engine->setDefaultPrototype(qMetaTypeId<"
<< meta_class->qualifiedCppName() << "*>(), QScriptValue());" << endl;
stream << " QScriptValue proto = engine->newVariant(qVariantFromValue(("
<< meta_class->qualifiedCppName() << "*)0));" << endl;
bool havePrototypePrototype = false;
if (meta_class->baseClass() != 0) {
stream << " proto.setPrototype(engine->defaultPrototype(qMetaTypeId<"
<< meta_class->baseClass()->qualifiedCppName() << "*>()));" << endl;
havePrototypePrototype = true;
}
foreach (AbstractMetaClass *iface, meta_class->interfaces()) {
AbstractMetaClass *impl = iface->primaryInterfaceImplementor();
if (impl == meta_class)
continue;
if (!havePrototypePrototype) {
stream << " proto.setPrototype(engine->defaultPrototype(qMetaTypeId<"
<< impl->qualifiedCppName() << "*>()));" << endl;
havePrototypePrototype = true;
} else {
// alternative would be to copy the properties from the secondary
// prototype to the primary prototype.
stream << " proto.setProperty(QString::fromLatin1(\"__"
<< impl->name() << "__\")," << endl
<< " engine->defaultPrototype(qMetaTypeId<"
<< impl->qualifiedCppName() << "*>())," << endl
<< " QScriptValue::SkipInEnumeration);" << endl;
}
}
if (!nameToPrototypeFunctions.isEmpty()) {
QMap<QString, AbstractMetaFunctionList>::const_iterator it;
int count = nameToPrototypeFunctions.size();
if (!meta_class->hasDefaultToStringFunction())
++count;
stream << " for (int i = 0; i < " << count << "; ++i) {" << endl
<< " QScriptValue fun = engine->newFunction(qtscript_"
<< meta_class->name() << "_prototype_call, qtscript_"
<< meta_class->name() << "_function_lengths[i+"
<< prototypeFunctionsOffset << "]);" << endl
<< " fun.setData(QScriptValue(engine, uint(0xBABE0000 + i)));" << endl
<< " proto.setProperty(QString::fromLatin1(qtscript_"
<< meta_class->name() << "_function_names[i+" << prototypeFunctionsOffset << "])," << endl
<< " fun, QScriptValue::SkipInEnumeration);" << endl
<< " }" << endl;
}
writeInjectedCode(stream, meta_class, CodeSnip::PrototypeInitialization);
stream << endl;
// register the prototype
// stream << " qDebug() << \"registering " << meta_class->name() << " prototype\";" << endl;
if (meta_class->typeEntry()->isValue() && hasDefaultCtor) {
stream << " engine->setDefaultPrototype(qMetaTypeId<"
<< meta_class->qualifiedCppName() << ">(), proto);" << endl;
}
if (isQObjectBased(meta_class)) {
stream << " qScriptRegisterMetaType<" << meta_class->qualifiedCppName() << "*>(engine, qtscript_"
<< meta_class->name() << "_toScriptValue, " << endl << " qtscript_"
<< meta_class->name() << "_fromScriptValue, proto);" << endl;
} else {
stream << " engine->setDefaultPrototype(qMetaTypeId<"
<< meta_class->qualifiedCppName() << "*>(), proto);" << endl;
}
stream << endl;
} else {
stream << " QScriptValue proto = QScriptValue();" << endl;
}
// setup constructor
stream << " QScriptValue ctor = engine->newFunction(qtscript_" << meta_class->name()
<< "_static_call, proto, qtscript_" << meta_class->name() << "_function_lengths[0]);" << endl;
stream << " ctor.setData(QScriptValue(engine, uint(0xBABE0000 + 0)));" << endl;
if (!nameToStaticFunctions.isEmpty()) {
// static functions
QMap<QString, AbstractMetaFunctionList>::const_iterator it;
stream << " for (int i = 0; i < " << nameToStaticFunctions.size() << "; ++i) {" << endl
<< " QScriptValue fun = engine->newFunction(qtscript_" << meta_class->name()
<< "_static_call," << endl
<< " qtscript_" << meta_class->name() << "_function_lengths[i+" << staticFunctionsOffset << "]);" << endl
<< " fun.setData(QScriptValue(engine, uint(0xBABE0000 + i+1)));" << endl
<< " ctor.setProperty(QString::fromLatin1(qtscript_"
<< meta_class->name() << "_function_names[i+" << staticFunctionsOffset << "])," << endl
<< " fun, QScriptValue::SkipInEnumeration);" << endl
<< " }" << endl;
}
stream << endl;
// enums and flags classes
{
for (int i = 0; i < enums.size(); ++i) {
const AbstractMetaEnum *enom = enums.at(i);
stream << " ctor.setProperty(QString::fromLatin1(\""
<< enom->name() << "\")," << endl
<< " qtscript_create_" << meta_class->name()
<< "_" << enom->name() << "_class(engine, ctor));" << endl;
FlagsTypeEntry *flags = enom->typeEntry()->flags();
if (flags) {
stream << " ctor.setProperty(QString::fromLatin1(\""
<< flags->targetLangName() << "\")," << endl
<< " qtscript_create_" << meta_class->name()
<< "_" << flags->targetLangName() << "_class(engine));" << endl;
}
}
}
writeInjectedCode(stream, meta_class, CodeSnip::ConstructorInitialization);
stream << " return ctor;" << endl;
stream << "}" << endl;
writeInjectedCode(stream, meta_class, CodeSnip::End);
QString packName = meta_class->package().replace(".", "_");
priGenerator->addSource(packName, fileNameForClass(meta_class));
setupGenerator->addClass(meta_class);
}
|