aboutsummaryrefslogtreecommitdiffstats
path: root/src/qmlcompiler/qqmljsimportvisitor.cpp
blob: f048748b5831c08973a6ce20aa7df1521e5ea77a (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
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
// Copyright (C) 2019 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "qqmljsimportvisitor_p.h"
#include "qqmljslogger_p.h"
#include "qqmljsmetatypes_p.h"
#include "qqmljsresourcefilemapper_p.h"

#include <QtCore/qfileinfo.h>
#include <QtCore/qdir.h>
#include <QtCore/qqueue.h>
#include <QtCore/qscopedvaluerollback.h>
#include <QtCore/qpoint.h>
#include <QtCore/qrect.h>
#include <QtCore/qsize.h>

#include <QtQml/private/qqmlsignalnames_p.h>
#include <QtQml/private/qv4codegen_p.h>
#include <QtQml/private/qqmlstringconverters_p.h>
#include <QtQml/private/qqmlirbuilder_p.h>
#include "qqmljsscope_p.h"
#include "qqmljsutils_p.h"
#include "qqmljsloggingutils.h"
#include "qqmlsaconstants.h"

#include <algorithm>
#include <limits>
#include <optional>
#include <variant>

QT_BEGIN_NAMESPACE

using namespace Qt::StringLiterals;

using namespace QQmlJS::AST;

/*!
    \internal
    Returns if assigning \a assignedType to \a property would require an
    implicit component wrapping.
 */
static bool causesImplicitComponentWrapping(const QQmlJSMetaProperty &property,
                                                  const QQmlJSScope::ConstPtr &assignedType)
{
    // See QQmlComponentAndAliasResolver::findAndRegisterImplicitComponents()
    // for the logic in qqmltypecompiler

    // Note: unlike findAndRegisterImplicitComponents() we do not check whether
    // the property type is *derived* from QQmlComponent at some point because
    // this is actually meaningless (and in the case of QQmlComponent::create()
    // gets rejected in QQmlPropertyValidator): if the type is not a
    // QQmlComponent, we have a type mismatch because of assigning a Component
    // object to a non-Component property
    const bool propertyVerdict = property.type()->internalName() == u"QQmlComponent";

    const bool assignedTypeVerdict = [&assignedType]() {
        // Note: nonCompositeBaseType covers the case when assignedType itself
        // is non-composite
        auto cppBase = QQmlJSScope::nonCompositeBaseType(assignedType);
        Q_ASSERT(cppBase); // any QML type has (or must have) a C++ base type

        // See isUsableComponent() in qqmltypecompiler.cpp: along with checking
        // whether a type has a QQmlComponent static meta object (which we
        // substitute here with checking the first non-composite base for being
        // a QQmlComponent), it also excludes QQmlAbstractDelegateComponent
        // subclasses from implicit wrapping
        if (cppBase->internalName() == u"QQmlComponent")
            return false;
        for (; cppBase; cppBase = cppBase->baseType()) {
            if (cppBase->internalName() == u"QQmlAbstractDelegateComponent")
                return false;
        }
        return true;
    }();

    return propertyVerdict && assignedTypeVerdict;
}

/*!
  \internal
  Sets the name of \a scope to \a name based on \a type.
*/
inline void setScopeName(QQmlJSScope::Ptr &scope, QQmlJSScope::ScopeType type, const QString &name)
{
    Q_ASSERT(scope);
    if (type == QQmlSA::ScopeType::GroupedPropertyScope
        || type == QQmlSA::ScopeType::AttachedPropertyScope)
        scope->setInternalName(name);
    else
        scope->setBaseTypeName(name);
}

/*!
  \internal
  Returns the name of \a scope based on \a type.
*/
inline QString getScopeName(const QQmlJSScope::ConstPtr &scope, QQmlJSScope::ScopeType type)
{
    Q_ASSERT(scope);
    if (type == QQmlSA::ScopeType::GroupedPropertyScope
        || type == QQmlSA::ScopeType::AttachedPropertyScope)
        return scope->internalName();

    return scope->baseTypeName();
}

template<typename Node>
QString buildName(const Node *node)
{
    QString result;
    for (const Node *segment = node; segment; segment = segment->next) {
        if (!result.isEmpty())
            result += u'.';
        result += segment->name;
    }
    return result;
}

QQmlJSImportVisitor::QQmlJSImportVisitor(
        const QQmlJSScope::Ptr &target, QQmlJSImporter *importer, QQmlJSLogger *logger,
        const QString &implicitImportDirectory, const QStringList &qmldirFiles)
    : m_implicitImportDirectory(implicitImportDirectory),
      m_qmldirFiles(qmldirFiles),
      m_currentScope(QQmlJSScope::create()),
      m_exportedRootScope(target),
      m_importer(importer),
      m_logger(logger),
      m_rootScopeImports(
          QQmlJSImporter::ImportedTypes::QML, {},
          importer->builtinInternalNames().arrayType())
{
    m_currentScope->setScopeType(QQmlSA::ScopeType::JSFunctionScope);
    Q_ASSERT(logger); // must be valid

    m_globalScope = m_currentScope;
    m_currentScope->setIsComposite(true);

    m_currentScope->setInternalName(u"global"_s);

    QLatin1String jsGlobVars[] = { /* Not listed on the MDN page; browser and QML extensions: */
                                   // console/debug api
                                   QLatin1String("console"), QLatin1String("print"),
                                   // garbage collector
                                   QLatin1String("gc"),
                                   // i18n
                                   QLatin1String("qsTr"), QLatin1String("qsTrId"),
                                   QLatin1String("QT_TR_NOOP"), QLatin1String("QT_TRANSLATE_NOOP"),
                                   QLatin1String("QT_TRID_NOOP"),
                                   // XMLHttpRequest
                                   QLatin1String("XMLHttpRequest")
    };

    QQmlJSScope::JavaScriptIdentifier globalJavaScript = {
        QQmlJSScope::JavaScriptIdentifier::LexicalScoped, QQmlJS::SourceLocation(), std::nullopt,
        true
    };
    for (const char **globalName = QV4::Compiler::Codegen::s_globalNames; *globalName != nullptr;
         ++globalName) {
        m_currentScope->insertJSIdentifier(QString::fromLatin1(*globalName), globalJavaScript);
    }
    for (const auto &jsGlobVar : jsGlobVars)
        m_currentScope->insertJSIdentifier(jsGlobVar, globalJavaScript);
}

QQmlJSImportVisitor::~QQmlJSImportVisitor() = default;

void QQmlJSImportVisitor::populateCurrentScope(
        QQmlJSScope::ScopeType type, const QString &name, const QQmlJS::SourceLocation &location)
{
    m_currentScope->setScopeType(type);
    setScopeName(m_currentScope, type, name);
    m_currentScope->setIsComposite(true);
    m_currentScope->setFilePath(QFileInfo(m_logger->fileName()).absoluteFilePath());
    m_currentScope->setSourceLocation(location);
    m_scopesByIrLocation.insert({ location.startLine, location.startColumn }, m_currentScope);
}

void QQmlJSImportVisitor::enterRootScope(QQmlJSScope::ScopeType type, const QString &name, const QQmlJS::SourceLocation &location)
{
    QQmlJSScope::reparent(m_currentScope, m_exportedRootScope);
    m_currentScope = m_exportedRootScope;
    populateCurrentScope(type, name, location);
}

void QQmlJSImportVisitor::enterEnvironment(QQmlJSScope::ScopeType type, const QString &name,
                                           const QQmlJS::SourceLocation &location)
{
    QQmlJSScope::Ptr newScope = QQmlJSScope::create();
    QQmlJSScope::reparent(m_currentScope, newScope);
    m_currentScope = std::move(newScope);
    populateCurrentScope(type, name, location);
}

bool QQmlJSImportVisitor::enterEnvironmentNonUnique(QQmlJSScope::ScopeType type,
                                                    const QString &name,
                                                    const QQmlJS::SourceLocation &location)
{
    Q_ASSERT(type == QQmlSA::ScopeType::GroupedPropertyScope
             || type == QQmlSA::ScopeType::AttachedPropertyScope);

    const auto pred = [&](const QQmlJSScope::ConstPtr &s) {
        // it's either attached or group property, so use internalName()
        // directly. see setScopeName() for details
        return s->internalName() == name;
    };
    const auto scopes = m_currentScope->childScopes();
    // TODO: linear search. might want to make childScopes() a set/hash-set and
    // use faster algorithm here
    auto it = std::find_if(scopes.begin(), scopes.end(), pred);
    if (it == scopes.end()) {
        // create and enter new scope
        enterEnvironment(type, name, location);
        return false;
    }
    // enter found scope
    m_scopesByIrLocation.insert({ location.startLine, location.startColumn }, *it);
    m_currentScope = *it;
    return true;
}

void QQmlJSImportVisitor::leaveEnvironment()
{
    m_currentScope = m_currentScope->parentScope();
}

bool QQmlJSImportVisitor::isTypeResolved(const QQmlJSScope::ConstPtr &type)
{
    const auto handleUnresolvedType = [this](const QQmlJSScope::ConstPtr &type) {
        m_logger->log(QStringLiteral("Type %1 is used but it is not resolved")
                              .arg(getScopeName(type, type->scopeType())),
                      qmlUnresolvedType, type->sourceLocation());
    };
    return isTypeResolved(type, handleUnresolvedType);
}

static bool mayBeUnresolvedGeneralizedGroupedProperty(const QQmlJSScope::ConstPtr &scope)
{
    return scope->scopeType() == QQmlSA::ScopeType::GroupedPropertyScope && !scope->baseType();
}

void QQmlJSImportVisitor::resolveAliasesAndIds()
{
    QQueue<QQmlJSScope::Ptr> objects;
    objects.enqueue(m_exportedRootScope);

    qsizetype lastRequeueLength = std::numeric_limits<qsizetype>::max();
    QQueue<QQmlJSScope::Ptr> requeue;

    while (!objects.isEmpty()) {
        const QQmlJSScope::Ptr object = objects.dequeue();
        const auto properties = object->ownProperties();

        bool doRequeue = false;
        for (const auto &property : properties) {
            if (!property.isAlias() || !property.type().isNull())
                continue;

            QStringList components = property.aliasExpression().split(u'.');
            QQmlJSMetaProperty targetProperty;

            bool foundProperty = false;

            // The first component has to be an ID. Find the object it refers to.
            QQmlJSScope::ConstPtr type = m_scopesById.scope(components.takeFirst(), object);
            QQmlJSScope::ConstPtr typeScope;
            if (!type.isNull()) {
                foundProperty = true;

                // Any further components are nested properties of that object.
                // Technically we can only resolve a limited depth in the engine, but the rules
                // on that are fuzzy and subject to change. Let's ignore it for now.
                // If the target is itself an alias and has not been resolved, re-queue the object
                // and try again later.
                while (type && !components.isEmpty()) {
                    const QString name = components.takeFirst();

                    if (!type->hasProperty(name)) {
                        foundProperty = false;
                        type = {};
                        break;
                    }

                    const auto target = type->property(name);
                    if (!target.type() && target.isAlias())
                        doRequeue = true;
                    typeScope = type;
                    type = target.type();
                    targetProperty = target;
                }
            }

            if (type.isNull()) {
                if (doRequeue)
                    continue;
                if (foundProperty) {
                    m_logger->log(QStringLiteral("Cannot deduce type of alias \"%1\"")
                                          .arg(property.propertyName()),
                                  qmlMissingType, object->sourceLocation());
                } else {
                    m_logger->log(QStringLiteral("Cannot resolve alias \"%1\"")
                                          .arg(property.propertyName()),
                                  qmlUnresolvedAlias, object->sourceLocation());
                }

                Q_ASSERT(property.index() >= 0); // this property is already in object
                object->addOwnProperty(property);

            } else {
                QQmlJSMetaProperty newProperty = property;
                newProperty.setType(type);
                // Copy additional property information from target
                newProperty.setIsList(targetProperty.isList());
                newProperty.setIsWritable(targetProperty.isWritable());
                newProperty.setIsPointer(targetProperty.isPointer());

                if (!typeScope.isNull() && !object->isPropertyLocallyRequired(property.propertyName())) {
                    object->setPropertyLocallyRequired(
                            newProperty.propertyName(),
                            typeScope->isPropertyRequired(targetProperty.propertyName()));
                }

                if (const QString internalName = type->internalName(); !internalName.isEmpty())
                    newProperty.setTypeName(internalName);

                Q_ASSERT(newProperty.index() >= 0); // this property is already in object
                object->addOwnProperty(newProperty);
            }
        }

        const auto childScopes = object->childScopes();
        for (const auto &childScope : childScopes) {
            if (mayBeUnresolvedGeneralizedGroupedProperty(childScope)) {
                const QString name = childScope->internalName();
                if (object->isNameDeferred(name)) {
                    const QQmlJSScope::ConstPtr deferred = m_scopesById.scope(name, childScope);
                    if (!deferred.isNull()) {
                        QQmlJSScope::resolveGeneralizedGroup(
                                    childScope, deferred, m_rootScopeImports, &m_usedTypes);
                    }
                }
            }
            objects.enqueue(childScope);
        }

        if (doRequeue)
            requeue.enqueue(object);

        if (objects.isEmpty() && requeue.size() < lastRequeueLength) {
            lastRequeueLength = requeue.size();
            objects.swap(requeue);
        }
    }

    while (!requeue.isEmpty()) {
        const QQmlJSScope::Ptr object = requeue.dequeue();
        const auto properties = object->ownProperties();
        for (const auto &property : properties) {
            if (!property.isAlias() || property.type())
                continue;
            m_logger->log(QStringLiteral("Alias \"%1\" is part of an alias cycle")
                                  .arg(property.propertyName()),
                          qmlAliasCycle, object->sourceLocation());
        }
    }
}

QString QQmlJSImportVisitor::implicitImportDirectory(
        const QString &localFile, QQmlJSResourceFileMapper *mapper)
{
    if (mapper) {
        const auto resource = mapper->entry(
                    QQmlJSResourceFileMapper::localFileFilter(localFile));
        if (resource.isValid()) {
            return resource.resourcePath.contains(u'/')
                    ? (u':' + resource.resourcePath.left(
                           resource.resourcePath.lastIndexOf(u'/') + 1))
                    : QStringLiteral(":/");
        }
    }

    return QFileInfo(localFile).canonicalPath() + u'/';
}

void QQmlJSImportVisitor::processImportWarnings(
        const QString &what, const QQmlJS::SourceLocation &srcLocation)
{
    const auto warnings = m_importer->takeWarnings();
    if (warnings.isEmpty())
        return;

    m_logger->log(QStringLiteral("Warnings occurred while importing %1:").arg(what), qmlImport,
                  srcLocation);
    m_logger->processMessages(warnings, qmlImport);
}

void QQmlJSImportVisitor::importBaseModules()
{
    Q_ASSERT(m_rootScopeImports.types().isEmpty());
    m_rootScopeImports = m_importer->importBuiltins();

    const QQmlJS::SourceLocation invalidLoc;
    for (auto it = m_rootScopeImports.types().keyBegin(), end = m_rootScopeImports.types().keyEnd();
         it != end; it++) {
        addImportWithLocation(*it, invalidLoc);
    }

    if (!m_qmldirFiles.isEmpty())
        m_importer->importQmldirs(m_qmldirFiles);

    // Pulling in the modules and neighboring qml files of the qmltypes we're trying to lint is not
    // something we need to do.
    if (!m_logger->fileName().endsWith(u".qmltypes"_s)) {
        QQmlJS::ContextualTypes fromDirectory =
                m_importer->importDirectory(m_implicitImportDirectory);
        m_rootScopeImports.addTypes(std::move(fromDirectory));

        // Import all possible resource directories the file may belong to.
        // This is somewhat fuzzy, but if you're mapping the same file to multiple resource
        // locations, you're on your own anyway.
        if (QQmlJSResourceFileMapper *mapper = m_importer->resourceFileMapper()) {
            const QStringList resourcePaths = mapper->resourcePaths(QQmlJSResourceFileMapper::Filter {
                    m_logger->fileName(), QStringList(), QQmlJSResourceFileMapper::Resource });
            for (const QString &path : resourcePaths) {
                const qsizetype lastSlash = path.lastIndexOf(QLatin1Char('/'));
                if (lastSlash == -1)
                    continue;
                m_rootScopeImports.addTypes(m_importer->importDirectory(path.first(lastSlash)));
            }
        }
    }

    processImportWarnings(QStringLiteral("base modules"));
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiProgram *)
{
    importBaseModules();
    return true;
}

void QQmlJSImportVisitor::endVisit(UiProgram *)
{
    for (const auto &scope : m_objectBindingScopes) {
        breakInheritanceCycles(scope);
        checkDeprecation(scope);
    }

    for (const auto &scope : m_objectDefinitionScopes) {
        if (m_pendingDefaultProperties.contains(scope))
            continue; // We're going to check this one below.
        breakInheritanceCycles(scope);
        checkDeprecation(scope);
    }

    for (const auto &scope : m_pendingDefaultProperties.keys()) {
        breakInheritanceCycles(scope);
        checkDeprecation(scope);
    }

    resolveAliasesAndIds();

    for (const auto &scope : m_objectDefinitionScopes)
        checkGroupedAndAttachedScopes(scope);

    setAllBindings();
    processDefaultProperties();
    processPropertyTypes();
    processMethodTypes();
    processPropertyBindings();
    processPropertyBindingObjects();
    checkRequiredProperties();

    auto unusedImports = m_importLocations;
    for (const QString &type : m_usedTypes) {
        for (const auto &importLocation : m_importTypeLocationMap.values(type))
            unusedImports.remove(importLocation);

        // If there are no more unused imports left we can abort early
        if (unusedImports.isEmpty())
            break;
    }

    for (const QQmlJS::SourceLocation &import : m_importStaticModuleLocationMap.values())
        unusedImports.remove(import);

    for (const auto &import : unusedImports) {
        m_logger->log(QString::fromLatin1("Unused import"), qmlUnusedImports, import);
    }

    populateRuntimeFunctionIndicesForDocument();
}

static QQmlJSAnnotation::Value bindingToVariant(QQmlJS::AST::Statement *statement)
{
    ExpressionStatement *expr = cast<ExpressionStatement *>(statement);

    if (!statement || !expr->expression)
        return {};

    switch (expr->expression->kind) {
    case Node::Kind_StringLiteral:
        return cast<StringLiteral *>(expr->expression)->value.toString();
    case Node::Kind_NumericLiteral:
        return cast<NumericLiteral *>(expr->expression)->value;
    default:
        return {};
    }
}

QVector<QQmlJSAnnotation> QQmlJSImportVisitor::parseAnnotations(QQmlJS::AST::UiAnnotationList *list)
{

    QVector<QQmlJSAnnotation> annotationList;

    for (UiAnnotationList *item = list; item != nullptr; item = item->next) {
        UiAnnotation *annotation = item->annotation;

        QQmlJSAnnotation qqmljsAnnotation;
        qqmljsAnnotation.name = buildName(annotation->qualifiedTypeNameId);

        for (UiObjectMemberList *memberItem = annotation->initializer->members; memberItem != nullptr; memberItem = memberItem->next) {
            switch (memberItem->member->kind) {
            case Node::Kind_UiScriptBinding: {
                auto *scriptBinding = QQmlJS::AST::cast<UiScriptBinding*>(memberItem->member);
                qqmljsAnnotation.bindings[buildName(scriptBinding->qualifiedId)]
                        = bindingToVariant(scriptBinding->statement);
                break;
            }
            default:
                // We ignore all the other information contained in the annotation
                break;
            }
        }

        annotationList.append(qqmljsAnnotation);
    }

    return annotationList;
}

void QQmlJSImportVisitor::setAllBindings()
{
    for (auto it = m_bindings.cbegin(); it != m_bindings.cend(); ++it) {
        // ensure the scope is resolved, if not - it is an error
        auto type = it->owner;
        if (!type->isFullyResolved()) {
            if (!type->isInCustomParserParent()) { // special otherwise
                m_logger->log(QStringLiteral("'%1' is used but it is not resolved")
                                      .arg(getScopeName(type, type->scopeType())),
                              qmlUnresolvedType, type->sourceLocation());
            }
            continue;
        }
        auto binding = it->create();
        if (binding.isValid())
            type->addOwnPropertyBinding(binding, it->specifier);
    }
}

void QQmlJSImportVisitor::processDefaultProperties()
{
    for (auto it = m_pendingDefaultProperties.constBegin();
         it != m_pendingDefaultProperties.constEnd(); ++it) {
        QQmlJSScope::ConstPtr parentScope = it.key();

        // We can't expect custom parser default properties to be sensible, discard them for now.
        if (parentScope->isInCustomParserParent())
            continue;

        /* consider:
         *
         *      QtObject { // <- parentScope
         *          default property var p // (1)
         *          QtObject {} // (2)
         *      }
         *
         * `p` (1) is a property of a subtype of QtObject, it couldn't be used
         * in a property binding (2)
         */
        // thus, use a base type of parent scope to detect a default property
        parentScope = parentScope->baseType();

        const QString defaultPropertyName =
                parentScope ? parentScope->defaultPropertyName() : QString();

        if (defaultPropertyName.isEmpty()) {
            // If the parent scope is based on Component it can have any child element
            // TODO: We should also store these somewhere
            bool isComponent = false;
            for (QQmlJSScope::ConstPtr s = parentScope; s; s = s->baseType()) {
                if (s->internalName() == QStringLiteral("QQmlComponent")) {
                    isComponent = true;
                    break;
                }
            }

            if (!isComponent) {
                m_logger->log(QStringLiteral("Cannot assign to non-existent default property"),
                              qmlMissingProperty, it.value().constFirst()->sourceLocation());
            }

            continue;
        }

        const QQmlJSMetaProperty defaultProp = parentScope->property(defaultPropertyName);
        auto propType = defaultProp.type();
        const auto handleUnresolvedDefaultProperty = [&](const QQmlJSScope::ConstPtr &) {
            // Property type is not fully resolved we cannot tell any more than this
            m_logger->log(QStringLiteral("Property \"%1\" has incomplete type \"%2\". You may be "
                                         "missing an import.")
                                  .arg(defaultPropertyName)
                                  .arg(defaultProp.typeName()),
                          qmlMissingProperty, it.value().constFirst()->sourceLocation());
        };

        if (propType.isNull()) {
            handleUnresolvedDefaultProperty(propType);
            continue;
        }

        if (it.value().size() > 1
                && !defaultProp.isList()
                && !propType->isListProperty()) {
            m_logger->log(
                    QStringLiteral("Cannot assign multiple objects to a default non-list property"),
                    qmlNonListProperty, it.value().constFirst()->sourceLocation());
        }

        if (!isTypeResolved(propType, handleUnresolvedDefaultProperty))
            continue;

        for (const QQmlJSScope::Ptr &scope : std::as_const(*it)) {
            if (!isTypeResolved(scope))
                continue;

            // Assigning any element to a QQmlComponent property implicitly wraps it into a Component
            // Check whether the property can be assigned the scope
            if (propType->canAssign(scope)) {
                scope->setIsWrappedInImplicitComponent(
                        causesImplicitComponentWrapping(defaultProp, scope));
                continue;
            }

            m_logger->log(QStringLiteral("Cannot assign to default property of incompatible type"),
                          qmlIncompatibleType, scope->sourceLocation());
        }
    }
}

void QQmlJSImportVisitor::processPropertyTypes()
{
    for (const PendingPropertyType &type : m_pendingPropertyTypes) {
        Q_ASSERT(type.scope->hasOwnProperty(type.name));

        auto property = type.scope->ownProperty(type.name);

        if (const auto propertyType =
                    QQmlJSScope::findType(property.typeName(), m_rootScopeImports).scope) {
            property.setType(propertyType);
            type.scope->addOwnProperty(property);
        } else {
            m_logger->log(property.typeName()
                                  + QStringLiteral(" was not found. Did you add all import paths?"),
                          qmlImport, type.location);
        }
    }
}

void QQmlJSImportVisitor::processMethodTypes()
{
    for (const auto &type : m_pendingMethodTypes) {

        for (auto [it, end] = type.scope->mutableOwnMethodsRange(type.methodName); it != end;
             ++it) {
            if (const auto returnType =
                        QQmlJSScope::findType(it->returnTypeName(), m_rootScopeImports).scope) {
                it->setReturnType({ returnType });
            } else {
                m_logger->log(u"\"%1\" was not found for the return type of method \"%2\"."_s.arg(
                                      it->returnTypeName(), it->methodName()),
                              qmlUnresolvedType, type.location);
            }

            for (auto [parameter, parameterEnd] = it->mutableParametersRange();
                 parameter != parameterEnd; ++parameter) {
                if (const auto parameterType =
                            QQmlJSScope::findType(parameter->typeName(), m_rootScopeImports)
                                    .scope) {
                    parameter->setType({ parameterType });
                } else {
                    m_logger->log(
                            u"\"%1\" was not found for the type of parameter \"%2\" in method \"%3\"."_s
                                    .arg(parameter->typeName(), parameter->name(),
                                         it->methodName()),
                            qmlUnresolvedType, type.location);
                }
            }
        }
    }
}

void QQmlJSImportVisitor::processPropertyBindingObjects()
{
    QSet<QPair<QQmlJSScope::Ptr, QString>> foundLiterals;
    {
        // Note: populating literals here is special, because we do not store
        // them in m_pendingPropertyObjectBindings, so we have to lookup all
        // bindings on a property for each scope and see if there are any
        // literal bindings there. this is safe to do once at the beginning
        // because this function doesn't add new literal bindings and all
        // literal bindings must already be added at this point.
        QSet<QPair<QQmlJSScope::Ptr, QString>> visited;
        for (const PendingPropertyObjectBinding &objectBinding :
             std::as_const(m_pendingPropertyObjectBindings)) {
            // unique because it's per-scope and per-property
            const auto uniqueBindingId = qMakePair(objectBinding.scope, objectBinding.name);
            if (visited.contains(uniqueBindingId))
                continue;
            visited.insert(uniqueBindingId);

            auto [existingBindingsBegin, existingBindingsEnd] =
                    uniqueBindingId.first->ownPropertyBindings(uniqueBindingId.second);
            const bool hasLiteralBindings =
                    std::any_of(existingBindingsBegin, existingBindingsEnd,
                                [](const QQmlJSMetaPropertyBinding &x) { return x.hasLiteral(); });
            if (hasLiteralBindings)
                foundLiterals.insert(uniqueBindingId);
        }
    }

    QSet<QPair<QQmlJSScope::Ptr, QString>> foundObjects;
    QSet<QPair<QQmlJSScope::Ptr, QString>> foundInterceptors;
    QSet<QPair<QQmlJSScope::Ptr, QString>> foundValueSources;

    for (const PendingPropertyObjectBinding &objectBinding :
         std::as_const(m_pendingPropertyObjectBindings)) {
        const QString propertyName = objectBinding.name;
        QQmlJSScope::ConstPtr childScope = objectBinding.childScope;

        if (!isTypeResolved(objectBinding.scope)) // guarantees property lookup
            continue;

        QQmlJSMetaProperty property = objectBinding.scope->property(propertyName);

        if (!property.isValid()) {
            m_logger->log(QStringLiteral("Property \"%1\" does not exist").arg(propertyName),
                          qmlMissingProperty, objectBinding.location);
            continue;
        }
        const auto handleUnresolvedProperty = [&](const QQmlJSScope::ConstPtr &) {
            // Property type is not fully resolved we cannot tell any more than this
            m_logger->log(QStringLiteral("Property \"%1\" has incomplete type \"%2\". You may be "
                                         "missing an import.")
                                  .arg(propertyName)
                                  .arg(property.typeName()),
                          qmlUnresolvedType, objectBinding.location);
        };
        if (property.type().isNull()) {
            handleUnresolvedProperty(property.type());
            continue;
        }

        // guarantee that canAssign() can be called
        if (!isTypeResolved(property.type(), handleUnresolvedProperty)
            || !isTypeResolved(childScope)) {
            continue;
        }

        if (!objectBinding.onToken && !property.type()->canAssign(childScope)) {
            // the type is incompatible
            m_logger->log(QStringLiteral("Property \"%1\" of type \"%2\" is assigned an "
                                         "incompatible type \"%3\"")
                                  .arg(propertyName)
                                  .arg(property.typeName())
                                  .arg(getScopeName(childScope, QQmlSA::ScopeType::QMLScope)),
                          qmlIncompatibleType, objectBinding.location);
            continue;
        }

        objectBinding.childScope->setIsWrappedInImplicitComponent(
                causesImplicitComponentWrapping(property, childScope));

        // unique because it's per-scope and per-property
        const auto uniqueBindingId = qMakePair(objectBinding.scope, objectBinding.name);
        const QString typeName = getScopeName(childScope, QQmlSA::ScopeType::QMLScope);

        if (objectBinding.onToken) {
            if (childScope->hasInterface(QStringLiteral("QQmlPropertyValueInterceptor"))) {
                if (foundInterceptors.contains(uniqueBindingId)) {
                    m_logger->log(QStringLiteral("Duplicate interceptor on property \"%1\"")
                                          .arg(propertyName),
                                  qmlDuplicatePropertyBinding, objectBinding.location);
                } else {
                    foundInterceptors.insert(uniqueBindingId);
                }
            } else if (childScope->hasInterface(QStringLiteral("QQmlPropertyValueSource"))) {
                if (foundValueSources.contains(uniqueBindingId)) {
                    m_logger->log(QStringLiteral("Duplicate value source on property \"%1\"")
                                          .arg(propertyName),
                                  qmlDuplicatePropertyBinding, objectBinding.location);
                } else if (foundObjects.contains(uniqueBindingId)
                           || foundLiterals.contains(uniqueBindingId)) {
                    m_logger->log(QStringLiteral("Cannot combine value source and binding on "
                                                 "property \"%1\"")
                                          .arg(propertyName),
                                  qmlDuplicatePropertyBinding, objectBinding.location);
                } else {
                    foundValueSources.insert(uniqueBindingId);
                }
            } else {
                m_logger->log(QStringLiteral("On-binding for property \"%1\" has wrong type \"%2\"")
                                      .arg(propertyName)
                                      .arg(typeName),
                              qmlIncompatibleType, objectBinding.location);
            }
        } else {
            // TODO: Warn here if binding.hasValue() is true
            if (foundValueSources.contains(uniqueBindingId)) {
                m_logger->log(
                        QStringLiteral("Cannot combine value source and binding on property \"%1\"")
                                .arg(propertyName),
                        qmlDuplicatePropertyBinding, objectBinding.location);
            } else {
                foundObjects.insert(uniqueBindingId);
            }
        }
    }
}

void QQmlJSImportVisitor::checkRequiredProperties()
{
    for (const auto &required : m_requiredProperties) {
        if (!required.scope->hasProperty(required.name)) {
            m_logger->log(
                    QStringLiteral("Property \"%1\" was marked as required but does not exist.")
                            .arg(required.name),
                    qmlRequired, required.location);
        }
    }

    for (const auto &defScope : m_objectDefinitionScopes) {
        if (defScope->parentScope() == m_globalScope || defScope->isInlineComponent() || defScope->isComponentRootElement())
            continue;

        QVector<QQmlJSScope::ConstPtr> scopesToSearch;
        for (QQmlJSScope::ConstPtr scope = defScope; scope; scope = scope->baseType()) {
            scopesToSearch << scope;
            const auto ownProperties = scope->ownProperties();
            for (auto propertyIt = ownProperties.constBegin();
                 propertyIt != ownProperties.constEnd(); ++propertyIt) {
                const QString propName = propertyIt.key();

                QQmlJSScope::ConstPtr prevRequiredScope;
                for (QQmlJSScope::ConstPtr requiredScope : scopesToSearch) {
                    if (requiredScope->isPropertyLocallyRequired(propName)) {
                        bool found =
                                std::find_if(scopesToSearch.constBegin(), scopesToSearch.constEnd(),
                                             [&](QQmlJSScope::ConstPtr scope) {
                                                 return scope->hasPropertyBindings(propName);
                                             })
                                != scopesToSearch.constEnd();

                        if (!found) {
                            const QString scopeId = m_scopesById.id(defScope, scope);
                            bool propertyUsedInRootAlias = false;
                            if (!scopeId.isEmpty()) {
                                for (const QQmlJSMetaProperty &property :
                                     m_exportedRootScope->ownProperties()) {
                                    if (!property.isAlias())
                                        continue;

                                    QStringList aliasExpression =
                                            property.aliasExpression().split(u'.');

                                    if (aliasExpression.size() != 2)
                                        continue;
                                    if (aliasExpression[0] == scopeId
                                        && aliasExpression[1] == propName) {
                                        propertyUsedInRootAlias = true;
                                        break;
                                    }
                                }
                            }

                            if (propertyUsedInRootAlias)
                                continue;

                            const QQmlJSScope::ConstPtr propertyScope = scopesToSearch.size() > 1
                                    ? scopesToSearch.at(scopesToSearch.size() - 2)
                                    : QQmlJSScope::ConstPtr();

                            const QString propertyScopeName = !propertyScope.isNull()
                                    ? getScopeName(propertyScope, QQmlSA::ScopeType::QMLScope)
                                    : u"here"_s;

                            const QString requiredScopeName = prevRequiredScope
                                    ? getScopeName(prevRequiredScope, QQmlSA::ScopeType::QMLScope)
                                    : u"here"_s;

                            std::optional<QQmlJSFixSuggestion> suggestion;

                            QString message =
                                    QStringLiteral(
                                            "Component is missing required property %1 from %2")
                                            .arg(propName)
                                            .arg(propertyScopeName);
                            if (requiredScope != scope) {
                                if (!prevRequiredScope.isNull()) {
                                    auto sourceScope = prevRequiredScope->baseType();
                                    suggestion = QQmlJSFixSuggestion{
                                        "%1:%2:%3: Property marked as required in %4."_L1
                                                .arg(sourceScope->filePath())
                                                .arg(sourceScope->sourceLocation().startLine)
                                                .arg(sourceScope->sourceLocation().startColumn)
                                                .arg(requiredScopeName),
                                        sourceScope->sourceLocation()
                                    };
                                    suggestion->setFilename(sourceScope->filePath());
                                } else {
                                    message += QStringLiteral(" (marked as required by %1)")
                                                       .arg(requiredScopeName);
                                }
                            }

                            m_logger->log(message, qmlRequired, defScope->sourceLocation(), true,
                                          true, suggestion);
                        }
                    }
                    prevRequiredScope = requiredScope;
                }
            }
        }
    }
}

void QQmlJSImportVisitor::processPropertyBindings()
{
    for (auto it = m_propertyBindings.constBegin(); it != m_propertyBindings.constEnd(); ++it) {
        QQmlJSScope::Ptr scope = it.key();
        for (auto &[visibilityScope, location, name] : it.value()) {
            if (!scope->hasProperty(name)) {
                // These warnings do not apply for custom parsers and their children and need to be
                // handled on a case by case basis

                if (scope->isInCustomParserParent())
                    continue;

                // TODO: Can this be in a better suited category?
                std::optional<QQmlJSFixSuggestion> fixSuggestion;

                for (QQmlJSScope::ConstPtr baseScope = scope; !baseScope.isNull();
                     baseScope = baseScope->baseType()) {
                    if (auto suggestion = QQmlJSUtils::didYouMean(
                                name, baseScope->ownProperties().keys(), location);
                        suggestion.has_value()) {
                        fixSuggestion = suggestion;
                        break;
                    }
                }

                m_logger->log(QStringLiteral("Binding assigned to \"%1\", but no property \"%1\" "
                                             "exists in the current element.")
                                      .arg(name),
                              qmlMissingProperty, location, true, true, fixSuggestion);
                continue;
            }

            const auto property = scope->property(name);
            if (!property.type()) {
                m_logger->log(QStringLiteral("No type found for property \"%1\". This may be due "
                                             "to a missing import statement or incomplete "
                                             "qmltypes files.")
                                      .arg(name),
                              qmlMissingType, location);
            }

            const auto &annotations = property.annotations();

            const auto deprecationAnn =
                    std::find_if(annotations.cbegin(), annotations.cend(),
                                 [](const QQmlJSAnnotation &ann) { return ann.isDeprecation(); });

            if (deprecationAnn != annotations.cend()) {
                const auto deprecation = deprecationAnn->deprecation();

                QString message = QStringLiteral("Binding on deprecated property \"%1\"")
                                          .arg(property.propertyName());

                if (!deprecation.reason.isEmpty())
                    message.append(QStringLiteral(" (Reason: %1)").arg(deprecation.reason));

                m_logger->log(message, qmlDeprecated, location);
            }
        }
    }
}

void QQmlJSImportVisitor::checkSignal(
        const QQmlJSScope::ConstPtr &signalScope, const QQmlJS::SourceLocation &location,
        const QString &handlerName, const QStringList &handlerParameters)
{
    const auto signal = QQmlSignalNames::handlerNameToSignalName(handlerName);

    std::optional<QQmlJSMetaMethod> signalMethod;
    const auto setSignalMethod = [&](const QQmlJSScope::ConstPtr &scope, const QString &name) {
        const auto methods = scope->methods(name, QQmlJSMetaMethodType::Signal);
        if (!methods.isEmpty())
            signalMethod = methods[0];
    };

    if (signal.has_value()) {
        if (signalScope->hasMethod(*signal)) {
            setSignalMethod(signalScope, *signal);
        } else if (auto p = QQmlJSUtils::propertyFromChangedHandler(signalScope, handlerName)) {
            // we have a change handler of the form "onXChanged" where 'X'
            // is a property name

            // NB: qqmltypecompiler prefers signal to bindable
            if (auto notify = p->notify(); !notify.isEmpty()) {
                setSignalMethod(signalScope, notify);
            } else {
                Q_ASSERT(!p->bindable().isEmpty());
                signalMethod = QQmlJSMetaMethod {}; // use dummy in this case
            }
        }
    }

    if (!signalMethod.has_value()) { // haven't found anything
        std::optional<QQmlJSFixSuggestion> fix;

        // There is a small chance of suggesting this fix for things that are not actually
        // QtQml/Connections elements, but rather some other thing that is also called
        // "Connections". However, I guess we can live with this.
        if (signalScope->baseTypeName() == QStringLiteral("Connections")) {

            // Cut to the end of the line to avoid hairy issues with pre-existing function()
            // and the colon.
            const qsizetype newLength = m_logger->code().indexOf(u'\n', location.end())
                    - location.offset;

            fix = QQmlJSFixSuggestion{
                "Implicitly defining %1 as signal handler in Connections is deprecated. "
                "Create a function instead."_L1.arg(handlerName),
                QQmlJS::SourceLocation(location.offset, newLength, location.startLine,
                                       location.startColumn),
                "function %1(%2) { ... }"_L1.arg(handlerName, handlerParameters.join(u", "))
            };
        }

        m_logger->log(QStringLiteral("no matching signal found for handler \"%1\"")
                              .arg(handlerName),
                      qmlUnqualified, location, true, true, fix);
        return;
    }

    const auto signalParameters = signalMethod->parameters();
    QHash<QString, qsizetype> parameterNameIndexes;
    // check parameter positions and also if signal is suitable for onSignal handler
    for (int i = 0, end = signalParameters.size(); i < end; i++) {
        auto &p = signalParameters[i];
        parameterNameIndexes[p.name()] = i;

        auto signalName = [&]() {
            if (signal)
                return u" called %1"_s.arg(*signal);
            return QString();
        };
        auto type = p.type();
        if (!type) {
            m_logger->log(
                    QStringLiteral(
                            "Type %1 of parameter %2 in signal%3 was not found, but is "
                            "required to compile %4. Did you add all import paths?")
                            .arg(p.typeName(), p.name(), signalName(), handlerName),
                    qmlSignalParameters, location);
            continue;
        }

        if (type->isComposite())
            continue;

        // only accept following parameters for non-composite types:
        // * QObjects by pointer (nonconst*, const*, const*const,*const)
        // * Value types by value (QFont, int)
        // * Value types by const ref (const QFont&, const int&)

        auto parameterName = [&]() {
            if (p.name().isEmpty())
                return QString();
            return u" called %1"_s.arg(p.name());
        };
        switch (type->accessSemantics()) {
        case QQmlJSScope::AccessSemantics::Reference:
            if (!p.isPointer())
                m_logger->log(QStringLiteral("Type %1 of parameter%2 in signal%3 should be "
                                             "passed by pointer to be able to compile %4. ")
                                      .arg(p.typeName(), parameterName(), signalName(),
                                           handlerName),
                              qmlSignalParameters, location);
            break;
        case QQmlJSScope::AccessSemantics::Value:
        case QQmlJSScope::AccessSemantics::Sequence:
            if (p.isPointer())
                m_logger->log(
                        QStringLiteral(
                                "Type %1 of parameter%2 in signal%3 should be passed by "
                                "value or const reference to be able to compile %4. ")
                                .arg(p.typeName(), parameterName(), signalName(),
                                     handlerName),
                        qmlSignalParameters, location);
            break;
        case QQmlJSScope::AccessSemantics::None:
            m_logger->log(
                    QStringLiteral("Type %1 of parameter%2 in signal%3 required by the "
                                   "compilation of %4 cannot be used. ")
                            .arg(p.typeName(), parameterName(), signalName(), handlerName),
                    qmlSignalParameters, location);
            break;
        }
    }

    if (handlerParameters.size() > signalParameters.size()) {
        m_logger->log(QStringLiteral("Signal handler for \"%2\" has more formal"
                                     " parameters than the signal it handles.")
                              .arg(handlerName),
                      qmlSignalParameters, location);
        return;
    }

    for (qsizetype i = 0, end = handlerParameters.size(); i < end; i++) {
        const QStringView handlerParameter = handlerParameters.at(i);
        auto it = parameterNameIndexes.constFind(handlerParameter.toString());
        if (it == parameterNameIndexes.constEnd())
            continue;
        const qsizetype j = *it;

        if (j == i)
            continue;

        m_logger->log(QStringLiteral("Parameter %1 to signal handler for \"%2\""
                                     " is called \"%3\". The signal has a parameter"
                                     " of the same name in position %4.")
                              .arg(i + 1)
                              .arg(handlerName, handlerParameter)
                              .arg(j + 1),
                      qmlSignalParameters, location);
    }
}

void QQmlJSImportVisitor::addDefaultProperties()
{
    QQmlJSScope::ConstPtr parentScope = m_currentScope->parentScope();
    if (m_currentScope == m_exportedRootScope || parentScope->isArrayScope()
        || m_currentScope->isInlineComponent()) // inapplicable
        return;

    m_pendingDefaultProperties[m_currentScope->parentScope()] << m_currentScope;

    if (parentScope->isInCustomParserParent())
        return;

    /* consider:
     *
     *      QtObject { // <- parentScope
     *          default property var p // (1)
     *          QtObject {} // (2)
     *      }
     *
     * `p` (1) is a property of a subtype of QtObject, it couldn't be used
     * in a property binding (2)
     */
    // thus, use a base type of parent scope to detect a default property
    parentScope = parentScope->baseType();

    const QString defaultPropertyName =
            parentScope ? parentScope->defaultPropertyName() : QString();

    if (defaultPropertyName.isEmpty()) // an error somewhere else
        return;

    // Note: in this specific code path, binding on default property
    // means an object binding (we work with pending objects here)
    QQmlJSMetaPropertyBinding binding(m_currentScope->sourceLocation(), defaultPropertyName);
    binding.setObject(getScopeName(m_currentScope, QQmlSA::ScopeType::QMLScope),
                      QQmlJSScope::ConstPtr(m_currentScope));
    m_bindings.append(UnfinishedBinding { m_currentScope->parentScope(), [=]() { return binding; },
                                          QQmlJSScope::UnnamedPropertyTarget });
}

void QQmlJSImportVisitor::breakInheritanceCycles(const QQmlJSScope::Ptr &originalScope)
{
    QList<QQmlJSScope::ConstPtr> scopes;
    for (QQmlJSScope::ConstPtr scope = originalScope; scope;) {
        if (scopes.contains(scope)) {
            QString inheritenceCycle;
            for (const auto &seen : std::as_const(scopes)) {
                inheritenceCycle.append(seen->baseTypeName());
                inheritenceCycle.append(QLatin1String(" -> "));
            }
            inheritenceCycle.append(scopes.first()->baseTypeName());

            const QString message = QStringLiteral("%1 is part of an inheritance cycle: %2")
                                            .arg(scope->internalName(), inheritenceCycle);
            m_logger->log(message, qmlInheritanceCycle, scope->sourceLocation());
            originalScope->clearBaseType();
            originalScope->setBaseTypeError(message);
            break;
        }

        scopes.append(scope);

        const auto newScope = scope->baseType();
        if (newScope.isNull()) {
            const QString error = scope->baseTypeError();
            const QString name = scope->baseTypeName();
            if (!error.isEmpty()) {
                m_logger->log(error, qmlImport, scope->sourceLocation(), true, true);
            } else if (!name.isEmpty()) {
                m_logger->log(
                        name + QStringLiteral(" was not found. Did you add all import paths?"),
                        qmlImport, scope->sourceLocation(), true, true,
                        QQmlJSUtils::didYouMean(scope->baseTypeName(),
                                                m_rootScopeImports.types().keys(),
                                                scope->sourceLocation()));
            }
        }

        scope = newScope;
    }
}

void QQmlJSImportVisitor::checkDeprecation(const QQmlJSScope::ConstPtr &originalScope)
{
    for (QQmlJSScope::ConstPtr scope = originalScope; scope; scope = scope->baseType()) {
        for (const QQmlJSAnnotation &annotation : scope->annotations()) {
            if (annotation.isDeprecation()) {
                QQQmlJSDeprecation deprecation = annotation.deprecation();

                QString message =
                        QStringLiteral("Type \"%1\" is deprecated").arg(scope->internalName());

                if (!deprecation.reason.isEmpty())
                    message.append(QStringLiteral(" (Reason: %1)").arg(deprecation.reason));

                m_logger->log(message, qmlDeprecated, originalScope->sourceLocation());
            }
        }
    }
}

void QQmlJSImportVisitor::checkGroupedAndAttachedScopes(QQmlJSScope::ConstPtr scope)
{
    // These warnings do not apply for custom parsers and their children and need to be handled on a
    // case by case basis
    if (scope->isInCustomParserParent())
        return;

    auto children = scope->childScopes();
    while (!children.isEmpty()) {
        auto childScope = children.takeFirst();
        const auto type = childScope->scopeType();
        switch (type) {
        case QQmlSA::ScopeType::GroupedPropertyScope:
        case QQmlSA::ScopeType::AttachedPropertyScope:
            if (!childScope->baseType()) {
                m_logger->log(QStringLiteral("unknown %1 property scope %2.")
                                      .arg(type == QQmlSA::ScopeType::GroupedPropertyScope
                                                   ? QStringLiteral("grouped")
                                                   : QStringLiteral("attached"),
                                           childScope->internalName()),
                              qmlUnqualified, childScope->sourceLocation());
            }
            children.append(childScope->childScopes());
            break;
        default:
            break;
        }
    }
}

void QQmlJSImportVisitor::flushPendingSignalParameters()
{
    const QQmlJSMetaSignalHandler handler = m_signalHandlers[m_pendingSignalHandler];
    for (const QString &parameter : handler.signalParameters) {
        m_currentScope->insertJSIdentifier(parameter,
                                           { QQmlJSScope::JavaScriptIdentifier::Injected,
                                             m_pendingSignalHandler, std::nullopt, false });
    }
    m_pendingSignalHandler = QQmlJS::SourceLocation();
}

/*! \internal

    Records a JS function or a Script binding for a given \a scope. Returns an
    index of a just recorded function-or-expression.

    \sa synthesizeCompilationUnitRuntimeFunctionIndices
*/
QQmlJSMetaMethod::RelativeFunctionIndex
QQmlJSImportVisitor::addFunctionOrExpression(const QQmlJSScope::ConstPtr &scope,
                                             const QString &name)
{
    auto &array = m_functionsAndExpressions[scope];
    array.emplaceBack(name);

    // add current function to all preceding functions in the stack. we don't
    // know which one is going to be the "publicly visible" one, so just blindly
    // add it to every level and let further logic take care of that. this
    // matches what m_innerFunctions represents as function at each level just
    // got a new inner function
    for (const auto &function : m_functionStack)
        m_innerFunctions[function]++;
    m_functionStack.push({ scope, name }); // create new function

    return QQmlJSMetaMethod::RelativeFunctionIndex { int(array.size() - 1) };
}

/*! \internal

    Removes last FunctionOrExpressionIdentifier from m_functionStack, performing
    some checks on \a name.

    \note \a name must match the name added via addFunctionOrExpression().

    \sa addFunctionOrExpression, synthesizeCompilationUnitRuntimeFunctionIndices
*/
void QQmlJSImportVisitor::forgetFunctionExpression(const QString &name)
{
    auto nameToVerify = name.isEmpty() ? u"<anon>"_s : name;
    Q_UNUSED(nameToVerify);
    Q_ASSERT(!m_functionStack.isEmpty());
    Q_ASSERT(m_functionStack.top().name == nameToVerify);
    m_functionStack.pop();
}

/*! \internal

    Sets absolute runtime function indices for \a scope based on \a count
    (document-level variable). Returns count incremented by the number of
    runtime functions that the current \a scope has.

    \note Not all scopes are considered as the function is compatible with the
    compilation unit output. The runtime functions are only recorded for
    QmlIR::Object (even if they don't strictly belong to it). Thus, in
    QQmlJSScope terms, we are only interested in QML scopes, group and attached
    property scopes.
*/
int QQmlJSImportVisitor::synthesizeCompilationUnitRuntimeFunctionIndices(
        const QQmlJSScope::Ptr &scope, int count) const
{
    const auto suitableScope = [](const QQmlJSScope::Ptr &scope) {
        const auto type = scope->scopeType();
        return type == QQmlSA::ScopeType::QMLScope
                || type == QQmlSA::ScopeType::GroupedPropertyScope
                || type == QQmlSA::ScopeType::AttachedPropertyScope;
    };

    if (!suitableScope(scope))
        return count;

    QList<QQmlJSMetaMethod::AbsoluteFunctionIndex> indices;
    auto it = m_functionsAndExpressions.constFind(scope);
    if (it == m_functionsAndExpressions.cend()) // scope has no runtime functions
        return count;

    const auto &functionsAndExpressions = *it;
    for (const QString &functionOrExpression : functionsAndExpressions) {
        scope->addOwnRuntimeFunctionIndex(
                static_cast<QQmlJSMetaMethod::AbsoluteFunctionIndex>(count));
        ++count;

        // there are special cases: onSignal: function() { doSomethingUsefull }
        // in which we would register 2 functions in the runtime functions table
        // for the same expression. even more, we can have named and unnamed
        // closures inside a function or a script binding e.g.:
        // ```
        // function foo() {
        //  var closure = () => { return 42; }; // this is an inner function
        //  /* or:
        //      property = Qt.binding(function() { return anotherProperty; });
        //   */
        //  return closure();
        // }
        // ```
        // see Codegen::defineFunction() in qv4codegen.cpp for more details
        count += m_innerFunctions.value({ scope, functionOrExpression }, 0);
    }

    return count;
}

void QQmlJSImportVisitor::populateRuntimeFunctionIndicesForDocument() const
{
    int count = 0;
    const auto synthesize = [&](const QQmlJSScope::Ptr &current) {
        count = synthesizeCompilationUnitRuntimeFunctionIndices(current, count);
    };
    QQmlJSUtils::traverseFollowingQmlIrObjectStructure(m_exportedRootScope, synthesize);
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::ExpressionStatement *ast)
{
    if (m_pendingSignalHandler.isValid()) {
        enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, u"signalhandler"_s,
                         ast->firstSourceLocation());
        flushPendingSignalParameters();
    }
    return true;
}

