aboutsummaryrefslogtreecommitdiffstats
path: root/src/qmlcompiler/qqmljstyperesolver.cpp
blob: 92da98650e576ee5b624bb7709c35ab4711a3871 (plain)
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
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
// Qt-Security score:significant

#include "qqmljstyperesolver_p.h"

#include "qqmljsimporter_p.h"
#include "qqmljsimportvisitor_p.h"
#include "qqmljslogger_p.h"
#include "qqmljsutils_p.h"
#include <private/qv4value_p.h>

#include <private/qduplicatetracker_p.h>

#include <QtCore/qloggingcategory.h>

QT_BEGIN_NAMESPACE

using namespace Qt::StringLiterals;

Q_STATIC_LOGGING_CATEGORY(lcTypeResolver, "qt.qml.compiler.typeresolver", QtInfoMsg);

static inline void assertExtension(const QQmlJSScope::ConstPtr &type, QLatin1String extension)
{
    Q_ASSERT(type);
    Q_ASSERT(type->extensionType().scope->internalName() == extension);
    Q_ASSERT(type->extensionIsJavaScript());
}

QQmlJSTypeResolver::QQmlJSTypeResolver(QQmlJSImporter *importer)
    : m_pool(std::make_unique<QQmlJSRegisterContentPool>())
    , m_imports(importer->builtinInternalNames())
{
    const QQmlJSImporter::ImportedTypes &builtinTypes = m_imports;

    m_voidType = builtinTypes.type(u"void"_s).scope;
    assertExtension(m_voidType, "undefined"_L1);

    m_nullType = builtinTypes.type(u"std::nullptr_t"_s).scope;
    Q_ASSERT(m_nullType);

    m_realType = builtinTypes.type(u"double"_s).scope;
    assertExtension(m_realType, "Number"_L1);

    m_floatType = builtinTypes.type(u"float"_s).scope;
    assertExtension(m_floatType, "Number"_L1);

    m_int8Type = builtinTypes.type(u"qint8"_s).scope;
    assertExtension(m_int8Type, "Number"_L1);

    m_uint8Type = builtinTypes.type(u"quint8"_s).scope;
    assertExtension(m_uint8Type, "Number"_L1);

    m_int16Type = builtinTypes.type(u"short"_s).scope;
    assertExtension(m_int16Type, "Number"_L1);

    m_uint16Type = builtinTypes.type(u"ushort"_s).scope;
    assertExtension(m_uint16Type, "Number"_L1);

    m_int32Type = builtinTypes.type(u"int"_s).scope;
    assertExtension(m_int32Type, "Number"_L1);

    m_uint32Type = builtinTypes.type(u"uint"_s).scope;
    assertExtension(m_uint32Type, "Number"_L1);

    m_int64Type = builtinTypes.type(u"qlonglong"_s).scope;
    Q_ASSERT(m_int64Type);

    m_uint64Type = builtinTypes.type(u"qulonglong"_s).scope;
    Q_ASSERT(m_uint64Type);

    m_sizeType = builtinTypes.type(u"qsizetype"_s).scope;
    assertExtension(m_sizeType, "Number"_L1);

    // qsizetype is either a 32bit or a 64bit signed integer. We don't want to special-case it.
    Q_ASSERT(m_sizeType == m_int32Type || m_sizeType == m_int64Type);

    m_boolType = builtinTypes.type(u"bool"_s).scope;
    assertExtension(m_boolType, "Boolean"_L1);

    m_stringType = builtinTypes.type(u"QString"_s).scope;
    assertExtension(m_stringType, "String"_L1);

    m_stringListType = builtinTypes.type(u"QStringList"_s).scope;
    assertExtension(m_stringListType, "Array"_L1);

    m_byteArrayType = builtinTypes.type(u"QByteArray"_s).scope;
    assertExtension(m_byteArrayType, "ArrayBuffer"_L1);

    m_urlType = builtinTypes.type(u"QUrl"_s).scope;
    assertExtension(m_urlType, "URL"_L1);

    m_dateTimeType = builtinTypes.type(u"QDateTime"_s).scope;
    assertExtension(m_dateTimeType, "Date"_L1);

    m_dateType = builtinTypes.type(u"QDate"_s).scope;
    Q_ASSERT(m_dateType);

    m_timeType = builtinTypes.type(u"QTime"_s).scope;
    Q_ASSERT(m_timeType);

    m_regexpType = builtinTypes.type(u"QRegularExpression"_s).scope;
    Q_ASSERT(m_regexpType);

    m_variantListType = builtinTypes.type(u"QVariantList"_s).scope;
    assertExtension(m_variantListType, "Array"_L1);

    m_variantMapType = builtinTypes.type(u"QVariantMap"_s).scope;
    Q_ASSERT(m_variantMapType);
    m_varType = builtinTypes.type(u"QVariant"_s).scope;
    Q_ASSERT(m_varType);

    m_qmlPropertyMapType = builtinTypes.type(u"QQmlPropertyMap"_s).scope;
    Q_ASSERT(m_qmlPropertyMapType);

    m_jsValueType = builtinTypes.type(u"QJSValue"_s).scope;
    Q_ASSERT(m_jsValueType);

    m_qObjectType = builtinTypes.type(u"QObject"_s).scope;
    assertExtension(m_qObjectType, "Object"_L1);

    m_qObjectListType = builtinTypes.type(u"QObjectList"_s).scope;
    assertExtension(m_qObjectListType, "Array"_L1);

    m_qQmlScriptStringType = builtinTypes.type(u"QQmlScriptString"_s).scope;
    Q_ASSERT(m_qQmlScriptStringType);

    m_functionType = builtinTypes.type(u"function"_s).scope;
    Q_ASSERT(m_functionType);

    m_numberPrototype = builtinTypes.type(u"NumberPrototype"_s).scope;
    Q_ASSERT(m_numberPrototype);

    m_arrayPrototype = builtinTypes.type(u"ArrayPrototype"_s).scope;
    Q_ASSERT(m_arrayPrototype);

    m_listPropertyType = m_qObjectType->listType();
    Q_ASSERT(m_listPropertyType->internalName() == u"QQmlListProperty<QObject>"_s);
    Q_ASSERT(m_listPropertyType->accessSemantics() == QQmlJSScope::AccessSemantics::Sequence);
    Q_ASSERT(m_listPropertyType->elementTypeName() == u"QObject"_s);
    assertExtension(m_listPropertyType, "Array"_L1);

    QQmlJSScope::Ptr emptyType = QQmlJSScope::create();
    emptyType->setAccessSemantics(QQmlJSScope::AccessSemantics::None);
    m_emptyType = emptyType;

    QQmlJSScope::Ptr jsPrimitiveType = QQmlJSScope::create();
    jsPrimitiveType->setInternalName(u"QJSPrimitiveValue"_s);
    jsPrimitiveType->setFilePath(u"qjsprimitivevalue.h"_s);
    jsPrimitiveType->setAccessSemantics(QQmlJSScope::AccessSemantics::Value);
    m_jsPrimitiveType = jsPrimitiveType;

    QQmlJSScope::Ptr metaObjectType = QQmlJSScope::create();
    metaObjectType->setInternalName(u"const QMetaObject"_s);
    metaObjectType->setFilePath(u"qmetaobject.h"_s);
    metaObjectType->setAccessSemantics(QQmlJSScope::AccessSemantics::Reference);
    m_metaObjectType = metaObjectType;

    m_jsGlobalObject = importer->jsGlobalObject();

    QQmlJSScope::Ptr forInIteratorPtr = QQmlJSScope::create();
    forInIteratorPtr->setAccessSemantics(QQmlJSScope::AccessSemantics::Value);
    forInIteratorPtr->setFilePath(u"qjslist.h"_s);
    forInIteratorPtr->setInternalName(u"QJSListForInIterator::Ptr"_s);
    m_forInIteratorPtr = forInIteratorPtr;

    QQmlJSScope::Ptr forOfIteratorPtr = QQmlJSScope::create();
    forOfIteratorPtr->setAccessSemantics(QQmlJSScope::AccessSemantics::Value);
    forOfIteratorPtr->setFilePath(u"qjslist.h"_s);
    forOfIteratorPtr->setInternalName(u"QJSListForOfIterator::Ptr"_s);
    m_forOfIteratorPtr = forOfIteratorPtr;

    // We use this as scope type quite often, and it should always be the same scope type.
    m_jsGlobalObjectContent = m_pool->createType(
            m_jsGlobalObject, QQmlJSRegisterContent::InvalidLookupIndex,
            QQmlJSRegisterContent::ScopeObject);
}

/*!
    \internal

    Initializes the type resolver. As part of that initialization, makes \a
    visitor traverse the program when given.
*/
void QQmlJSTypeResolver::init(QQmlJSImportVisitor *visitor, QQmlJS::AST::Node *program)
{
    m_logger = visitor->logger();

    m_objectsById.clear();
    m_objectsByLocation.clear();
    m_imports.clear();
    m_signalHandlers.clear();

    if (program)
        program->accept(visitor);

    m_objectsById = visitor->addressableScopes();
    m_objectsByLocation = visitor->scopesBylocation();
    m_signalHandlers = visitor->signalHandlers();
    m_imports = visitor->imports();
    m_seenModuleQualifiers = visitor->seenModuleQualifiers();
}

QQmlJSScope::ConstPtr QQmlJSTypeResolver::mathObject() const
{
    return jsGlobalObject()->property(u"Math"_s).type();
}

QQmlJSScope::ConstPtr QQmlJSTypeResolver::consoleObject() const
{
    return jsGlobalObject()->property(u"console"_s).type();
}

QQmlJSScope::ConstPtr
QQmlJSTypeResolver::scopeForLocation(const QV4::CompiledData::Location &location) const
{
    // #if required for standalone DOM compilation against Qt 6.2
    qCDebug(lcTypeResolver()).nospace()
            << "looking for object at " << location.line() << ':' << location.column();
    return m_objectsByLocation[location];
}

QQmlJSScope::ConstPtr QQmlJSTypeResolver::typeFromAST(QQmlJS::AST::Type *type) const
{
    const QString typeId = QmlIR::IRBuilder::asString(type->typeId);
    if (!type->typeArgument)
        return m_imports.type(typeId).scope;
    if (typeId == u"list"_s) {
        if (const QQmlJSScope::ConstPtr typeArgument = typeForName(type->typeArgument->toString()))
            return typeArgument->listType();
    }
    return QQmlJSScope::ConstPtr();
}

QQmlJSScope::ConstPtr QQmlJSTypeResolver::typeForConst(QV4::ReturnedValue rv) const
{
    QV4::Value value = QV4::Value::fromReturnedValue(rv);
    if (value.isUndefined())
        return voidType();

    if (value.isInt32())
        return int32Type();

    if (value.isBoolean())
        return boolType();

    if (value.isDouble())
        return realType();

    if (value.isNull())
        return nullType();

    if (value.isEmpty())
        return emptyType();

    return {};
}

QQmlJSRegisterContent
QQmlJSTypeResolver::typeForBinaryOperation(QSOperator::Op oper, QQmlJSRegisterContent left,
                                           QQmlJSRegisterContent right) const
{
    Q_ASSERT(left.isValid());
    Q_ASSERT(right.isValid());

    switch (oper) {
    case QSOperator::Op::Equal:
    case QSOperator::Op::NotEqual:
    case QSOperator::Op::StrictEqual:
    case QSOperator::Op::StrictNotEqual:
    case QSOperator::Op::Lt:
    case QSOperator::Op::Gt:
    case QSOperator::Op::Ge:
    case QSOperator::Op::In:
    case QSOperator::Op::Le:
        return operationType(boolType());
    case QSOperator::Op::BitAnd:
    case QSOperator::Op::BitOr:
    case QSOperator::Op::BitXor:
    case QSOperator::Op::LShift:
    case QSOperator::Op::RShift:
        return operationType(int32Type());
    case QSOperator::Op::URShift:
        return operationType(uint32Type());
    case QSOperator::Op::Add: {
        const auto leftContents = left.containedType();
        const auto rightContents = right.containedType();
        if (leftContents == stringType() || rightContents == stringType())
            return operationType(stringType());

        const QQmlJSScope::ConstPtr result = merge(leftContents, rightContents);
        if (result == boolType())
            return operationType(int32Type());
        if (isNumeric(result))
            return operationType(realType());

        return operationType(jsPrimitiveType());
    }
    case QSOperator::Op::Sub:
    case QSOperator::Op::Mul:
    case QSOperator::Op::Exp: {
        const QQmlJSScope::ConstPtr result = merge(left.containedType(), right.containedType());
        return operationType(result == boolType() ? int32Type() : realType());
    }
    case QSOperator::Op::Div:
    case QSOperator::Op::Mod:
        return operationType(realType());
    case QSOperator::Op::As:
        return operationType(right.containedType());
    default:
        break;
    }

    return operationType(merge(left.containedType(), right.containedType()));
}

QQmlJSRegisterContent QQmlJSTypeResolver::typeForArithmeticUnaryOperation(
        UnaryOperator op, QQmlJSRegisterContent operand) const
{
    switch (op) {
    case UnaryOperator::Not:
        return operationType(boolType());
    case UnaryOperator::Complement:
        return operationType(int32Type());
    case UnaryOperator::Plus:
        if (isIntegral(operand))
            return operationType(operand.containedType());
        Q_FALLTHROUGH();
    default:
        if (operand.containedType() == boolType())
            return operationType(int32Type());
        break;
    }

    return operationType(realType());
}

bool QQmlJSTypeResolver::isPrimitive(QQmlJSRegisterContent type) const
{
    return isPrimitive(type.containedType());
}

bool QQmlJSTypeResolver::isNumeric(QQmlJSRegisterContent type) const
{
    return isNumeric(type.containedType());
}

bool QQmlJSTypeResolver::isIntegral(QQmlJSRegisterContent type) const
{
    return isIntegral(type.containedType());
}

bool QQmlJSTypeResolver::isIntegral(const QQmlJSScope::ConstPtr &type) const
{
    return isSignedInteger(type) || isUnsignedInteger(type);
}

bool QQmlJSTypeResolver::isPrimitive(const QQmlJSScope::ConstPtr &type) const
{
    return (isNumeric(type) && type != m_int64Type && type != m_uint64Type)
            || type == m_boolType   || type == m_voidType || type == m_nullType
            || type == m_stringType || type == m_jsPrimitiveType;
}

bool QQmlJSTypeResolver::isNumeric(const QQmlJSScope::ConstPtr &type) const
{
    if (!type) // should this be a precondition instead?
        return false;

    if (type->scopeType() == QQmlJSScope::ScopeType::EnumScope)
        return true;

    if (type == m_realType)
        return true;
    if (type == m_floatType)
        return true;
    if (type == m_int8Type)
        return true;
    if (type == m_uint8Type)
        return true;
    if (type == m_int16Type)
        return true;
    if (type == m_uint16Type)
        return true;
    if (type == m_int32Type)
        return true;
    if (type == m_uint32Type)
        return true;
    if (type == m_int64Type)
        return true;
    if (type == m_uint64Type)
        return true;
    // sizetype is covered by one of the above cases (int32 or int64)
    // booleans are not numeric

    // the number prototype is numeric
    if (type == m_numberPrototype)
        return true;

    // and types directly inheriting from it, notably number, are also
    // numeric
    if (type->baseType() == m_numberPrototype)
        return true;

    // it isn't possible (for users) to derive from m_numberPrototpye,
    // so we know the list above is exhaustive / we don't need to go up
    // further in the inheritance chain

    return false;
}

bool QQmlJSTypeResolver::isSignedInteger(const QQmlJSScope::ConstPtr &type) const
{
    return type == m_int8Type || type == m_int16Type
            || type == m_int32Type || type == m_int64Type;
}

bool QQmlJSTypeResolver::isUnsignedInteger(const QQmlJSScope::ConstPtr &type) const
{
    return type == m_uint8Type || type == m_uint16Type
            || type == m_uint32Type || type == m_uint64Type;
}

bool QQmlJSTypeResolver::isNativeArrayIndex(const QQmlJSScope::ConstPtr &type) const
{
    return type == m_uint8Type || type == m_int8Type || type == m_uint16Type || type == m_int16Type
            || type == m_uint32Type || type == m_int32Type;
}

QQmlJSScope::ConstPtr QQmlJSTypeResolver::containedTypeForName(const QString &name) const
{
    QQmlJSScope::ConstPtr type = typeForName(name);

    if (!type || type->isSingleton() || type->isScript())
        return type;

    switch (type->accessSemantics()) {
    case QQmlJSScope::AccessSemantics::Reference:
        if (const auto attached = type->attachedType())
            return genericType(attached) ? attached : QQmlJSScope::ConstPtr();
        return metaObjectType();
    case QQmlJSScope::AccessSemantics::None:
        return metaObjectType();
    case QQmlJSScope::AccessSemantics::Sequence:
    case QQmlJSScope::AccessSemantics::Value:
        return canAddressValueTypes() ?  metaObjectType() : QQmlJSScope::ConstPtr();
    }

    Q_UNREACHABLE_RETURN(QQmlJSScope::ConstPtr());
}