void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ExpressionStatement *)
{
    if (m_currentScope->scopeType() == QQmlSA::ScopeType::JSFunctionScope
        && m_currentScope->baseTypeName() == u"signalhandler"_s) {
        leaveEnvironment();
    }
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::StringLiteral *sl)
{
    const QString s = m_logger->code().mid(sl->literalToken.begin(), sl->literalToken.length);

    if (s.contains(QLatin1Char('\r')) || s.contains(QLatin1Char('\n')) || s.contains(QChar(0x2028u))
        || s.contains(QChar(0x2029u))) {
        QString templateString;

        bool escaped = false;
        const QChar stringQuote = s[0];
        for (qsizetype i = 1; i < s.size() - 1; i++) {
            const QChar c = s[i];

            if (c == u'\\') {
                escaped = !escaped;
            } else if (escaped) {
                // If we encounter an escaped quote, unescape it since we use backticks here
                if (c == stringQuote)
                    templateString.chop(1);

                escaped = false;
            } else {
                if (c == u'`')
                    templateString += u'\\';
                if (c == u'$' && i + 1 < s.size() - 1 && s[i + 1] == u'{')
                    templateString += u'\\';
            }

            templateString += c;
        }

        QQmlJSFixSuggestion suggestion = { "Use a template literal instead."_L1, sl->literalToken,
                                           u"`" % templateString % u"`" };
        suggestion.setAutoApplicable();
        m_logger->log(QStringLiteral("String contains unescaped line terminator which is "
                                     "deprecated."),
                      qmlMultilineStrings, sl->literalToken, true, true, suggestion);
    }

    return true;
}