QQmlJSRegisterContent QQmlJSTypeResolver::registerContentForName(
        const QString &name, QQmlJSRegisterContent scopeType) const
{
    QQmlJSScope::ConstPtr type = typeForName(name);
    if (!type)
        return QQmlJSRegisterContent();

    if (type->isSingleton()) {
        return m_pool->createType(
                type, QQmlJSRegisterContent::InvalidLookupIndex,
                QQmlJSRegisterContent::Singleton, scopeType);
    }

    if (type->isScript()) {
        return m_pool->createType(
                type, QQmlJSRegisterContent::InvalidLookupIndex,
                QQmlJSRegisterContent::Script, scopeType);
    }

    const QQmlJSRegisterContent namedType = m_pool->createType(
            type, QQmlJSRegisterContent::InvalidLookupIndex, QQmlJSRegisterContent::TypeByName,
            scopeType);

    if (const auto attached = type->attachedType()) {
        if (!genericType(attached)) {
            m_logger->log(u"Cannot resolve generic base of attached %1"_s.arg(
                                  attached->internalName()),
                          qmlCompiler, attached->sourceLocation());
            return {};
        } else if (type->accessSemantics() != QQmlJSScope::AccessSemantics::Reference) {
            m_logger->log(u"Cannot retrieve attached object for non-reference type %1"_s.arg(
                                  type->internalName()),
                          qmlCompiler, type->sourceLocation());
            return {};
        } else {
            // We don't know yet whether we need the attached or the plain object. In direct
            // mode, we will figure this out using the scope type and access any enums of the
            // plain type directly. In indirect mode, we can use enum lookups.
            return m_pool->createType(
                        attached, QQmlJSRegisterContent::InvalidLookupIndex,
                        QQmlJSRegisterContent::Attachment, namedType);
        }
    }

    switch (type->accessSemantics()) {
    case QQmlJSScope::AccessSemantics::None:
    case QQmlJSScope::AccessSemantics::Reference:
        // A plain reference to a non-singleton, non-attached type.
        // We may still need the plain type reference for enum lookups,
        // Store it as QMetaObject.
        // This only works with namespaces and object types.
        return m_pool->createType(
                metaObjectType(), QQmlJSRegisterContent::InvalidLookupIndex,
                QQmlJSRegisterContent::MetaType, namedType);
    case QQmlJSScope::AccessSemantics::Sequence:
    case QQmlJSScope::AccessSemantics::Value:
        if (scopeType.isImportNamespace() || canAddressValueTypes()) {
            return m_pool->createType(
                    metaObjectType(), QQmlJSRegisterContent::InvalidLookupIndex,
                    QQmlJSRegisterContent::MetaType, namedType);
        }
        // Else this is not actually a type reference. You cannot get the metaobject
        // of a value type in QML and sequences don't even have metaobjects.
        break;
    }

    return QQmlJSRegisterContent();
}

QQmlJSRegisterContent QQmlJSTypeResolver::original(QQmlJSRegisterContent type) const
{
    QQmlJSRegisterContent result = type.original();
    return result.isNull() ? type : result;
}

QQmlJSScope::ConstPtr QQmlJSTypeResolver::originalContainedType(
        QQmlJSRegisterContent container) const
{
    return original(container).containedType();
}

bool QQmlJSTypeResolver::adjustTrackedType(
        QQmlJSRegisterContent tracked, const QQmlJSScope::ConstPtr &conversion) const
{
    if (m_cloneMode == QQmlJSTypeResolver::DoNotCloneTypes)
        return true;

    QQmlJSScope::ConstPtr contained = tracked.containedType();
    QQmlJSScope::ConstPtr result = conversion;

    // Do not adjust to the JavaScript extension of the original type. Rather keep the original
    // type in that case.
    QQmlJSUtils::searchBaseAndExtensionTypes(
            contained, [&](const QQmlJSScope::ConstPtr &scope, QQmlJSScope::ExtensionKind kind) {
        if (kind != QQmlJSScope::ExtensionJavaScript || scope != result)
            return false;
        result = contained;
        return true;
    });


    // If we cannot convert to the new type without the help of e.g. lookupResultMetaType(),
    // we better not change the type.
    if (!canPrimitivelyConvertFromTo(contained, result)
        && !canPopulate(result, contained, nullptr)
        && !selectConstructor(result, contained, nullptr).isValid()) {
        return false;
    }

    m_pool->adjustType(tracked, result);
    return true;
}

bool QQmlJSTypeResolver::adjustTrackedType(
        QQmlJSRegisterContent tracked, QQmlJSRegisterContent conversion) const
{
    return adjustTrackedType(tracked, conversion.containedType());
}

bool QQmlJSTypeResolver::adjustTrackedType(
        QQmlJSRegisterContent tracked, const QList<QQmlJSRegisterContent> &conversions) const
{
    if (m_cloneMode == QQmlJSTypeResolver::DoNotCloneTypes)
        return true;

    QQmlJSScope::ConstPtr result;
    for (QQmlJSRegisterContent type : conversions)
        result = merge(type.containedType(), result);

    return adjustTrackedType(tracked, result);
}

void QQmlJSTypeResolver::adjustOriginalType(
        QQmlJSRegisterContent tracked, const QQmlJSScope::ConstPtr &conversion) const
{
    if (m_cloneMode == QQmlJSTypeResolver::DoNotCloneTypes)
        return;

    m_pool->generalizeType(tracked, conversion);
}

void QQmlJSTypeResolver::generalizeType(QQmlJSRegisterContent type) const
{
    if (m_cloneMode == QQmlJSTypeResolver::DoNotCloneTypes)
        return;

    for (QQmlJSRegisterContent orig = type; !orig.isNull(); orig = orig.original()) {
        if (!orig.shadowed().isValid())
            m_pool->generalizeType(orig, genericType(orig.containedType()));
    }
}

bool QQmlJSTypeResolver::canConvertFromTo(const QQmlJSScope::ConstPtr &from,
                                          const QQmlJSScope::ConstPtr &to) const
{
    if (canPrimitivelyConvertFromTo(from, to)
            || canPopulate(to, from, nullptr)
            || selectConstructor(to, from, nullptr).isValid()) {
        return true;
    }

    // ### need a generic solution for custom cpp types:
    // if (from->m_hasBoolOverload && equals(to, boolType))
    //    return true;

    // All of these types have QString conversions that require a certain format
    // TODO: Actually verify these strings or deprecate them.
    //       Some of those type are builtins or should be builtins. We should add code for them
    //       in QQmlJSCodeGenerator::conversion().
    if (from == m_stringType && !to.isNull()) {
        const QString toTypeName = to->internalName();
        if (toTypeName == u"QPoint"_s || toTypeName == u"QPointF"_s
                || toTypeName == u"QSize"_s || toTypeName == u"QSizeF"_s
                || toTypeName == u"QRect"_s || toTypeName == u"QRectF"_s) {
            return true;
        }
    }

    return false;
}

bool QQmlJSTypeResolver::canConvertFromTo(QQmlJSRegisterContent from,
                                          QQmlJSRegisterContent to) const
{
    return canConvertFromTo(from.containedType(), to.containedType());
}

static QQmlJSRegisterContent::ContentVariant mergeVariants(QQmlJSRegisterContent::ContentVariant a,
                                                           QQmlJSRegisterContent::ContentVariant b)
{
    return (a == b) ? a : QQmlJSRegisterContent::Unknown;
}

QQmlJSRegisterContent QQmlJSTypeResolver::merge(
        QQmlJSRegisterContent a, QQmlJSRegisterContent b) const
{
    Q_ASSERT(a != b);

    // We cannot easily provide an operator< for QQmlJSRegisterContent.
    // Therefore we use qHash and operator== here to deduplicate. That's somewhat inefficient.
    QSet<QQmlJSRegisterContent> origins;

    QQmlJSRegisterContent aResultScope;
    if (a.isConversion()) {
        const auto aOrigins = a.conversionOrigins();
        for (const auto &aOrigin : aOrigins)
            origins.insert(aOrigin);
        aResultScope = a.conversionResultScope();
    } else {
        origins.insert(a);
        aResultScope = a.scope();
    }

    QQmlJSRegisterContent bResultScope;
    if (b.isConversion()) {
        const auto bOrigins = b.conversionOrigins();
        for (const auto &bOrigin : bOrigins)
            origins.insert(bOrigin);
        bResultScope = b.conversionResultScope();
    } else {
        origins.insert(b);
        bResultScope = b.scope();
    }

    const auto mergeScopes = [&](QQmlJSRegisterContent a, QQmlJSRegisterContent b) {
        // If they are the same, we don't want to re-track them.
        // We want the repetition on type mismatches to converge.
        return (a == b) ? a : merge(a, b);
    };

    return m_pool->createConversion(
            origins.values(),
            merge(a.containedType(), b.containedType()),
            mergeScopes(aResultScope, bResultScope),
            mergeVariants(a.variant(), b.variant()),
            mergeScopes(a.scope(), b.scope()));
}

QQmlJSScope::ConstPtr QQmlJSTypeResolver::merge(const QQmlJSScope::ConstPtr &a,
                                                const QQmlJSScope::ConstPtr &b) const
{
    if (a.isNull())
        return b;

    if (b.isNull())
        return a;

    const auto baseOrExtension
            = [](const QQmlJSScope::ConstPtr &a, const QQmlJSScope::ConstPtr &b) {
        QQmlJSScope::ConstPtr found;
        QQmlJSUtils::searchBaseAndExtensionTypes(
                a, [&](const QQmlJSScope::ConstPtr &scope, QQmlJSScope::ExtensionKind kind) {
            switch (kind) {
            case QQmlJSScope::NotExtension:
                // If b inherits scope, then scope is a common base type of a and b
                if (b->inherits(scope)) {
                    found = scope;
                    return true;
                }
                break;
            case QQmlJSScope::ExtensionJavaScript:
                // Merging a type with its JavaScript extension produces the type.
                // Giving the JavaScript extension as type to be read means we expect any type
                // that fulfills the given JavaScript interface
                if (scope == b) {
                    found = a;
                    return true;
                }
                break;
            case QQmlJSScope::ExtensionType:
            case QQmlJSScope::ExtensionNamespace:
                break;
            }
            return false;
        });
        return found;
    };

    if (a == b)
        return a;

    if (a == jsValueType() || a == varType())
        return a;
    if (b == jsValueType() || b == varType())
        return b;

    const auto isInt32Compatible = [&](const QQmlJSScope::ConstPtr &type) {
        return (isIntegral(type)
                    && type != uint32Type()
                    && type != int64Type()
                    && type != uint64Type())
                || type == boolType();
    };

    if (isInt32Compatible(a) && isInt32Compatible(b))
        return int32Type();

    const auto isUInt32Compatible = [&](const QQmlJSScope::ConstPtr &type) {
        return (isUnsignedInteger(type) && type != uint64Type()) || type == boolType();
    };

    if (isUInt32Compatible(a) && isUInt32Compatible(b))
        return uint32Type();

    if (isNumeric(a) && isNumeric(b))
        return realType();

    if (isPrimitive(a) && isPrimitive(b))
        return jsPrimitiveType();

    if (const auto base = baseOrExtension(a, b))
        return base;

    if (const auto base = baseOrExtension(b, a))
        return base;

    if ((a == nullType() || a == boolType()) && b->isReferenceType())
        return b;

    if ((b == nullType() || b == boolType()) && a->isReferenceType())
        return a;

    return varType();
}

bool QQmlJSTypeResolver::canHold(
        const QQmlJSScope::ConstPtr &container, const QQmlJSScope::ConstPtr &contained) const
{
    if (container == contained || container == m_varType || container == m_jsValueType)
        return true;

    if (container == m_jsPrimitiveType)
        return isPrimitive(contained);

    if (container == m_variantListType)
        return contained->accessSemantics() == QQmlJSScope::AccessSemantics::Sequence;

    if (container == m_qObjectListType || container == m_listPropertyType) {
        if (contained->accessSemantics() != QQmlJSScope::AccessSemantics::Sequence)
            return false;
        if (QQmlJSScope::ConstPtr element = contained->elementType())
            return element->isReferenceType();
        return false;
    }

    if (QQmlJSUtils::searchBaseAndExtensionTypes(
                container, [&](const QQmlJSScope::ConstPtr &base) {
        return base == contained;
    })) {
        return true;
    }

    if (container->isReferenceType()) {
        if (QQmlJSUtils::searchBaseAndExtensionTypes(
                    contained, [&](const QQmlJSScope::ConstPtr &base) {
            return base == container;
        })) {
            return true;
        }
    }

    return false;
}


bool QQmlJSTypeResolver::canHoldUndefined(QQmlJSRegisterContent content) const
{
    const auto canBeUndefined = [this](const QQmlJSScope::ConstPtr &type) {
        return type == m_voidType || type == m_varType
                || type == m_jsValueType || type == m_jsPrimitiveType;
    };

    if (!canBeUndefined(content.containedType()))
        return false;

    if (!content.isConversion())
        return true;

    const auto origins = content.conversionOrigins();
    for (const auto &origin : origins) {
        if (canBeUndefined(originalContainedType(origin)))
            return true;
    }

    return false;
}

bool QQmlJSTypeResolver::isOptionalType(QQmlJSRegisterContent content) const
{
    if (!content.isConversion())
        return false;

    const auto origins = content.conversionOrigins();
    if (origins.length() != 2)
        return false;

    // Conversion origins are always adjusted to the conversion result. None of them will be void.
    // Therefore, retrieve the originals first.

    return original(origins[0]).contains(m_voidType) || original(origins[1]).contains(m_voidType);
}

QQmlJSRegisterContent QQmlJSTypeResolver::extractNonVoidFromOptionalType(
        QQmlJSRegisterContent content) const
{
    if (!isOptionalType(content))
        return QQmlJSRegisterContent();

    // Conversion origins are always adjusted to the conversion result. None of them will be void.
    // Therefore, retrieve the originals first.

    auto origins = content.conversionOrigins();
    std::transform(origins.cbegin(), origins.cend(), origins.begin(),
                   [this](QQmlJSRegisterContent content) {return original(content);});
    const QQmlJSRegisterContent result = origins[0].contains(m_voidType)
            ? origins[1]
            : origins[0];

    // The result may still be undefined. You can write "undefined ?? undefined ?? 1"
    return result;
}

QQmlJSScope::ConstPtr QQmlJSTypeResolver::genericType(
        const QQmlJSScope::ConstPtr &type,
        ComponentIsGeneric allowComponent) const
{
    if (type->isScript())
        return m_jsValueType;

    if (type == m_metaObjectType)
        return m_metaObjectType;

    if (type->accessSemantics() == QQmlJSScope::AccessSemantics::Reference) {
        QString unresolvedBaseTypeName;
        for (auto base = type; base;) {
            // QObject and QQmlComponent are the two required base types.
            // Any QML type system has to define those, or use the ones from builtins.
            // As QQmlComponent is derived from QObject, we can restrict ourselves to the latter.
            // This results in less if'ery when retrieving a QObject* from somewhere and deciding
            // what it is.
            if (base->internalName() == u"QObject"_s) {
                return base;
            } else if (allowComponent == ComponentIsGeneric::Yes
                       && base->internalName() == u"QQmlComponent"_s) {
                return base;
            }

            if (auto baseBase = base->baseType()) {
                base = baseBase;
            } else {
                unresolvedBaseTypeName = base->baseTypeName();
                break;
            }
        }

        // Reference types that are not QObject or QQmlComponent are likely JavaScript objects.
        // We don't want to deal with those, but m_jsValueType is the best generic option.
        if (type->filePath().isEmpty())
            return m_jsValueType;

        m_logger->log(u"Object type %1 is not derived from QObject or QQmlComponent. "
                      "You may need to fully qualify all names in C++ so that moc can see them. "
                      "You may also need to add qt_extract_metatypes(<target containing %2>)."_s
                      .arg(type->internalName(), unresolvedBaseTypeName),
                      qmlCompiler, type->sourceLocation());

        // If it does have a filePath, it's some C++ type which we haven't fully resolved.
        return m_jsValueType;
    }

    if (type->isListProperty())
        return m_listPropertyType;

    if (type->scopeType() == QQmlSA::ScopeType::EnumScope)
        return type->baseType();

    if (isPrimitive(type)) {
        // If the filePath is set, the type is storable and we can just return it.
        if (!type->filePath().isEmpty())
            return type;

        // If the type is JavaScript's 'number' type, it's not directly storable, but still
        // primitive. We use C++ 'double' then.
        if (isNumeric(type))
            return m_realType;

        // Otherwise we use QJSPrimitiveValue.
        // TODO: JavaScript's 'string' and 'boolean' could be special-cased here.
        return m_jsPrimitiveType;
    }

    for (const QQmlJSScope::ConstPtr &builtin : {
                 m_realType, m_floatType, m_int8Type, m_uint8Type, m_int16Type, m_uint16Type,
                 m_int32Type, m_uint32Type, m_int64Type, m_uint64Type, m_boolType, m_stringType,
                 m_stringListType, m_byteArrayType, m_urlType, m_dateTimeType, m_dateType,
                 m_timeType, m_variantListType, m_variantMapType, m_varType, m_jsValueType,
                 m_jsPrimitiveType, m_listPropertyType, m_qObjectType, m_qObjectListType,
                 m_metaObjectType, m_forInIteratorPtr, m_forOfIteratorPtr }) {
        if (type == builtin || type == builtin->listType())
            return type;
    }

    return m_varType;
}