inline QQmlJSImportVisitor::UnfinishedBinding
createNonUniqueScopeBinding(QQmlJSScope::Ptr &scope, const QString &name,
                            const QQmlJS::SourceLocation &srcLocation);

static void logLowerCaseImport(QStringView superType, QQmlJS::SourceLocation location,
                               QQmlJSLogger *logger)
{
    QStringView namespaceName{ superType };
    namespaceName = namespaceName.first(namespaceName.indexOf(u'.'));
    logger->log(u"Namespace '%1' of '%2' must start with an upper case letter."_s.arg(namespaceName)
                        .arg(superType),
                qmlUncreatableType, location, true, true);
}

bool QQmlJSImportVisitor::visit(UiObjectDefinition *definition)
{
    const QString superType = buildName(definition->qualifiedTypeNameId);

    const bool isRoot = !rootScopeIsValid();
    Q_ASSERT(!superType.isEmpty());

    // we need to assume that it is a type based on its capitalization. Types defined in inline
    // components, for example, can have their type definition after their type usages:
    // Item { property IC myIC; component IC: Item{}; }
    const qsizetype indexOfTypeName = superType.lastIndexOf(u'.');
    const bool looksLikeGroupedProperty = superType.front().isLower();

    if (indexOfTypeName != -1 && looksLikeGroupedProperty) {
        logLowerCaseImport(superType, definition->qualifiedTypeNameId->identifierToken,
                           m_logger);
    }

    if (!looksLikeGroupedProperty) {
        if (!isRoot) {
            enterEnvironment(QQmlSA::ScopeType::QMLScope, superType,
                             definition->firstSourceLocation());
        } else {
            enterRootScope(QQmlSA::ScopeType::QMLScope, superType,
                           definition->firstSourceLocation());
            m_currentScope->setIsSingleton(m_rootIsSingleton);
        }

        const QTypeRevision revision = QQmlJSScope::resolveTypes(
                    m_currentScope, m_rootScopeImports, &m_usedTypes);
        if (auto base = m_currentScope->baseType(); base) {
            if (isRoot && base->internalName() == u"QQmlComponent") {
                m_logger->log(u"Qml top level type cannot be 'Component'."_s, qmlTopLevelComponent,
                              definition->qualifiedTypeNameId->identifierToken, true, true);
            }
            if (base->isSingleton() && m_currentScope->isComposite()) {
                m_logger->log(u"Singleton Type %1 is not creatable."_s.arg(
                                      m_currentScope->baseTypeName()),
                              qmlUncreatableType, definition->qualifiedTypeNameId->identifierToken,
                              true, true);

            } else if (!base->isCreatable()) {
                // composite type m_currentScope is allowed to be uncreatable, but it cannot be the base of anything else
                m_logger->log(u"Type %1 is not creatable."_s.arg(m_currentScope->baseTypeName()),
                              qmlUncreatableType, definition->qualifiedTypeNameId->identifierToken,
                              true, true);
            }
        }
        if (m_nextIsInlineComponent) {
            Q_ASSERT(std::holds_alternative<InlineComponentNameType>(m_currentRootName));
            const QString &name = std::get<InlineComponentNameType>(m_currentRootName);
            m_currentScope->setIsInlineComponent(true);
            m_currentScope->setInlineComponentName(name);
            m_currentScope->setOwnModuleName(m_exportedRootScope->moduleName());
            m_rootScopeImports.setType(name, { m_currentScope, revision });
            m_nextIsInlineComponent = false;
        }

        addDefaultProperties();
        Q_ASSERT(m_currentScope->scopeType() == QQmlSA::ScopeType::QMLScope);
        m_qmlTypes.append(m_currentScope);

        m_objectDefinitionScopes << m_currentScope;
    } else {
        enterEnvironmentNonUnique(QQmlSA::ScopeType::GroupedPropertyScope, superType,
                                  definition->firstSourceLocation());
        m_bindings.append(createNonUniqueScopeBinding(m_currentScope, superType,
                                                      definition->firstSourceLocation()));
        QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports, &m_usedTypes);
    }

    m_currentScope->setAnnotations(parseAnnotations(definition->annotations));

    return true;
}