/*!
 * \internal
 * The type of a JavaScript literal value appearing in script code
 */
QQmlJSRegisterContent QQmlJSTypeResolver::literalType(const QQmlJSScope::ConstPtr &type) const
{
    return m_pool->createType(
            type, QQmlJSRegisterContent::InvalidLookupIndex, QQmlJSRegisterContent::Literal);
}

/*!
 * \internal
 * The type of the result of a JavaScript operation
 */
QQmlJSRegisterContent QQmlJSTypeResolver::operationType(const QQmlJSScope::ConstPtr &type) const
{
    return m_pool->createType(
            type, QQmlJSRegisterContent::InvalidLookupIndex, QQmlJSRegisterContent::Operation);
}

/*!
 * \internal
 * A type named explicitly, for example in "as"-casts or as function annotation.
 */
QQmlJSRegisterContent QQmlJSTypeResolver::namedType(const QQmlJSScope::ConstPtr &type) const
{
    return m_pool->createType(
            type, QQmlJSRegisterContent::InvalidLookupIndex, QQmlJSRegisterContent::TypeByName);
}

QQmlJSRegisterContent QQmlJSTypeResolver::syntheticType(const QQmlJSScope::ConstPtr &type) const
{
    return m_pool->createType(
            type, QQmlJSRegisterContent::InvalidLookupIndex, QQmlJSRegisterContent::Unknown);
}

static QQmlJSRegisterContent::ContentVariant scopeContentVariant(QQmlJSScope::ExtensionKind mode,
                                                                 bool isMethod)
{
    switch (mode) {
    case QQmlJSScope::NotExtension:
    case QQmlJSScope::ExtensionType:
    case QQmlJSScope::ExtensionJavaScript:
        return isMethod
                ? QQmlJSRegisterContent::Method
                : QQmlJSRegisterContent::Property;
    case QQmlJSScope::ExtensionNamespace:
        break;
    }
    Q_UNREACHABLE_RETURN(QQmlJSRegisterContent::Unknown);
}

static bool isRevisionAllowed(int memberRevision, const QQmlJSScope::ConstPtr &scope)
{
    Q_ASSERT(scope->isComposite());
    const QTypeRevision revision = QTypeRevision::fromEncodedVersion(memberRevision);

    // If the memberRevision is either invalid or 0.0, then everything is allowed.
    if (!revision.isValid() || revision == QTypeRevision::zero())
        return true;

    const QTypeRevision typeRevision = QQmlJSScope::nonCompositeBaseRevision(
                {scope->baseType(), scope->baseTypeRevision()});

    // If the revision is not valid, we haven't found a non-composite base type.
    // There is nothing we can say about the property then.
    return typeRevision.isValid() && typeRevision >= revision;
}

QQmlJSScope::ConstPtr QQmlJSTypeResolver::resolveParentProperty(
        const QString &name, const QQmlJSScope::ConstPtr &base,
        const QQmlJSScope::ConstPtr &propType) const
{
    if (m_parentMode != UseDocumentParent || name != base->parentPropertyName())
        return propType;

    const QQmlJSScope::ConstPtr baseParent = base->parentScope();
    if (!baseParent || !baseParent->inherits(propType))
        return propType;

    const QString defaultPropertyName = baseParent->defaultPropertyName();
    if (defaultPropertyName.isEmpty()) // no reason to search for bindings
        return propType;

    const QList<QQmlJSMetaPropertyBinding> defaultPropBindings
            = baseParent->propertyBindings(defaultPropertyName);
    for (const QQmlJSMetaPropertyBinding &binding : defaultPropBindings) {
        if (binding.bindingType() == QQmlSA::BindingType::Object && binding.objectType() == base)
            return baseParent;
    }

    return propType;
}

/*!
 * \internal
 *
 * Retrieves the type of whatever \a name signifies in the given \a scope.
 * \a name can be an ID, a property of the scope, a singleton, an attachment,
 * a plain type reference or a JavaScript global.
 *
 * TODO: The lookup is actually wrong. We cannot really retrieve JavaScript
 *       globals here because any runtime-inserted context property would
 *       override them. We still do because we don't have a better solution for
 *       identifying e.g. the console object, yet.
 *
 * \a options tells us whether to consider components as bound. If components
 * are bound we can retrieve objects identified by ID in outer contexts.
 *
 * TODO: This is also wrong because we should alternate scopes and contexts when
 *       traveling the scope/context hierarchy. Currently we have IDs from any
 *       context override all scope properties if components are considered
 *       bound. This is mostly because we don't care about outer scopes at all;
 *       so we cannot determine with certainty whether an ID from a far outer
 *       context is overridden by a property of a near outer scope. To
 *       complicate this further, user context properties can also be inserted
 *       in outer contexts at run time, shadowing names in further removed outer
 *       scopes and contexts. What we need to do is determine where exactly what
 *       kind of property can show up and defend against that with additional
 *       pragmas.
 *
 * Note: It probably takes at least 3 nested bound components in one document to
 *       trigger the misbehavior.
 */
QQmlJSScope::ConstPtr QQmlJSTypeResolver::scopedType(
        const QQmlJSScope::ConstPtr &scope, const QString &name,
        QQmlJSScopesByIdOptions options) const
{
    QQmlJSScopesById::CertainCallback<QQmlJSScope::ConstPtr> identified;
    if (m_objectsById.possibleScopes(name, scope, options, identified)
            != QQmlJSScopesById::Success::Yes) {
        // Could not determine component boundaries
        return {};
    }

    if (identified.result) {
        // Found a definite match
        return identified.result;
    }

    if (QQmlJSScope::ConstPtr base = QQmlJSScope::findCurrentQMLScope(scope)) {
        QQmlJSScope::ConstPtr result;
        if (QQmlJSUtils::searchBaseAndExtensionTypes(
                    base, [&](const QQmlJSScope::ConstPtr &found, QQmlJSScope::ExtensionKind mode) {
            if (mode == QQmlJSScope::ExtensionNamespace) // no use for it here
                return false;

            if (found->hasOwnProperty(name)) {
                const QQmlJSMetaProperty prop = found->ownProperty(name);
                if (!isRevisionAllowed(prop.revision(), scope))
                    return false;

                result = resolveParentProperty(name, base, prop.type());
                return true;
            }

            if (found->hasOwnMethod(name)) {
                const auto methods = found->ownMethods(name);
                for (const auto &method : methods) {
                    if (isRevisionAllowed(method.revision(), scope)) {
                        result = jsValueType();
                        return true;
                    }
                }
            }

            return false;
        })) {
            return result;
        }
    }

    if (QQmlJSScope::ConstPtr result = containedTypeForName(name))
        return result;

    if (m_jsGlobalObject->hasProperty(name))
        return m_jsGlobalObject->property(name).type();

    if (m_jsGlobalObject->hasMethod(name))
        return jsValueType();

    return {};
}

/*!
 * \internal
 *
 * Same as the other scopedType method, but accepts a QQmlJSRegisterContent and
 * also returns one. This way you not only get the type, but also the content
 * variant and various meta info.
 */
QQmlJSRegisterContent QQmlJSTypeResolver::scopedType(QQmlJSRegisterContent scope,
                                                     const QString &name, int lookupIndex,
                                                     QQmlJSScopesByIdOptions options) const
{
    const QQmlJSScope::ConstPtr contained = scope.containedType();

    QQmlJSScopesById::CertainCallback<QQmlJSScope::ConstPtr> identified;
    if (m_objectsById.possibleScopes(name, contained, options, identified)
            != QQmlJSScopesById::Success::Yes) {
        // Could not determine component boundaries
        return {};
    }

    if (identified.result) {
        // Found a definite match
        return m_pool->createType(
                identified.result, lookupIndex, QQmlJSRegisterContent::ObjectById, scope);
    }

    if (QQmlJSScope::ConstPtr base = QQmlJSScope::findCurrentQMLScope(contained)) {
        QQmlJSRegisterContent result;
        if (QQmlJSUtils::searchBaseAndExtensionTypes(
                    base, [&](const QQmlJSScope::ConstPtr &found, QQmlJSScope::ExtensionKind mode) {
            if (mode == QQmlJSScope::ExtensionNamespace) // no use for it here
                return false;

            const QQmlJSRegisterContent resultScope = mode == QQmlJSScope::NotExtension
                    ? scope
                    : extensionType(found, scope);

            if (found->hasOwnProperty(name)) {
                QQmlJSMetaProperty prop = found->ownProperty(name);
                if (!isRevisionAllowed(prop.revision(), contained))
                    return false;

                prop.setType(resolveParentProperty(name, base, prop.type()));
                result = m_pool->createProperty(
                        prop, QQmlJSRegisterContent::InvalidLookupIndex, lookupIndex,
                        scopeContentVariant(mode, false), resultScope);
                return true;
            }

            if (found->hasOwnMethod(name)) {
                auto methods = found->ownMethods(name);
                for (auto it = methods.begin(); it != methods.end();) {
                    if (!isRevisionAllowed(it->revision(), contained))
                        it = methods.erase(it);
                    else
                        ++it;
                }
                if (methods.isEmpty())
                    return false;
                result = m_pool->createMethod(
                        methods, jsValueType(), scopeContentVariant(mode, true), resultScope);
                return true;
            }

            // Unqualified enums are not allowed
            return false;
        })) {
            return result;
        }
    }

    QQmlJSRegisterContent result = registerContentForName(name, scope);

    if (result.isValid())
        return result;

    if (m_jsGlobalObject->hasProperty(name)) {
        return m_pool->createProperty(
                m_jsGlobalObject->property(name), QQmlJSRegisterContent::InvalidLookupIndex,
                lookupIndex, QQmlJSRegisterContent::Property, m_jsGlobalObjectContent);
    } else if (m_jsGlobalObject->hasMethod(name)) {
        return m_pool->createMethod(
                m_jsGlobalObject->methods(name), jsValueType(),
                QQmlJSRegisterContent::Property, m_jsGlobalObjectContent);
    }

    return {};
}

/*!
 * \fn QQmlJSScope::ConstPtr typeForId(const QQmlJSScope::ConstPtr &scope, const QString &name, QQmlJSScopesByIdOptions options) const
 *
 * \internal
 *
 * Same as scopedType(), but assumes that the \a name is an ID and only searches
 * the context.
 *
 * TODO: This is just as wrong as scopedType() in that it disregards both scope
 *       properties overriding context properties and run time context
 *       properties.
 */

bool QQmlJSTypeResolver::checkEnums(
        QQmlJSRegisterContent scope, const QString &name,
        QQmlJSRegisterContent *result) const
{
    // You can't have lower case enum names in QML, even if we know the enums here.
    if (name.isEmpty() || !name.at(0).isUpper())
        return false;

    const auto enums = scope.containedType()->ownEnumerations();
    for (const auto &enumeration : enums) {
        if ((enumeration.isScoped() || enumeration.isQml()) && enumeration.name() == name) {
            *result = m_pool->createEnumeration(
                    enumeration, QString(),
                    QQmlJSRegisterContent::Enum,
                    scope);
            return true;
        }

        if ((!enumeration.isScoped() || enumeration.isQml()
             || !scope.containedType()->enforcesScopedEnums()) && enumeration.hasKey(name)) {
            *result = m_pool->createEnumeration(
                    enumeration, name,
                    QQmlJSRegisterContent::Enum,
                    scope);
            return true;
        }
    }

    return false;
}

bool QQmlJSTypeResolver::canPopulate(
        const QQmlJSScope::ConstPtr &type, const QQmlJSScope::ConstPtr &passedArgumentType,
        bool *isExtension) const
{
    // TODO: We could allow QVariantMap and QVariantHash to be populated, but that needs extra
    //       code in the code generator.

    if (type.isNull()
            || canHold(passedArgumentType, type)
            || isPrimitive(passedArgumentType)
            || type->accessSemantics() != QQmlJSScope::AccessSemantics::Value
            || !type->isStructured()) {
        return false;
    }

    if (isExtension)
        *isExtension = !type->extensionType().scope.isNull();

    return true;
}

QQmlJSMetaMethod QQmlJSTypeResolver::selectConstructor(
        const QQmlJSScope::ConstPtr &type, const QQmlJSScope::ConstPtr &passedArgumentType,
        bool *isExtension) const
{
    // If the "from" type can hold the target type, we should not try to coerce
    // it to any constructor argument.
    if (type.isNull()
            || canHold(passedArgumentType, type)
            || type->accessSemantics() != QQmlJSScope::AccessSemantics::Value
            || !type->isCreatable()) {
        return QQmlJSMetaMethod();
    }

    auto doSelectConstructor = [&](const QQmlJSScope::ConstPtr &type) {
        QQmlJSMetaMethod candidate;

        const auto ownMethods = type->ownMethods();
        for (const QQmlJSMetaMethod &method : ownMethods) {
            if (!method.isConstructor())
                continue;

            const auto index = method.constructorIndex();
            Q_ASSERT(index != QQmlJSMetaMethod::RelativeFunctionIndex::Invalid);

            const auto methodArguments = method.parameters();
            if (methodArguments.size() != 1)
                continue;

            const QQmlJSScope::ConstPtr methodArgumentType = methodArguments[0].type();

            if (passedArgumentType == methodArgumentType)
                return method;

            // Do not select further ctors here. We don't want to do multi-step construction as that
            // is confusing and easily leads to infinite recursion.
            if (!candidate.isValid()
                && canPrimitivelyConvertFromTo(passedArgumentType, methodArgumentType)) {
                candidate = method;
            }
        }

        return candidate;
    };

    if (QQmlJSScope::ConstPtr extension = type->extensionType().scope) {
        const QQmlJSMetaMethod ctor = doSelectConstructor(extension);
        if (ctor.isValid()) {
            if (isExtension)
                *isExtension = true;
            return ctor;
        }
    }

    if (isExtension)
        *isExtension = false;

    return doSelectConstructor(type);
}

bool QQmlJSTypeResolver::areEquivalentLists(
        const QQmlJSScope::ConstPtr &a, const QQmlJSScope::ConstPtr &b) const
{
    const QQmlJSScope::ConstPtr equivalentLists[2][2] = {
        { m_stringListType, m_stringType->listType() },
        { m_variantListType, m_varType->listType() }
    };

    for (const auto eq : equivalentLists) {
        if ((a == eq[0] && b == eq[1]) || (a == eq[1] && b == eq[0]))
            return true;
    }

    return false;
}

bool QQmlJSTypeResolver::isTriviallyCopyable(const QQmlJSScope::ConstPtr &type) const
{
    // pointers are trivially copyable
    if (type->isReferenceType())
        return true;

    // Enum values are trivially copyable
    if (type->scopeType() == QQmlSA::ScopeType::EnumScope)
        return true;

    for (const QQmlJSScope::ConstPtr &trivial : {
            m_nullType, m_voidType,
            m_boolType, m_metaObjectType,
            m_realType, m_floatType,
            m_int8Type, m_uint8Type,
            m_int16Type, m_uint16Type,
            m_int32Type, m_uint32Type,
            m_int64Type, m_uint64Type }) {
        if (type == trivial)
            return true;
    }

    return false;
}

bool QQmlJSTypeResolver::inherits(const QQmlJSScope::ConstPtr &derived, const QQmlJSScope::ConstPtr &base) const
{
    const bool matchByName = !base->isComposite();
    for (QQmlJSScope::ConstPtr derivedBase = derived; derivedBase;
            derivedBase = derivedBase->baseType()) {
        if (derivedBase == base)
            return true;
        if (matchByName
                && !derivedBase->isComposite()
                && derivedBase->internalName() == base->internalName()) {
            return true;
        }
    }
    return false;
}