void QQmlJSImportVisitor::endVisit(UiObjectDefinition *)
{
    QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports, &m_usedTypes);
    leaveEnvironment();
}

bool QQmlJSImportVisitor::visit(UiInlineComponent *component)
{
    if (!std::holds_alternative<RootDocumentNameType>(m_currentRootName)) {
        m_logger->log(u"Nested inline components are not supported"_s, qmlSyntax,
                      component->firstSourceLocation());
        return true;
    }

    m_nextIsInlineComponent = true;
    m_currentRootName = component->name.toString();
    return true;
}

void QQmlJSImportVisitor::endVisit(UiInlineComponent *component)
{
    m_currentRootName = RootDocumentNameType();
    if (m_nextIsInlineComponent) {
        m_logger->log(u"Inline component declaration must be followed by a typename"_s,
                      qmlSyntax, component->firstSourceLocation());
    }
    m_nextIsInlineComponent = false; // might have missed an inline component if file contains invalid QML
}

bool QQmlJSImportVisitor::visit(UiPublicMember *publicMember)
{
    switch (publicMember->type) {
    case UiPublicMember::Signal: {
        if (m_currentScope->ownMethods().contains(publicMember->name.toString())) {
            m_logger->log(QStringLiteral("Duplicated signal name \"%1\".").arg(
                publicMember->name.toString()), qmlDuplicatedName,
                publicMember->firstSourceLocation());
        }
        UiParameterList *param = publicMember->parameters;
        QQmlJSMetaMethod method;
        method.setMethodType(QQmlJSMetaMethodType::Signal);
        method.setMethodName(publicMember->name.toString());
        method.setSourceLocation(combine(publicMember->firstSourceLocation(),
                                         publicMember->lastSourceLocation()));
        while (param) {
            method.addParameter(
                    QQmlJSMetaParameter(
                            param->name.toString(),
                            param->type ? param->type->toString() : QString()
                        ));
            param = param->next;
        }
        m_currentScope->addOwnMethod(method);
        break;
    }
    case UiPublicMember::Property: {
        if (m_currentScope->ownProperties().contains(publicMember->name.toString())) {
            m_logger->log(QStringLiteral("Duplicated property name \"%1\".").arg(
                publicMember->name.toString()), qmlDuplicatedName,
                publicMember->firstSourceLocation());
        }
        QString typeName = buildName(publicMember->memberType);
        if (typeName.contains(u'.') && typeName.front().isLower()) {
            logLowerCaseImport(typeName, publicMember->typeToken, m_logger);
        }

        QString aliasExpr;
        const bool isAlias = (typeName == u"alias"_s);
        if (isAlias) {
            auto tryParseAlias = [&]() {
            typeName.clear(); // type name is useless for alias here, so keep it empty
            if (!publicMember->statement) {
                m_logger->log(QStringLiteral("Invalid alias expression – an initalizer is needed."),
                              qmlSyntax, publicMember->memberType->firstSourceLocation()); // TODO: extend warning to cover until endSourceLocation
                return;
            }
            const auto expression = cast<ExpressionStatement *>(publicMember->statement);
            auto node = expression ? expression->expression : nullptr;
            auto fex = cast<FieldMemberExpression *>(node);
            while (fex) {
                node = fex->base;
                aliasExpr.prepend(u'.' + fex->name.toString());
                fex = cast<FieldMemberExpression *>(node);
            }

            if (const auto idExpression = cast<IdentifierExpression *>(node)) {
                aliasExpr.prepend(idExpression->name.toString());
            } else {
                // cast to expression might have failed above, so use publicMember->statement
                // to obtain the source location
                m_logger->log(QStringLiteral("Invalid alias expression. Only IDs and field "
                                             "member expressions can be aliased."),
                              qmlSyntax, publicMember->statement->firstSourceLocation());
            }
            };
            tryParseAlias();
        } else {
            if (m_rootScopeImports.hasType(typeName)
                && !m_rootScopeImports.type(typeName).scope.isNull()) {
                if (m_importTypeLocationMap.contains(typeName))
                    m_usedTypes.insert(typeName);
            }
        }
        QQmlJSMetaProperty prop;
        prop.setPropertyName(publicMember->name.toString());
        prop.setIsList(publicMember->typeModifier == QLatin1String("list"));
        prop.setIsWritable(!publicMember->isReadonly());
        prop.setAliasExpression(aliasExpr);
        const auto type =
                isAlias ? QQmlJSScope::ConstPtr() : m_rootScopeImports.type(typeName).scope;
        if (type) {
            prop.setType(prop.isList() ? type->listType() : type);
            const QString internalName = type->internalName();
            prop.setTypeName(internalName.isEmpty() ? typeName : internalName);
        } else if (!isAlias) {
            m_pendingPropertyTypes << PendingPropertyType { m_currentScope, prop.propertyName(),
                                                            publicMember->firstSourceLocation() };
            prop.setTypeName(typeName);
        }
        prop.setAnnotations(parseAnnotations(publicMember->annotations));
        if (publicMember->isDefaultMember())
            m_currentScope->setOwnDefaultPropertyName(prop.propertyName());
        prop.setIndex(m_currentScope->ownProperties().size());
        m_currentScope->insertPropertyIdentifier(prop);
        if (publicMember->isRequired())
            m_currentScope->setPropertyLocallyRequired(prop.propertyName(), true);

        BindingExpressionParseResult parseResult = BindingExpressionParseResult::Invalid;
        // if property is an alias, initialization expression is not a binding
        if (!isAlias) {
            parseResult =
                    parseBindingExpression(publicMember->name.toString(), publicMember->statement);
        }

        // however, if we have a property with a script binding assigned to it,
        // we have to create a new scope
        if (parseResult == BindingExpressionParseResult::Script) {
            Q_ASSERT(!m_savedBindingOuterScope); // automatically true due to grammar
            m_savedBindingOuterScope = m_currentScope;
            enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, QStringLiteral("binding"),
                             publicMember->statement->firstSourceLocation());
        }

        break;
    }
    }

    return true;
}