bool QQmlJSTypeResolver::canPrimitivelyConvertFromTo(
        const QQmlJSScope::ConstPtr &from, const QQmlJSScope::ConstPtr &to) const
{
    if (from == to)
        return true;
    if (from == m_varType || to == m_varType)
        return true;
    if (from == m_jsValueType || to == m_jsValueType)
        return true;
    if (to == m_qQmlScriptStringType)
        return true;
    if (isNumeric(from) && isNumeric(to))
        return true;
    // We can convert everything to bool.
    if (to == m_boolType)
        return true;

    if (from->accessSemantics() == QQmlJSScope::AccessSemantics::Reference
            && to == m_stringType) {
        return true;
    }

    // Yes, our String has number constructors.
    if (isNumeric(from) && to == m_stringType)
        return true;

    // We can convert strings to numbers, but not to enums
    if (from == m_stringType && isNumeric(to))
        return to->scopeType() != QQmlJSScope::ScopeType::EnumScope;

    // We can always convert between strings and urls.
    if ((from == m_stringType && to == m_urlType)
            || (from == m_urlType && to == m_stringType)) {
        return true;
    }

    // We can always convert between strings and byte arrays.
    if ((from == m_stringType && to == m_byteArrayType)
            || (from == m_byteArrayType && to == m_stringType)) {
        return true;
    }

    if (to == m_voidType)
        return true;

    if (to.isNull())
        return from == m_voidType;

    const auto types = { m_dateTimeType, m_dateType, m_timeType, m_stringType };
    for (const auto &originType : types) {
        if (from != originType)
            continue;

        for (const auto &targetType : types) {
            if (to == targetType)
                return true;
        }

        if (to == m_realType)
            return true;

        break;
    }

    if (from == m_nullType && to->accessSemantics() == QQmlJSScope::AccessSemantics::Reference)
        return true;

    if (from == m_jsPrimitiveType) {
        // You can cast any primitive to a nullptr
        return isPrimitive(to) || to->accessSemantics() == QQmlJSScope::AccessSemantics::Reference;
    }

    if (to == m_jsPrimitiveType)
        return isPrimitive(from);

    const bool matchByName = !to->isComposite();
    Q_ASSERT(!matchByName || !to->internalName().isEmpty());
    if (QQmlJSUtils::searchBaseAndExtensionTypes(
            from, [&](const QQmlJSScope::ConstPtr &scope, QQmlJSScope::ExtensionKind kind) {
        switch (kind) {
        case QQmlJSScope::NotExtension:
        case QQmlJSScope::ExtensionJavaScript:
            // Converting to a base type is trivially supported.
            // Converting to the JavaScript extension of a type just produces the type itself.
            // Giving the JavaScript extension as type to be converted to means we expect any
            // result that fulfills the given JavaScript interface.
            return scope == to
                    || (matchByName && scope->internalName() == to->internalName());
        case QQmlJSScope::ExtensionType:
        case QQmlJSScope::ExtensionNamespace:
            break;
        }
        return false;
    })) {
        return true;
    }

    if (from == m_variantListType)
        return to->accessSemantics() == QQmlJSScope::AccessSemantics::Sequence;

    // We can convert anything that fits into QJSPrimitiveValue
    if (canConvertFromTo(from, m_jsPrimitiveType) && canConvertFromTo(m_jsPrimitiveType, to))
        return true;

    if (areEquivalentLists(from, to))
        return true;

    if (from->isListProperty()
            && to->accessSemantics() == QQmlJSScope::AccessSemantics::Sequence
            && canConvertFromTo(from->elementType(), to->elementType())) {
        return true;
    }

    // it is possible to assing a singlar object to a list property if it could be stored in the list
    if (to->accessSemantics() == QQmlJSScope::AccessSemantics::Sequence
            && from->accessSemantics()  == QQmlJSScope::AccessSemantics::Reference
            && from->inherits(to->elementType())) {
        return true;
    }

    if (to == m_stringType && from->accessSemantics() == QQmlJSScope::AccessSemantics::Sequence)
        return canConvertFromTo(from->elementType(), m_stringType);

    return false;
}

QQmlJSRegisterContent QQmlJSTypeResolver::lengthProperty(
        bool isWritable, QQmlJSRegisterContent scope) const
{
    QQmlJSMetaProperty prop;
    prop.setPropertyName(u"length"_s);
    prop.setTypeName(u"qsizetype"_s);
    prop.setType(sizeType());
    prop.setIsWritable(isWritable);
    return m_pool->createProperty(
            prop, QQmlJSRegisterContent::InvalidLookupIndex,
            QQmlJSRegisterContent::InvalidLookupIndex, QQmlJSRegisterContent::Property, scope);
}

QQmlJSRegisterContent QQmlJSTypeResolver::memberType(
        QQmlJSRegisterContent type, const QString &name, int baseLookupIndex,
        int resultLookupIndex) const
{
    QQmlJSRegisterContent result;
    const QQmlJSScope::ConstPtr contained = type.containedType();

    // If we got a plain type reference we have to check the enums of the _scope_.
    if (contained == metaObjectType())
        return memberEnumType(type.scope(), name);

    if (contained == variantMapType() || contained->inherits(qmlPropertyMapType())) {
        QQmlJSMetaProperty prop;
        prop.setPropertyName(name);
        prop.setTypeName(u"QVariant"_s);
        prop.setType(varType());
        prop.setIsWritable(true);
        return m_pool->createProperty(
                prop, baseLookupIndex, resultLookupIndex,
                QQmlJSRegisterContent::Property, type);
    }

    if (contained == jsValueType()) {
        QQmlJSMetaProperty prop;
        prop.setPropertyName(name);
        prop.setTypeName(u"QJSValue"_s);
        prop.setType(jsValueType());
        prop.setIsWritable(true);
        return m_pool->createProperty(
                prop, baseLookupIndex, resultLookupIndex,
                QQmlJSRegisterContent::Property, type);
    }

    if ((contained == stringType()
            || contained->accessSemantics() == QQmlJSScope::AccessSemantics::Sequence)
            && name == u"length"_s) {
        return lengthProperty(contained != stringType(), type);
    }

    const auto check = [&](const QQmlJSScope::ConstPtr &scope, QQmlJSScope::ExtensionKind mode) {
        const QQmlJSRegisterContent resultScope = mode == QQmlJSScope::NotExtension
                ? baseType(scope, type)
                : extensionType(scope, type);

        if (mode != QQmlJSScope::ExtensionNamespace) {
            if (scope->hasOwnProperty(name)) {
                const auto prop = scope->ownProperty(name);
                result = m_pool->createProperty(
                        prop, baseLookupIndex, resultLookupIndex,
                        QQmlJSRegisterContent::Property, resultScope);
                return true;
            }

            if (scope->hasOwnMethod(name)) {
                const auto methods = scope->ownMethods(name);
                result = m_pool->createMethod(
                        methods, jsValueType(), QQmlJSRegisterContent::Method, resultScope);
                return true;
            }
        }

        return checkEnums(resultScope, name, &result);
    };

    if (QQmlJSUtils::searchBaseAndExtensionTypes(type.containedType(), check))
        return result;

    for (auto scope = contained;
         scope && (QQmlSA::isFunctionScope(scope->scopeType())
                   || scope->scopeType() == QQmlSA::ScopeType::JSLexicalScope);
         scope = scope->parentScope()) {
        if (auto ownIdentifier = scope->ownJSIdentifier(name)) {
            QQmlJSMetaProperty prop;
            prop.setPropertyName(name);
            prop.setTypeName(u"QJSValue"_s);
            prop.setType(jsValueType());
            prop.setIsWritable(!(ownIdentifier.value().isConst));

            return m_pool->createProperty(
                    prop, baseLookupIndex, resultLookupIndex,
                    QQmlJSRegisterContent::Property,
                    parentScope(scope, type));
        }
    }

    // check enums before checking attached types of attached types (chained attached types)
    if (type.isType()) {
        if (auto result = memberEnumType(type.scope(), name); result.isValid())
            return result;
    }

    if (QQmlJSScope::ConstPtr attachedBase = typeForName(name)) {
        if (QQmlJSScope::ConstPtr attached = attachedBase->attachedType()) {
            if (!genericType(attached)) {
                m_logger->log(u"Cannot resolve generic base of attached %1"_s.arg(
                                      attached->internalName()),
                              qmlCompiler, attached->sourceLocation());
                return {};
            } else if (contained->accessSemantics() != QQmlJSScope::AccessSemantics::Reference) {
                m_logger->log(u"Cannot retrieve attached object for non-reference type %1"_s.arg(
                                      contained->internalName()),
                              qmlCompiler, contained->sourceLocation());
                return {};
            } else {
                const QQmlJSRegisterContent namedType = m_pool->createType(
                        attachedBase, QQmlJSRegisterContent::InvalidLookupIndex,
                        QQmlJSRegisterContent::TypeByName, type);

                return m_pool->createType(
                        attached, resultLookupIndex, QQmlJSRegisterContent::Attachment,
                        namedType);
            }
        }
    }

    return {};
}

QQmlJSRegisterContent QQmlJSTypeResolver::memberEnumType(
        QQmlJSRegisterContent type, const QString &name) const
{
    QQmlJSRegisterContent result;

    if (QQmlJSUtils::searchBaseAndExtensionTypes(
                type.containedType(),
                [&](const QQmlJSScope::ConstPtr &scope, QQmlJSScope::ExtensionKind mode) {
                    return checkEnums(mode == QQmlJSScope::NotExtension
                                              ? baseType(scope, type)
                                              : extensionType(scope, type),
                                      name, &result);
                })) {
        return result;
    }

    return {};
}

QQmlJSRegisterContent QQmlJSTypeResolver::memberType(
        QQmlJSRegisterContent type, const QString &name, int lookupIndex) const
{
    if (type.isType())
        return memberType(type, name, type.resultLookupIndex(), lookupIndex);
    if (type.isProperty() || type.isMethodCall())
        return memberType(type, name, type.resultLookupIndex(), lookupIndex);
    if (type.isEnumeration()) {
        const auto enumeration = type.enumeration();
        if (!type.enumMember().isEmpty() || !enumeration.hasKey(name))
            return {};
        return m_pool->createEnumeration(
                enumeration, name, QQmlJSRegisterContent::Enum, type.scope());
    }
    if (type.isMethod()) {
        QQmlJSMetaProperty prop;
        prop.setTypeName(u"QJSValue"_s);
        prop.setPropertyName(name);
        prop.setType(jsValueType());
        prop.setIsWritable(true);
        return m_pool->createProperty(
                prop, QQmlJSRegisterContent::InvalidLookupIndex, lookupIndex,
                QQmlJSRegisterContent::Property, type);
    }
    if (type.isImportNamespace()) {
        Q_ASSERT(type.scopeType()->isReferenceType());
        return registerContentForName(name, type);
    }
    if (type.isConversion()) {
        if (const auto result = memberType(
                    type, name, type.resultLookupIndex(), lookupIndex);
            result.isValid()) {
            return result;
        }

        if (const auto result = memberEnumType(type.scope(), name); result.isValid())
            return result;

        // If the conversion consists of only undefined and one actual type,
        // we can produce the members of that one type.
        // If the value is then actually undefined, the result is an exception.

        const auto nonVoid = extractNonVoidFromOptionalType(type);

        // If the conversion cannot hold the original type, it loses information.
        return (!nonVoid.isNull() && canHold(type.conversionResultType(), nonVoid.containedType()))
                ? memberType(nonVoid, name, type.resultLookupIndex(), lookupIndex)
                : QQmlJSRegisterContent();
    }

    Q_UNREACHABLE_RETURN({});
}

QQmlJSRegisterContent QQmlJSTypeResolver::elementType(QQmlJSRegisterContent list) const
{
    QQmlJSScope::ConstPtr value;

    auto valueType = [&](const QQmlJSScope::ConstPtr &scope) -> QQmlJSScope::ConstPtr {
        if (scope->accessSemantics() == QQmlJSScope::AccessSemantics::Sequence)
            return scope->elementType();

        if (scope == m_forInIteratorPtr)
            return m_sizeType;

        if (scope == m_forOfIteratorPtr)
            return list.scopeType()->elementType();

        if (scope == m_jsValueType || scope == m_varType)
            return m_jsValueType;

        if (scope == m_stringType)
            return m_stringType;

        return QQmlJSScope::ConstPtr();
    };

    value = valueType(list.containedType());

    if (value.isNull())
        return {};

    QQmlJSMetaProperty property;
    property.setPropertyName(u"[]"_s);
    property.setTypeName(value->internalName());
    property.setType(value);

    return m_pool->createProperty(
            property, QQmlJSRegisterContent::InvalidLookupIndex,
            QQmlJSRegisterContent::InvalidLookupIndex, QQmlJSRegisterContent::ListValue,
            list);
}

QQmlJSRegisterContent QQmlJSTypeResolver::returnType(
        const QQmlJSMetaMethod &method, const QQmlJSScope::ConstPtr &returnType,
        QQmlJSRegisterContent scope) const
{
    return m_pool->createMethodCall(method, returnType, scope);
}

QQmlJSRegisterContent QQmlJSTypeResolver::extensionType(
        const QQmlJSScope::ConstPtr &extension, QQmlJSRegisterContent base) const
{
    return m_pool->createType(
            extension, base.resultLookupIndex(), QQmlJSRegisterContent::Extension, base);
}

/*!
 * \internal
 * Encodes \a base as a base type of \a derived and returns a QQmlJSRegisterContent.
 * "Base type" here is understood the same way as std::is_base_of would understand it.
 * That means, if you pass the contained type of \a derived as \a base, then \a derived
 * itself is returned.
 */
QQmlJSRegisterContent QQmlJSTypeResolver::baseType(
        const QQmlJSScope::ConstPtr &base, QQmlJSRegisterContent derived) const
{
    return m_pool->createType(
            base, derived.resultLookupIndex(), QQmlJSRegisterContent::BaseType, derived);
}

/*!
 * \internal
 * Encodes \a parent as a parent scope of \a child and returns a QQmlJSRegisterContent.
 * "Parent scope" here means any scope above, but also _including_ \a child.
 * That means, if you pass the contained type of \a child as \a parent, then \a child
 * itself is returned.
 */
QQmlJSRegisterContent QQmlJSTypeResolver::parentScope(
        const QQmlJSScope::ConstPtr &parent, QQmlJSRegisterContent child) const
{
    return m_pool->createType(
            parent, child.resultLookupIndex(), QQmlJSRegisterContent::ParentScope, child);
}

QQmlJSRegisterContent QQmlJSTypeResolver::iteratorPointer(
        QQmlJSRegisterContent listType, QQmlJS::AST::ForEachType type,
        int lookupIndex) const
{
    const QQmlJSScope::ConstPtr value = (type == QQmlJS::AST::ForEachType::In)
            ? m_int32Type
            : elementType(listType).containedType();

    QQmlJSScope::ConstPtr iteratorPointer = type == QQmlJS::AST::ForEachType::In
            ? m_forInIteratorPtr
            : m_forOfIteratorPtr;

    QQmlJSMetaProperty prop;
    prop.setPropertyName(u"<>"_s);
    prop.setTypeName(iteratorPointer->internalName());
    prop.setType(iteratorPointer);
    return m_pool->createProperty(
            prop, lookupIndex,
            QQmlJSRegisterContent::InvalidLookupIndex, QQmlJSRegisterContent::ListIterator,
            listType);
}

QQmlJSScope::ConstPtr QQmlJSTypeResolver::storedType(const QQmlJSScope::ConstPtr &type) const
{
    if (type.isNull())
        return {};
    if (type == voidType())
        return type;
    if (type->isScript())
        return jsValueType();
    if (type->isComposite()) {
        if (const QQmlJSScope::ConstPtr nonComposite = QQmlJSScope::nonCompositeBaseType(type))
            return nonComposite;

        // If we can't find the non-composite base, we really don't know what it is.
        return genericType(type);
    }
    if (type->filePath().isEmpty())
        return genericType(type);
    return type;
}

static QQmlJSRegisterContent doConvert(
        QQmlJSRegisterContent from, const QQmlJSScope::ConstPtr &to,
        QQmlJSRegisterContent scope, QQmlJSRegisterContentPool *pool)
{
    if (from.isConversion()) {
        return pool->createConversion(
                from.conversionOrigins(), to,
                scope.isValid() ? scope : from.conversionResultScope(),
                from.variant(), from.scope());
    }

    return pool->createConversion(
            QList<QQmlJSRegisterContent>{from},
            to, scope, from.variant(),
            from.scope());
}

QQmlJSRegisterContent QQmlJSTypeResolver::convert(
        QQmlJSRegisterContent from, QQmlJSRegisterContent to) const
{
    return doConvert(from, to.containedType(), to.scope(), m_pool.get());
}

QQmlJSRegisterContent QQmlJSTypeResolver::convert(
        QQmlJSRegisterContent from, const QQmlJSScope::ConstPtr &to) const
{
    return doConvert(from, to, QQmlJSRegisterContent(), m_pool.get());
}

QT_END_NAMESPACE