void QQmlJSImportVisitor::endVisit(UiPublicMember *publicMember)
{
    if (m_savedBindingOuterScope) {
        m_currentScope = m_savedBindingOuterScope;
        m_savedBindingOuterScope = {};
        // m_savedBindingOuterScope is only set if we encounter a script binding
        forgetFunctionExpression(publicMember->name.toString());
    }
}

bool QQmlJSImportVisitor::visit(UiRequired *required)
{
    const QString name = required->name.toString();

    m_requiredProperties << RequiredProperty { m_currentScope, name,
                                               required->firstSourceLocation() };

    m_currentScope->setPropertyLocallyRequired(name, true);
    return true;
}

void QQmlJSImportVisitor::visitFunctionExpressionHelper(QQmlJS::AST::FunctionExpression *fexpr)
{
    using namespace QQmlJS::AST;
    auto name = fexpr->name.toString();
    bool pending = false;
    if (!name.isEmpty()) {
        QQmlJSMetaMethod method(name);
        method.setMethodType(QQmlJSMetaMethodType::Method);
        method.setSourceLocation(combine(fexpr->firstSourceLocation(), fexpr->lastSourceLocation()));

        if (!m_pendingMethodAnnotations.isEmpty()) {
            method.setAnnotations(m_pendingMethodAnnotations);
            m_pendingMethodAnnotations.clear();
        }

        // If signatures are explicitly ignored, we don't parse the types
        const bool parseTypes = m_scopesById.signaturesAreEnforced();

        bool formalsFullyTyped = parseTypes;
        bool anyFormalTyped = false;
        if (const auto *formals = parseTypes ? fexpr->formals : nullptr) {
            const auto parameters = formals->formals();
            for (const auto &parameter : parameters) {
                const QString type = parameter.typeAnnotation
                        ? parameter.typeAnnotation->type->toString()
                        : QString();
                if (type.isEmpty()) {
                    formalsFullyTyped = false;
                    method.addParameter(QQmlJSMetaParameter(parameter.id, QStringLiteral("var")));
                }  else {
                    anyFormalTyped = true;
                    method.addParameter(QQmlJSMetaParameter(parameter.id, type));
                    if (!pending) {
                        m_pendingMethodTypes << PendingMethodType{
                            m_currentScope,
                            name,
                            combine(parameter.typeAnnotation->firstSourceLocation(),
                                    parameter.typeAnnotation->lastSourceLocation())
                        };
                        pending = true;
                    }
                }
            }
        }

        // If a function is fully typed, we can call it like a C++ function.
        method.setIsJavaScriptFunction(!formalsFullyTyped);

        // Methods with explicit return type return that.
        // Methods with only untyped arguments return an untyped value.
        // Methods with at least one typed argument but no explicit return type return void.
        // In order to make a function without arguments return void, you have to specify that.
        if (parseTypes && fexpr->typeAnnotation) {
            method.setReturnTypeName(fexpr->typeAnnotation->type->toString());
            if (!pending) {
                m_pendingMethodTypes << PendingMethodType{
                    m_currentScope, name,
                    combine(fexpr->typeAnnotation->firstSourceLocation(),
                            fexpr->typeAnnotation->lastSourceLocation())
                };
                pending = true;
            }
        } else if (anyFormalTyped)
            method.setReturnTypeName(QStringLiteral("void"));
        else
            method.setReturnTypeName(QStringLiteral("var"));

        method.setJsFunctionIndex(addFunctionOrExpression(m_currentScope, method.methodName()));
        m_currentScope->addOwnMethod(method);

        if (m_currentScope->scopeType() != QQmlSA::ScopeType::QMLScope) {
            m_currentScope->insertJSIdentifier(name,
                                               { QQmlJSScope::JavaScriptIdentifier::LexicalScoped,
                                                 fexpr->firstSourceLocation(),
                                                 method.returnTypeName(), false });
        }
        enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, name, fexpr->firstSourceLocation());
    } else {
        addFunctionOrExpression(m_currentScope, QStringLiteral("<anon>"));
        enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, QStringLiteral("<anon>"),
                         fexpr->firstSourceLocation());
    }
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::FunctionExpression *fexpr)
{
    visitFunctionExpressionHelper(fexpr);
    return true;
}

void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FunctionExpression *fexpr)
{
    forgetFunctionExpression(fexpr->name.toString());
    leaveEnvironment();
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiSourceElement *srcElement)
{
    m_pendingMethodAnnotations = parseAnnotations(srcElement->annotations);
    return true;
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::FunctionDeclaration *fdecl)
{
    visitFunctionExpressionHelper(fdecl);
    return true;
}

void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FunctionDeclaration *fdecl)
{
    forgetFunctionExpression(fdecl->name.toString());
    leaveEnvironment();
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::ClassExpression *ast)
{
    QQmlJSMetaProperty prop;
    prop.setPropertyName(ast->name.toString());
    m_currentScope->addOwnProperty(prop);
    enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, ast->name.toString(),
                     ast->firstSourceLocation());
    return true;
}

void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ClassExpression *)
{
    leaveEnvironment();
}

void handleTranslationBinding(QQmlJSMetaPropertyBinding &binding, QStringView base,
                              QQmlJS::AST::ArgumentList *args)
{
    QStringView contextString;
    QStringView mainString;
    QStringView commentString;
    auto registerContextString = [&](QStringView string) {
        contextString = string;
        return 0;
    };
    auto registerMainString = [&](QStringView string) {
        mainString = string;
        return 0;
    };
    auto registerCommentString = [&](QStringView string) {
        commentString = string;
        return 0;
    };
    auto finalizeBinding = [&](QV4::CompiledData::Binding::Type type,
                               QV4::CompiledData::TranslationData data) {
        if (type == QV4::CompiledData::Binding::Type_Translation) {
            binding.setTranslation(mainString, commentString, contextString, data.number);
        } else if (type == QV4::CompiledData::Binding::Type_TranslationById) {
            binding.setTranslationId(mainString, data.number);
        } else {
            binding.setStringLiteral(mainString);
        }
    };
    QmlIR::tryGeneratingTranslationBindingBase(
                base, args,
                registerMainString, registerCommentString, registerContextString, finalizeBinding);
}

QQmlJSImportVisitor::BindingExpressionParseResult
QQmlJSImportVisitor::parseBindingExpression(const QString &name,
                                            const QQmlJS::AST::Statement *statement)
{
    if (statement == nullptr)
        return BindingExpressionParseResult::Invalid;

    const auto *exprStatement = cast<const ExpressionStatement *>(statement);

    if (exprStatement == nullptr) {
        QQmlJS::SourceLocation location = statement->firstSourceLocation();

        if (const auto *block = cast<const Block *>(statement); block && block->statements) {
            location = block->statements->firstSourceLocation();
        }

        QQmlJSMetaPropertyBinding binding(location, name);
        binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
                                 QQmlSA::ScriptBindingKind::PropertyBinding);
        m_bindings.append(UnfinishedBinding {
            m_currentScope,
            [binding = std::move(binding)]() { return binding; }
        });
        return BindingExpressionParseResult::Script;
    }

    auto expr = exprStatement->expression;
    QQmlJSMetaPropertyBinding binding(
                combine(expr->firstSourceLocation(), expr->lastSourceLocation()),
                name);

    bool isUndefinedBinding = false;

    switch (expr->kind) {
    case Node::Kind_TrueLiteral:
        binding.setBoolLiteral(true);
        break;
    case Node::Kind_FalseLiteral:
        binding.setBoolLiteral(false);
        break;
    case Node::Kind_NullExpression:
        binding.setNullLiteral();
        break;
    case Node::Kind_IdentifierExpression: {
        auto idExpr = QQmlJS::AST::cast<QQmlJS::AST::IdentifierExpression *>(expr);
        Q_ASSERT(idExpr);
        isUndefinedBinding = (idExpr->name == u"undefined");
        break;
    }
    case Node::Kind_NumericLiteral:
        binding.setNumberLiteral(cast<NumericLiteral *>(expr)->value);
        break;
    case Node::Kind_StringLiteral:
        binding.setStringLiteral(cast<StringLiteral *>(expr)->value);
        break;
    case Node::Kind_RegExpLiteral:
        binding.setRegexpLiteral(cast<RegExpLiteral *>(expr)->pattern);
        break;
    case Node::Kind_TemplateLiteral: {
        auto templateLit = QQmlJS::AST::cast<QQmlJS::AST::TemplateLiteral *>(expr);
        Q_ASSERT(templateLit);
        if (templateLit->hasNoSubstitution) {
            binding.setStringLiteral(templateLit->value);
        } else {
            binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
                                     QQmlSA::ScriptBindingKind::PropertyBinding);
            for (QQmlJS::AST::TemplateLiteral *l = templateLit; l; l = l->next) {
                if (QQmlJS::AST::ExpressionNode *expression = l->expression)
                    expression->accept(this);
            }
        }
        break;
    }
    default:
        if (QQmlJS::AST::UnaryMinusExpression *unaryMinus = QQmlJS::AST::cast<QQmlJS::AST::UnaryMinusExpression *>(expr)) {
            if (QQmlJS::AST::NumericLiteral *lit = QQmlJS::AST::cast<QQmlJS::AST::NumericLiteral *>(unaryMinus->expression))
                binding.setNumberLiteral(-lit->value);
        } else if (QQmlJS::AST::CallExpression *call = QQmlJS::AST::cast<QQmlJS::AST::CallExpression *>(expr)) {
            if (QQmlJS::AST::IdentifierExpression *base = QQmlJS::AST::cast<QQmlJS::AST::IdentifierExpression *>(call->base))
                handleTranslationBinding(binding, base->name, call->arguments);
        }
        break;
    }

    if (!binding.isValid()) {
        // consider this to be a script binding (see IRBuilder::setBindingValue)
        binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
                                 QQmlSA::ScriptBindingKind::PropertyBinding,
                                 isUndefinedBinding ? ScriptBindingValueType::ScriptValue_Undefined
                                                    : ScriptBindingValueType::ScriptValue_Unknown);
    }
    m_bindings.append(UnfinishedBinding { m_currentScope, [=]() { return binding; } });

    // translations are neither literal bindings nor script bindings
    if (binding.bindingType() == QQmlSA::BindingType::Translation
        || binding.bindingType() == QQmlSA::BindingType::TranslationById) {
        return BindingExpressionParseResult::Translation;
    }
    if (!QQmlJSMetaPropertyBinding::isLiteralBinding(binding.bindingType()))
        return BindingExpressionParseResult::Script;
    m_literalScopesToCheck << m_currentScope;
    return BindingExpressionParseResult::Literal;
}

bool QQmlJSImportVisitor::isImportPrefix(QString prefix) const
{
    if (prefix.isEmpty() || !prefix.front().isUpper())
        return false;

    return m_rootScopeImports.isNullType(prefix);
}

void QQmlJSImportVisitor::handleIdDeclaration(QQmlJS::AST::UiScriptBinding *scriptBinding)
{
    const auto *statement = cast<ExpressionStatement *>(scriptBinding->statement);
    if (!statement) {
        m_logger->log(u"id must be followed by an identifier"_s, qmlSyntax,
                      scriptBinding->statement->firstSourceLocation());
        return;
    }
    const QString name = [&]() {
        if (const auto *idExpression = cast<IdentifierExpression *>(statement->expression))
            return idExpression->name.toString();
        else if (const auto *idString = cast<StringLiteral *>(statement->expression)) {
            m_logger->log(u"ids do not need quotation marks"_s, qmlSyntaxIdQuotation,
                          idString->firstSourceLocation());
            return idString->value.toString();
        }
        m_logger->log(u"Failed to parse id"_s, qmlSyntax,
                      statement->expression->firstSourceLocation());
        return QString();
    }();
    if (m_scopesById.existsAnywhereInDocument(name)) {
        // ### TODO: find an alternative to breakInhertianceCycles here
        // we shouldn't need to search for the current root component in any case here
        breakInheritanceCycles(m_currentScope);
        if (auto otherScopeWithID = m_scopesById.scope(name, m_currentScope)) {
            auto otherLocation = otherScopeWithID->sourceLocation();
            // critical because subsequent analysis cannot cope with messed up ids
            // and the file is invalid
            m_logger->log(u"Found a duplicated id. id %1 was first declared at %2:%3"_s.arg(
                                  name, QString::number(otherLocation.startLine),
                                  QString::number(otherLocation.startColumn)),
                          qmlSyntaxDuplicateIds, // ??
                          scriptBinding->firstSourceLocation());
        }
    }
    if (!name.isEmpty())
        m_scopesById.insert(name, m_currentScope);
}

/*! \internal

    Creates a new binding of either a GroupProperty or an AttachedProperty type.
    The binding is added to the parentScope() of \a scope, under property name
    \a name and location \a srcLocation.
*/
inline QQmlJSImportVisitor::UnfinishedBinding
createNonUniqueScopeBinding(QQmlJSScope::Ptr &scope, const QString &name,
                            const QQmlJS::SourceLocation &srcLocation)
{
    const auto createBinding = [=]() {
        const QQmlJSScope::ScopeType type = scope->scopeType();
        Q_ASSERT(type == QQmlSA::ScopeType::GroupedPropertyScope
                 || type == QQmlSA::ScopeType::AttachedPropertyScope);
        const QQmlSA::BindingType bindingType = (type == QQmlSA::ScopeType::GroupedPropertyScope)
                ? QQmlSA::BindingType::GroupProperty
                : QQmlSA::BindingType::AttachedProperty;

        const auto propertyBindings = scope->parentScope()->ownPropertyBindings(name);
        const bool alreadyHasBinding = std::any_of(propertyBindings.first, propertyBindings.second,
                                                   [&](const QQmlJSMetaPropertyBinding &binding) {
                                                       return binding.bindingType() == bindingType;
                                                   });
        if (alreadyHasBinding) // no need to create any more
            return QQmlJSMetaPropertyBinding(QQmlJS::SourceLocation {});

        QQmlJSMetaPropertyBinding binding(srcLocation, name);
        if (type == QQmlSA::ScopeType::GroupedPropertyScope)
            binding.setGroupBinding(static_cast<QSharedPointer<QQmlJSScope>>(scope));
        else
            binding.setAttachedBinding(static_cast<QSharedPointer<QQmlJSScope>>(scope));
        return binding;
    };
    return { scope->parentScope(), createBinding };
}

bool QQmlJSImportVisitor::visit(UiScriptBinding *scriptBinding)
{
    Q_ASSERT(!m_savedBindingOuterScope); // automatically true due to grammar
    Q_ASSERT(!m_thisScriptBindingIsJavaScript); // automatically true due to grammar
    m_savedBindingOuterScope = m_currentScope;
    const auto id = scriptBinding->qualifiedId;
    if (!id->next && id->name == QLatin1String("id")) {
        handleIdDeclaration(scriptBinding);
        return true;
    }

    auto group = id;

    QString prefix;
    for (; group->next; group = group->next) {
        const QString name = group->name.toString();
        if (name.isEmpty())
            break;

        if (group == id && isImportPrefix(name)) {
            prefix = name + u'.';
            continue;
        }

        const bool isAttachedProperty = name.front().isUpper();
        if (isAttachedProperty) {
            // attached property
            enterEnvironmentNonUnique(QQmlSA::ScopeType::AttachedPropertyScope, prefix + name,
                                      group->firstSourceLocation());
        } else {
            // grouped property
            enterEnvironmentNonUnique(QQmlSA::ScopeType::GroupedPropertyScope, prefix + name,
                                      group->firstSourceLocation());
        }
        m_bindings.append(createNonUniqueScopeBinding(m_currentScope, prefix + name,
                                                      group->firstSourceLocation()));

        prefix.clear();
    }

    const auto name = group->name.toString();

    // This is a preliminary check.
    // Even if the name starts with "on", it might later turn out not to be a signal.
    const auto signal = QQmlSignalNames::handlerNameToSignalName(name);

    if (!signal.has_value() || m_currentScope->hasProperty(name)) {
        m_propertyBindings[m_currentScope].append(
                { m_savedBindingOuterScope, group->firstSourceLocation(), name });
        // ### TODO: report Invalid parse status as a warning/error
        auto result = parseBindingExpression(name, scriptBinding->statement);
        m_thisScriptBindingIsJavaScript = (result == BindingExpressionParseResult::Script);
    } else {
        const auto statement = scriptBinding->statement;
        QStringList signalParameters;

        if (ExpressionStatement *expr = cast<ExpressionStatement *>(statement)) {
            if (FunctionExpression *func = expr->expression->asFunctionDefinition()) {
                for (FormalParameterList *formal = func->formals; formal; formal = formal->next)
                    signalParameters << formal->element->bindingIdentifier.toString();
            }
        }

        QQmlJSMetaMethod scopeSignal;
        const auto methods = m_currentScope->methods(*signal, QQmlJSMetaMethodType::Signal);
        if (!methods.isEmpty())
            scopeSignal = methods[0];

        const auto firstSourceLocation = statement->firstSourceLocation();
        bool hasMultilineStatementBody =
                statement->lastSourceLocation().startLine > firstSourceLocation.startLine;
        m_pendingSignalHandler = firstSourceLocation;
        m_signalHandlers.insert(firstSourceLocation,
                                { scopeSignal.parameterNames(), hasMultilineStatementBody });

        // NB: calculate runtime index right away to avoid miscalculation due to
        // losing real AST traversal order
        const auto index = addFunctionOrExpression(m_currentScope, name);
        const auto createBinding = [
                this,
                scope = m_currentScope,
                signalName = *signal,
                index,
                name,
                firstSourceLocation,
                groupLocation = group->firstSourceLocation(),
                signalParameters]() {
            // when encountering a signal handler, add it as a script binding
            Q_ASSERT(scope->isFullyResolved());
            QQmlSA::ScriptBindingKind kind = QQmlSA::ScriptBindingKind::Invalid;
            const auto methods = scope->methods(signalName, QQmlJSMetaMethodType::Signal);
            if (!methods.isEmpty()) {
                kind = QQmlSA::ScriptBindingKind::SignalHandler;
                checkSignal(scope, groupLocation, name, signalParameters);
            } else if (QQmlJSUtils::propertyFromChangedHandler(scope, name).has_value()) {
                kind = QQmlSA::ScriptBindingKind::ChangeHandler;
                checkSignal(scope, groupLocation, name, signalParameters);
            } else if (scope->hasProperty(name)) {
                // Not a signal handler after all.
                // We can see this now because the type is fully resolved.
                kind = QQmlSA::ScriptBindingKind::PropertyBinding;
                m_signalHandlers.remove(firstSourceLocation);
            } else {
                // We already know it's bad, but let's allow checkSignal() to do its thing.
                checkSignal(scope, groupLocation, name, signalParameters);
            }

            QQmlJSMetaPropertyBinding binding(firstSourceLocation, name);
            binding.setScriptBinding(index, kind);
            return binding;
        };
        m_bindings.append(UnfinishedBinding { m_currentScope, createBinding });
        m_thisScriptBindingIsJavaScript = true;
    }

    // TODO: before leaving the scopes, we must create the binding.

    // Leave any group/attached scopes so that the binding scope doesn't see its properties.
    while (m_currentScope->scopeType() == QQmlSA::ScopeType::GroupedPropertyScope
           || m_currentScope->scopeType() == QQmlSA::ScopeType::AttachedPropertyScope) {
        leaveEnvironment();
    }

    enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, QStringLiteral("binding"),
                     scriptBinding->statement->firstSourceLocation());

    return true;
}

void QQmlJSImportVisitor::endVisit(UiScriptBinding *)
{
    if (m_savedBindingOuterScope) {
        m_currentScope = m_savedBindingOuterScope;
        m_savedBindingOuterScope = {};
    }

    // forgetFunctionExpression() but without the name check since script
    // bindings are special (script bindings only sometimes result in java
    // script bindings. e.g. a literal binding is also a UiScriptBinding)
    if (m_thisScriptBindingIsJavaScript) {
        m_thisScriptBindingIsJavaScript = false;
        Q_ASSERT(!m_functionStack.isEmpty());
        m_functionStack.pop();
    }
}

bool QQmlJSImportVisitor::visit(UiArrayBinding *arrayBinding)
{
    enterEnvironment(QQmlSA::ScopeType::QMLScope, buildName(arrayBinding->qualifiedId),
                     arrayBinding->firstSourceLocation());
    m_currentScope->setIsArrayScope(true);

    // TODO: support group/attached properties

    return true;
}

void QQmlJSImportVisitor::endVisit(UiArrayBinding *arrayBinding)
{
    // immediate children (QML scopes) of m_currentScope are the objects inside
    // the array binding. note that we always work with object bindings here as
    // this is the only kind of bindings that UiArrayBinding is created for. any
    // other expressions involving lists (e.g. `var p: [1,2,3]`) are considered
    // to be script bindings
    const auto children = m_currentScope->childScopes();
    const auto propertyName = getScopeName(m_currentScope, QQmlSA::ScopeType::QMLScope);
    leaveEnvironment();

    qsizetype i = 0;
    for (auto element = arrayBinding->members; element; element = element->next, ++i) {
        const auto &type = children[i];
        if ((type->scopeType() != QQmlSA::ScopeType::QMLScope)) {
            m_logger->log(u"Declaring an object which is not an Qml object"
                          " as a list member."_s, qmlSyntax, element->firstSourceLocation());
            return;
        }
        m_pendingPropertyObjectBindings
                << PendingPropertyObjectBinding { m_currentScope, type, propertyName,
                                                  element->firstSourceLocation(), false };
        QQmlJSMetaPropertyBinding binding(element->firstSourceLocation(), propertyName);
        binding.setObject(getScopeName(type, QQmlSA::ScopeType::QMLScope),
                          QQmlJSScope::ConstPtr(type));
        m_bindings.append(UnfinishedBinding {
            m_currentScope,
            [binding = std::move(binding)]() { return binding; },
            QQmlJSScope::ListPropertyTarget
        });
    }
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiEnumDeclaration *uied)
{
    if (m_currentScope->inlineComponentName()) {
        m_logger->log(u"Enums declared inside of inline component are ignored."_s, qmlSyntax,
                      uied->firstSourceLocation());
    }
    QQmlJSMetaEnum qmlEnum(uied->name.toString());
    qmlEnum.setIsQml(true);
    for (const auto *member = uied->members; member; member = member->next) {
        qmlEnum.addKey(member->member.toString());
        qmlEnum.addValue(int(member->value));
    }
    m_currentScope->addOwnEnumeration(qmlEnum);
    return true;
}

void QQmlJSImportVisitor::addImportWithLocation(const QString &name,
                                                const QQmlJS::SourceLocation &loc)
{
    if (m_importTypeLocationMap.contains(name)
        && m_importTypeLocationMap.values(name).contains(loc))
        return;

    m_importTypeLocationMap.insert(name, loc);

    // If it's not valid it's a builtin. We don't need to complain about it being unused.
    if (loc.isValid())
        m_importLocations.insert(loc);
}

void QQmlJSImportVisitor::importFromHost(const QString &path, const QString &prefix,
                                         const QQmlJS::SourceLocation &location)
{
    QFileInfo fileInfo(path);
    if (!fileInfo.exists()) {
        m_logger->log("File or directory you are trying to import does not exist: %1."_L1.arg(path),
                      qmlImport, location);
        return;
    }

    if (fileInfo.isFile()) {
        const auto scope = m_importer->importFile(path);
        const QString actualPrefix = prefix.isEmpty() ? scope->internalName() : prefix;
        m_rootScopeImports.setType(actualPrefix, { scope, QTypeRevision() });
        addImportWithLocation(actualPrefix, location);
    } else if (fileInfo.isDir()) {
        const auto scopes = m_importer->importDirectory(path, prefix);
        m_rootScopeImports.addTypes(scopes);
        for (auto it = scopes.types().keyBegin(), end = scopes.types().keyEnd(); it != end; it++)
            addImportWithLocation(*it, location);
    } else {
        m_logger->log(
                "%1 is neither a file nor a directory. Are sure the import path is correct?"_L1.arg(
                        path),
                qmlImport, location);
    }
}

void QQmlJSImportVisitor::importFromQrc(const QString &path, const QString &prefix,
                                        const QQmlJS::SourceLocation &location)
{
    if (const QQmlJSResourceFileMapper *mapper = m_importer->resourceFileMapper()) {
        if (mapper->isFile(path)) {
            const auto entry = m_importer->resourceFileMapper()->entry(
                    QQmlJSResourceFileMapper::resourceFileFilter(path));
            const auto scope = m_importer->importFile(entry.filePath);
            const QString actualPrefix =
                    prefix.isEmpty() ? QFileInfo(entry.resourcePath).baseName() : prefix;
            m_rootScopeImports.setType(actualPrefix, { scope, QTypeRevision() });
            addImportWithLocation(actualPrefix, location);
        } else {
            const auto scopes = m_importer->importDirectory(path, prefix);
            m_rootScopeImports.addTypes(scopes);
            for (auto it = scopes.types().keyBegin(), end = scopes.types().keyEnd(); it != end; it++)
                addImportWithLocation(*it, location);
        }
    }
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiImport *import)
{
    // construct path
    QString prefix = QLatin1String("");
    if (import->asToken.isValid()) {
        prefix += import->importId;
        if (!import->importId.isEmpty() && !import->importId.front().isUpper()) {
            m_logger->log(u"Import qualifier '%1' must start with a capital letter."_s.arg(
                                  import->importId),
                          qmlImport, import->importIdToken, true, true);
        }
    }

    const QString filename = import->fileName.toString();
    if (!filename.isEmpty()) {
        const QUrl url(filename);
        const QString scheme = url.scheme();
        const QQmlJS::SourceLocation importLocation = import->firstSourceLocation();
        if (scheme == ""_L1) {
            QFileInfo fileInfo(url.path());
            QString absolute = fileInfo.isRelative()
                    ? QDir::cleanPath(QDir(m_implicitImportDirectory).filePath(filename))
                    : filename;
            if (absolute.startsWith(u':')) {
                importFromQrc(absolute, prefix, importLocation);
            } else {
                importFromHost(absolute, prefix, importLocation);
            }
            processImportWarnings("path \"%1\""_L1.arg(url.path()), importLocation);
            return true;
        } else if (scheme == "file"_L1) {
            importFromHost(url.path(), prefix, importLocation);
            processImportWarnings("URL \"%1\""_L1.arg(url.path()), importLocation);
            return true;
        } else if (scheme == "qrc"_L1) {
            importFromQrc(":"_L1 + url.path(), prefix, importLocation);
            processImportWarnings("URL \"%1\""_L1.arg(url.path()), importLocation);
            return true;
        } else {
            m_logger->log("Unknown import syntax. Imports can be paths, qrc urls or file urls"_L1,
                          qmlImport, import->firstSourceLocation());
        }
    }

    const QString path = buildName(import->importUri);

    QStringList staticModulesProvided;

    const auto imported = m_importer->importModule(
            path, prefix, import->version ? import->version->version : QTypeRevision(),
            &staticModulesProvided);
    m_rootScopeImports.addTypes(imported);
    for (auto it = imported.types().keyBegin(), end = imported.types().keyEnd(); it != end; it++)
        addImportWithLocation(*it, import->firstSourceLocation());

    if (prefix.isEmpty()) {
        for (const QString &staticModule : staticModulesProvided) {
            // Always prefer a direct import of static module to it being imported as a dependency
            if (path != staticModule && m_importStaticModuleLocationMap.contains(staticModule))
                continue;

            m_importStaticModuleLocationMap[staticModule] = import->firstSourceLocation();
        }
    }

    processImportWarnings(QStringLiteral("module \"%1\"").arg(path), import->firstSourceLocation());
    return true;
}

#if QT_VERSION >= QT_VERSION_CHECK(6, 6, 0)
template<typename F>
void handlePragmaValues(QQmlJS::AST::UiPragma *pragma, F &&assign)
{
    for (const QQmlJS::AST::UiPragmaValueList *v = pragma->values; v; v = v->next)
        assign(v->value);
}
#else
template<typename F>
void handlePragmaValues(QQmlJS::AST::UiPragma *pragma, F &&assign)
{
    assign(pragma->value);
}
#endif

bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiPragma *pragma)
{
    if (pragma->name == u"Strict"_s) {
        // If a file uses pragma Strict, it expects to be compiled, so automatically
        // enable compiler warnings unless the level is set explicitly already (e.g.
        // by the user).

        if (!m_logger->wasCategoryChanged(qmlCompiler)) {
            // TODO: the logic here is rather complicated and may be buggy
            m_logger->setCategoryLevel(qmlCompiler, QtWarningMsg);
            m_logger->setCategoryIgnored(qmlCompiler, false);
        }
    } else if (pragma->name == u"Singleton") {
        m_rootIsSingleton = true;
    } else if (pragma->name == u"ComponentBehavior") {
        handlePragmaValues(pragma, [this, pragma](QStringView value) {
            if (value == u"Bound") {
                m_scopesById.setComponentsAreBound(true);
            } else if (value == u"Unbound") {
                m_scopesById.setComponentsAreBound(false);
            } else {
                m_logger->log(u"Unknown argument \"%1\" to pragma ComponentBehavior"_s.arg(value),
                              qmlSyntax, pragma->firstSourceLocation());
            }
        });
    } else if (pragma->name == u"FunctionSignatureBehavior") {
        handlePragmaValues(pragma, [this, pragma](QStringView value) {
            if (value == u"Enforced") {
                m_scopesById.setSignaturesAreEnforced(true);
            } else if (value == u"Ignored") {
                m_scopesById.setSignaturesAreEnforced(false);
            } else {
                m_logger->log(
                        u"Unknown argument \"%1\" to pragma FunctionSignatureBehavior"_s.arg(value),
                        qmlSyntax, pragma->firstSourceLocation());
            }
        });
    } else if (pragma->name == u"ValueTypeBehavior") {
        handlePragmaValues(pragma, [this, pragma](QStringView value) {
            if (value == u"Copy") {
                // Ignore
            } else if (value == u"Reference") {
                // Ignore
            } else if (value == u"Addressable") {
                m_scopesById.setValueTypesAreAddressable(true);
            } else if (value == u"Inaddressable") {
                m_scopesById.setValueTypesAreAddressable(false);
            } else {
                m_logger->log(u"Unknown argument \"%1\" to pragma ValueTypeBehavior"_s.arg(value),
                              qmlSyntax, pragma->firstSourceLocation());
            }
        });
    }

    return true;
}

void QQmlJSImportVisitor::throwRecursionDepthError()
{
    m_logger->log(QStringLiteral("Maximum statement or expression depth exceeded"),
                  qmlRecursionDepthErrors, QQmlJS::SourceLocation());
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::ClassDeclaration *ast)
{
    enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, ast->name.toString(),
                     ast->firstSourceLocation());
    return true;
}

void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ClassDeclaration *)
{
    leaveEnvironment();
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::ForStatement *ast)
{
    enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral("forloop"),
                     ast->firstSourceLocation());
    return true;
}

void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ForStatement *)
{
    leaveEnvironment();
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::ForEachStatement *ast)
{
    enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral("foreachloop"),
                     ast->firstSourceLocation());
    return true;
}

void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ForEachStatement *)
{
    leaveEnvironment();
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::Block *ast)
{
    enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral("block"),
                     ast->firstSourceLocation());

    if (m_pendingSignalHandler.isValid())
        flushPendingSignalParameters();

    return true;
}

void QQmlJSImportVisitor::endVisit(QQmlJS::AST::Block *)
{
    leaveEnvironment();
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::CaseBlock *ast)
{
    enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral("case"),
                     ast->firstSourceLocation());
    return true;
}

void QQmlJSImportVisitor::endVisit(QQmlJS::AST::CaseBlock *)
{
    leaveEnvironment();
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::Catch *catchStatement)
{
    enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral("catch"),
                     catchStatement->firstSourceLocation());
    m_currentScope->insertJSIdentifier(
            catchStatement->patternElement->bindingIdentifier.toString(),
            { QQmlJSScope::JavaScriptIdentifier::LexicalScoped,
              catchStatement->patternElement->firstSourceLocation(), std::nullopt,
              catchStatement->patternElement->scope == QQmlJS::AST::VariableScope::Const });
    return true;
}

void QQmlJSImportVisitor::endVisit(QQmlJS::AST::Catch *)
{
    leaveEnvironment();
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::WithStatement *ast)
{
    enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral("with"),
                     ast->firstSourceLocation());

    m_logger->log(QStringLiteral("with statements are strongly discouraged in QML "
                                 "and might cause false positives when analysing unqualified "
                                 "identifiers"),
                  qmlWith, ast->firstSourceLocation());

    return true;
}

void QQmlJSImportVisitor::endVisit(QQmlJS::AST::WithStatement *)
{
    leaveEnvironment();
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::VariableDeclarationList *vdl)
{
    while (vdl) {
        std::optional<QString> typeName;
        if (TypeAnnotation *annotation = vdl->declaration->typeAnnotation)
            if (Type *type = annotation->type)
                typeName = type->toString();

        m_currentScope->insertJSIdentifier(
                vdl->declaration->bindingIdentifier.toString(),
                { (vdl->declaration->scope == QQmlJS::AST::VariableScope::Var)
                          ? QQmlJSScope::JavaScriptIdentifier::FunctionScoped
                          : QQmlJSScope::JavaScriptIdentifier::LexicalScoped,
                  vdl->declaration->firstSourceLocation(), typeName,
                  vdl->declaration->scope == QQmlJS::AST::VariableScope::Const });
        vdl = vdl->next;
    }
    return true;
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::FormalParameterList *fpl)
{
    for (auto const &boundName : fpl->boundNames()) {

        std::optional<QString> typeName;
        if (TypeAnnotation *annotation = boundName.typeAnnotation.data())
            if (Type *type = annotation->type)
                typeName = type->toString();
        m_currentScope->insertJSIdentifier(boundName.id,
                                           { QQmlJSScope::JavaScriptIdentifier::Parameter,
                                             boundName.location, typeName, false });
    }
    return true;
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiObjectBinding *uiob)
{
    // ... __styleData: QtObject {...}

    Q_ASSERT(uiob->qualifiedTypeNameId);

    bool needsResolution = false;
    int scopesEnteredCounter = 0;

    const QString typeName = buildName(uiob->qualifiedTypeNameId);
    if (typeName.front().isLower() && typeName.contains(u'.')) {
        logLowerCaseImport(typeName, uiob->qualifiedTypeNameId->identifierToken, m_logger);
    }

    QString prefix;
    for (auto group = uiob->qualifiedId; group->next; group = group->next) {
        const QString idName = group->name.toString();

        if (idName.isEmpty())
            break;

        if (group == uiob->qualifiedId && isImportPrefix(idName)) {
            prefix = idName + u'.';
            continue;
        }

        const auto scopeKind = idName.front().isUpper() ? QQmlSA::ScopeType::AttachedPropertyScope
                                                        : QQmlSA::ScopeType::GroupedPropertyScope;

        bool exists =
                enterEnvironmentNonUnique(scopeKind, prefix + idName, group->firstSourceLocation());

        m_bindings.append(createNonUniqueScopeBinding(m_currentScope, prefix + idName,
                                                      group->firstSourceLocation()));

        ++scopesEnteredCounter;
        needsResolution = needsResolution || !exists;

        prefix.clear();
    }

    for (int i=0; i < scopesEnteredCounter; ++i) { // leave the scopes we entered again
        leaveEnvironment();
    }

    // recursively resolve types for current scope if new scopes are found
    if (needsResolution)
        QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports, &m_usedTypes);

    enterEnvironment(QQmlSA::ScopeType::QMLScope, typeName,
                     uiob->qualifiedTypeNameId->identifierToken);
    QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports, &m_usedTypes);

    m_qmlTypes.append(m_currentScope); // new QMLScope is created here, so add it
    m_objectBindingScopes << m_currentScope;
    return true;
}

void QQmlJSImportVisitor::endVisit(QQmlJS::AST::UiObjectBinding *uiob)
{
    QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports, &m_usedTypes);
    // must be mutable, as we might mark it as implicitly wrapped in a component
    const QQmlJSScope::Ptr childScope = m_currentScope;
    leaveEnvironment();

    auto group = uiob->qualifiedId;
    int scopesEnteredCounter = 0;

    QString prefix;
    for (; group->next; group = group->next) {
        const QString idName = group->name.toString();

        if (idName.isEmpty())
            break;

        if (group == uiob->qualifiedId && isImportPrefix(idName)) {
            prefix = idName + u'.';
            continue;
        }

        const auto scopeKind = idName.front().isUpper() ? QQmlSA::ScopeType::AttachedPropertyScope
                                                        : QQmlSA::ScopeType::GroupedPropertyScope;
        // definitely exists
        [[maybe_unused]] bool exists =
                enterEnvironmentNonUnique(scopeKind, prefix + idName, group->firstSourceLocation());
        Q_ASSERT(exists);
        scopesEnteredCounter++;

        prefix.clear();
    }

    // on ending the visit to UiObjectBinding, set the property type to the
    // just-visited one if the property exists and this type is valid

    const QString propertyName = group->name.toString();

    if (m_currentScope->isNameDeferred(propertyName)) {
        bool foundIds = false;
        QList<QQmlJSScope::ConstPtr> childScopes { childScope };

        while (!childScopes.isEmpty()) {
            const QQmlJSScope::ConstPtr scope = childScopes.takeFirst();
            if (!m_scopesById.id(scope, scope).isEmpty()) {
                foundIds = true;
                break;
            }

            childScopes << scope->childScopes();
        }

        if (foundIds) {
            m_logger->log(
                    u"Cannot defer property assignment to \"%1\". Assigning an id to an object or one of its sub-objects bound to a deferred property will make the assignment immediate."_s
                            .arg(propertyName),
                    qmlDeferredPropertyId, uiob->firstSourceLocation());
        }
    }

    if (m_currentScope->isInCustomParserParent()) {
        // These warnings do not apply for custom parsers and their children and need to be handled
        // on a case by case basis
    } else {
        m_pendingPropertyObjectBindings
                << PendingPropertyObjectBinding { m_currentScope, childScope, propertyName,
                                                  uiob->firstSourceLocation(), uiob->hasOnToken };

        QQmlJSMetaPropertyBinding binding(uiob->firstSourceLocation(), propertyName);
        if (uiob->hasOnToken) {
            if (childScope->hasInterface(u"QQmlPropertyValueInterceptor"_s)) {
                binding.setInterceptor(getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
                                       QQmlJSScope::ConstPtr(childScope));
            } else { // if (childScope->hasInterface(u"QQmlPropertyValueSource"_s))
                binding.setValueSource(getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
                                       QQmlJSScope::ConstPtr(childScope));
            }
        } else {
            binding.setObject(getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
                              QQmlJSScope::ConstPtr(childScope));
        }
        m_bindings.append(UnfinishedBinding { m_currentScope, [=]() { return binding; } });
    }

    for (int i = 0; i < scopesEnteredCounter; ++i)
        leaveEnvironment();
}

bool QQmlJSImportVisitor::visit(ExportDeclaration *)
{
    Q_ASSERT(rootScopeIsValid());
    Q_ASSERT(m_exportedRootScope != m_globalScope);
    Q_ASSERT(m_currentScope == m_globalScope);
    m_currentScope = m_exportedRootScope;
    return true;
}

void QQmlJSImportVisitor::endVisit(ExportDeclaration *)
{
    Q_ASSERT(rootScopeIsValid());
    m_currentScope = m_exportedRootScope->parentScope();
    Q_ASSERT(m_currentScope == m_globalScope);
}

bool QQmlJSImportVisitor::visit(ESModule *module)
{
    Q_ASSERT(!rootScopeIsValid());
    enterRootScope(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral("module"),
                   module->firstSourceLocation());
    m_currentScope->setIsScript(true);
    importBaseModules();
    leaveEnvironment();
    return true;
}

void QQmlJSImportVisitor::endVisit(ESModule *)
{
    QQmlJSScope::resolveTypes(m_exportedRootScope, m_rootScopeImports, &m_usedTypes);
}

bool QQmlJSImportVisitor::visit(Program *)
{
    Q_ASSERT(m_globalScope == m_currentScope);
    Q_ASSERT(!rootScopeIsValid());
    *m_exportedRootScope = std::move(*QQmlJSScope::clone(m_currentScope));
    m_exportedRootScope->setIsScript(true);
    m_currentScope = m_exportedRootScope;
    importBaseModules();
    return true;
}

void QQmlJSImportVisitor::endVisit(Program *)
{
    QQmlJSScope::resolveTypes(m_exportedRootScope, m_rootScopeImports, &m_usedTypes);
}

void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FieldMemberExpression *fieldMember)
{
    // This is a rather rough approximation of "used type" but the "unused import"
    // info message doesn't have to be 100% accurate.
    const QString name = fieldMember->name.toString();
    if (m_importTypeLocationMap.contains(name)) {
        const QQmlJSImportedScope type = m_rootScopeImports.type(name);
        if (type.scope.isNull()) {
            if (m_rootScopeImports.hasType(name))
                m_usedTypes.insert(name);
        } else if (!type.scope->ownAttachedTypeName().isEmpty()) {
            m_usedTypes.insert(name);
        }
    }
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::IdentifierExpression *idexp)
{
    const QString name = idexp->name.toString();
    if (m_importTypeLocationMap.contains(name)) {
        m_usedTypes.insert(name);
    }

    return true;
}

bool QQmlJSImportVisitor::visit(QQmlJS::AST::PatternElement *element)
{
    // Handles variable declarations such as var x = [1,2,3].
    if (element->isVariableDeclaration()) {
        QQmlJS::AST::BoundNames names;
        element->boundNames(&names);
        for (const auto &name : names) {
            std::optional<QString> typeName;
            if (TypeAnnotation *annotation = name.typeAnnotation.data())
                if (Type *type = annotation->type)
                    typeName = type->toString();
            m_currentScope->insertJSIdentifier(
                    name.id,
                    { (element->scope == QQmlJS::AST::VariableScope::Var)
                              ? QQmlJSScope::JavaScriptIdentifier::FunctionScoped
                              : QQmlJSScope::JavaScriptIdentifier::LexicalScoped,
                      name.location, typeName,
                      element->scope == QQmlJS::AST::VariableScope::Const });
        }
    }

    return true;
}

QT_END_NAMESPACE