aboutsummaryrefslogtreecommitdiffstats
path: root/src/qmlls/qqmllsutils.cpp
blob: bc9f21d7b9022c2636924cbb5c4a7a88a0294e14 (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
// Copyright (C) 2023 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qqmllsutils_p.h"

#include <QtLanguageServer/private/qlanguageserverspectypes_p.h>
#include <QtCore/qthreadpool.h>
#include <QtCore/private/qduplicatetracker_p.h>
#include <QtCore/QRegularExpression>
#include <QtQmlDom/private/qqmldomexternalitems_p.h>
#include <QtQmlDom/private/qqmldomtop_p.h>
#include <QtQmlDom/private/qqmldomscriptelements_p.h>
#include <QtQmlDom/private/qqmldom_utils_p.h>
#include <QtQml/private/qqmlsignalnames_p.h>
#include <QtQml/private/qqmljslexer_p.h>
#include <QtQmlCompiler/private/qqmljsutils_p.h>

#include <algorithm>
#include <iterator>
#include <memory>
#include <optional>
#include <set>
#include <stack>
#include <type_traits>
#include <utility>
#include <variant>

using namespace QLspSpecification;
using namespace QQmlJS::Dom;
using namespace Qt::StringLiterals;

QT_BEGIN_NAMESPACE

Q_LOGGING_CATEGORY(QQmlLSUtilsLog, "qt.languageserver.utils")

QString QQmlLSUtils::qualifiersFrom(const DomItem &el)
{
    const bool isAccess = QQmlLSUtils::isFieldMemberAccess(el);
    if (!isAccess && !QQmlLSUtils::isFieldMemberExpression(el))
        return {};

    const DomItem fieldMemberExpressionBeginning = el.filterUp(
            [](DomType, const DomItem &item) { return !QQmlLSUtils::isFieldMemberAccess(item); },
            FilterUpOptions::ReturnOuter);
    QStringList qualifiers =
            QQmlLSUtils::fieldMemberExpressionBits(fieldMemberExpressionBeginning, el);

    QString result;
    for (const QString &qualifier : qualifiers)
        result.append(qualifier).append(QChar(u'.'));
    return result;
}

/*!
   \internal
    Helper to check if item is a Field Member Expression \c {<someExpression>.propertyName}.
*/
bool QQmlLSUtils::isFieldMemberExpression(const DomItem &item)
{
    return item.internalKind() == DomType::ScriptBinaryExpression
            && item.field(Fields::operation).value().toInteger()
            == ScriptElements::BinaryExpression::FieldMemberAccess;
}

/*!
   \internal
    Helper to check if item is a Field Member Access \c memberAccess in
    \c {<someExpression>.memberAccess}.
*/
bool QQmlLSUtils::isFieldMemberAccess(const DomItem &item)
{
    auto parent = item.directParent();
    if (!isFieldMemberExpression(parent))
        return false;

    DomItem rightHandSide = parent.field(Fields::right);
    return item == rightHandSide;
}

/*!
   \internal
    Get the bits of a field member expression, like \c{a}, \c{b} and \c{c} for \c{a.b.c}.

   stopAtChild can either be an FieldMemberExpression, a ScriptIdentifierExpression or a default
   constructed DomItem: This exits early before processing Field::right of an
   FieldMemberExpression stopAtChild, or before processing a ScriptIdentifierExpression stopAtChild.
   No early exits if stopAtChild is default constructed.
*/
QStringList QQmlLSUtils::fieldMemberExpressionBits(const DomItem &item, const DomItem &stopAtChild)
{
    const bool isAccess = isFieldMemberAccess(item);
    const bool isExpression = isFieldMemberExpression(item);

    // assume it is a non-qualified name
    if (!isAccess && !isExpression)
        return { item.value().toString() };

    const DomItem stopMarker =
            isFieldMemberExpression(stopAtChild) ? stopAtChild : stopAtChild.directParent();

    QStringList result;
    DomItem current =
            isAccess ? item.directParent() : (isFieldMemberExpression(item) ? item : DomItem{});

    for (; isFieldMemberExpression(current); current = current.field(Fields::right)) {
        result << current.field(Fields::left).value().toString();

        if (current == stopMarker)
            return result;
    }
    result << current.value().toString();

    return result;
}

/*!
   \internal
   The language server protocol calls "URI" what QML calls "URL".
   According to RFC 3986, a URL is a special case of URI that not only
   identifies a resource but also shows how to access it.
   In QML, however, URIs are distinct from URLs. URIs are the
   identifiers of modules, for example "QtQuick.Controls".
   In order to not confuse the terms we interpret language server URIs
   as URLs in the QML code model.
   This method marks a point of translation between the terms, but does
   not have to change the actual URI/URL.

   \sa QQmlLSUtils::qmlUriToLspUrl
 */
QByteArray QQmlLSUtils::lspUriToQmlUrl(const QByteArray &uri)
{
    return uri;
}

QByteArray QQmlLSUtils::qmlUrlToLspUri(const QByteArray &url)
{
    return url;
}

/*!
   \internal
   \brief Converts a QQmlJS::SourceLocation to a LSP Range.

   QQmlJS::SourceLocation starts counting lines and rows at 1, but the LSP Range starts at 0.
   Also, the QQmlJS::SourceLocation contains startLine, startColumn and length while the LSP Range
   contains startLine, startColumn, endLine and endColumn, which must be computed from the actual
   qml code.
 */
QLspSpecification::Range QQmlLSUtils::qmlLocationToLspLocation(const QString &code,
                                                               QQmlJS::SourceLocation qmlLocation)
{
    Range range;

    range.start.line = qmlLocation.startLine - 1;
    range.start.character = qmlLocation.startColumn - 1;

    auto end = QQmlLSUtils::textRowAndColumnFrom(code, qmlLocation.end());
    range.end.line = end.line;
    range.end.character = end.character;
    return range;
}

/*!
   \internal
   \brief Convert a text position from (line, column) into an offset.

   Row, Column and the offset are all 0-based.
   For example, \c{s[textOffsetFrom(s, 5, 55)]} returns the character of s at line 5 and column 55.

   \sa QQmlLSUtils::textRowAndColumnFrom
*/
qsizetype QQmlLSUtils::textOffsetFrom(const QString &text, int row, int column)
{
    int targetLine = row;
    qsizetype i = 0;
    while (i != text.size() && targetLine != 0) {
        QChar c = text.at(i++);
        if (c == u'\n') {
            --targetLine;
        }
        if (c == u'\r') {
            if (i != text.size() && text.at(i) == u'\n')
                ++i;
            --targetLine;
        }
    }
    qsizetype leftChars = column;
    while (i != text.size() && leftChars) {
        QChar c = text.at(i);
        if (c == u'\n' || c == u'\r')
            break;
        ++i;
        if (!c.isLowSurrogate())
            --leftChars;
    }
    return i;
}

/*!
   \internal
   \brief Convert a text position from an offset into (line, column).

   Row, Column and the offset are all 0-based.
   For example, \c{textRowAndColumnFrom(s, 55)} returns the line and columns of the
   character at \c {s[55]}.

   \sa QQmlLSUtils::textOffsetFrom
*/
QQmlLSUtilsTextPosition QQmlLSUtils::textRowAndColumnFrom(const QString &text, qsizetype offset)
{
    int row = 0;
    int column = 0;
    qsizetype currentLineOffset = 0;
    for (qsizetype i = 0; i < offset; i++) {
        QChar c = text[i];
        if (c == u'\n') {
            row++;
            currentLineOffset = i + 1;
        } else if (c == u'\r') {
            if (i > 0 && text[i - 1] == u'\n')
                currentLineOffset++;
        }
    }
    column = offset - currentLineOffset;

    return { row, column };
}

static QList<QQmlLSUtilsItemLocation>::const_iterator
handlePropertyDefinitionAndBindingOverlap(const QList<QQmlLSUtilsItemLocation> &items,
                                          qsizetype offsetInFile)
{
    auto smallest = std::min_element(
            items.begin(), items.end(),
            [](const QQmlLSUtilsItemLocation &a, const QQmlLSUtilsItemLocation &b) {
                return a.fileLocation->info().fullRegion.length
                        < b.fileLocation->info().fullRegion.length;
            });

    if (smallest->domItem.internalKind() == DomType::Binding) {
        // weird edge case: the filelocations of property definitions and property bindings are
        // actually overlapping, which means that qmlls cannot distinguish between bindings and
        // bindings in property definitions. Those need to be treated differently for
        // autocompletion, for example.
        // Therefore: when inside a binding and a propertydefinition, choose the property definition
        // if offsetInFile is before the colon, like for example:
        // property var helloProperty: Rectangle { /*...*/ }
        // |----return propertydef---|-- return Binding ---|

        // get the smallest property definition to avoid getting the property definition that the
        // current QmlObject is getting bound to!
        auto smallestPropertyDefinition = std::min_element(
                items.begin(), items.end(),
                [](const QQmlLSUtilsItemLocation &a, const QQmlLSUtilsItemLocation &b) {
                    // make property definition smaller to avoid getting smaller items that are not
                    // property definitions
                    const bool aIsPropertyDefinition =
                            a.domItem.internalKind() == DomType::PropertyDefinition;
                    const bool bIsPropertyDefinition =
                            b.domItem.internalKind() == DomType::PropertyDefinition;
                    return aIsPropertyDefinition > bIsPropertyDefinition
                            && a.fileLocation->info().fullRegion.length
                            < b.fileLocation->info().fullRegion.length;
                });

        if (smallestPropertyDefinition->domItem.internalKind() != DomType::PropertyDefinition)
            return smallest;

        const auto propertyDefinitionColon =
                smallestPropertyDefinition->fileLocation->info().regions[ColonTokenRegion];
        const auto smallestColon = smallest->fileLocation->info().regions[ColonTokenRegion];
        // sanity check: is it the definition of the current binding? check if they both have their
        // ':' at the same location
        if (propertyDefinitionColon.isValid() && propertyDefinitionColon == smallestColon
            && offsetInFile < smallestColon.offset) {
            return smallestPropertyDefinition;
        }
    }
    return smallest;
}

static QList<QQmlLSUtilsItemLocation>
filterItemsFromTextLocation(const QList<QQmlLSUtilsItemLocation> &items, qsizetype offsetInFile)
{
    if (items.size() < 2)
        return items;

    // if there are multiple items, take the smallest one + its neighbors
    // this allows to prefer inline components over main components, when both contain the
    // current textposition, and to disregard internal structures like property maps, which
    // "contain" everything from their first-appearing to last-appearing property (e.g. also
    // other stuff in between those two properties).

    QList<QQmlLSUtilsItemLocation> filteredItems;

    auto smallest = handlePropertyDefinitionAndBindingOverlap(items, offsetInFile);

    filteredItems.append(*smallest);

    const QQmlJS::SourceLocation smallestLoc = smallest->fileLocation->info().fullRegion;
    const quint32 smallestBegin = smallestLoc.begin();
    const quint32 smallestEnd = smallestLoc.end();

    for (auto it = items.begin(); it != items.end(); it++) {
        if (it == smallest)
            continue;

        const QQmlJS::SourceLocation itLoc = it->fileLocation->info().fullRegion;
        const quint32 itBegin = itLoc.begin();
        const quint32 itEnd = itLoc.end();
        if (itBegin == smallestEnd || smallestBegin == itEnd) {
            filteredItems.append(*it);
        }
    }
    return filteredItems;
}

/*!
    \internal
    \brief Find the DomItem representing the object situated in file at given line and
   character/column.

    If line and character point between two objects, two objects might be returned.
    If line and character point to whitespace, it might return an inner node of the QmlDom-Tree.
 */
QList<QQmlLSUtilsItemLocation> QQmlLSUtils::itemsFromTextLocation(const DomItem &file, int line,
                                                                  int character)
{
    QList<QQmlLSUtilsItemLocation> itemsFound;
    std::shared_ptr<QmlFile> filePtr = file.ownerAs<QmlFile>();
    if (!filePtr)
        return itemsFound;
    FileLocations::Tree t = filePtr->fileLocationsTree();
    Q_ASSERT(t);
    QString code = filePtr->code(); // do something more advanced wrt to changes wrt to this->code?
    QList<QQmlLSUtilsItemLocation> toDo;
    qsizetype targetPos = textOffsetFrom(code, line, character);
    Q_ASSERT(targetPos >= 0);
    auto containsTarget = [targetPos](QQmlJS::SourceLocation l) {
        if constexpr (sizeof(qsizetype) <= sizeof(quint32)) {
            return l.begin() <= quint32(targetPos) && quint32(targetPos) <= l.end();
        } else {
            return l.begin() <= targetPos && targetPos <= l.end();
        }
    };
    if (containsTarget(t->info().fullRegion)) {
        QQmlLSUtilsItemLocation loc;
        loc.domItem = file;
        loc.fileLocation = t;
        toDo.append(loc);
    }
    while (!toDo.isEmpty()) {
        QQmlLSUtilsItemLocation iLoc = toDo.last();
        toDo.removeLast();

        bool inParentButOutsideChildren = true;

        auto subEls = iLoc.fileLocation->subItems();
        for (auto it = subEls.begin(); it != subEls.end(); ++it) {
            auto subLoc = std::static_pointer_cast<AttachedInfoT<FileLocations>>(it.value());
            Q_ASSERT(subLoc);

            if (containsTarget(subLoc->info().fullRegion)) {
                QQmlLSUtilsItemLocation subItem;
                subItem.domItem = iLoc.domItem.path(it.key());
                if (!subItem.domItem) {
                    qCDebug(QQmlLSUtilsLog)
                            << "A DomItem child is missing or the FileLocationsTree structure does "
                               "not follow the DomItem Structure.";
                    continue;
                }
                // the parser inserts empty Script Expressions for bindings that are not completely
                // written out yet. Ignore them here.
                if (subItem.domItem.internalKind() == DomType::ScriptExpression
                    && subLoc->info().fullRegion.length == 0) {
                    continue;
                }
                subItem.fileLocation = subLoc;
                toDo.append(subItem);
                inParentButOutsideChildren = false;
            }
        }
        if (inParentButOutsideChildren) {
            itemsFound.append(iLoc);
        }
    }

    // filtering step:
    auto filtered = filterItemsFromTextLocation(itemsFound, targetPos);
    return filtered;
}

DomItem QQmlLSUtils::baseObject(const DomItem &object)
{
    DomItem prototypes;
    DomItem qmlObject = object.qmlObject();
    // object is (or is inside) an inline component definition
    if (object.internalKind() == DomType::QmlComponent || !qmlObject) {
        prototypes = object.component()
                             .field(Fields::objects)
                             .index(0)
                             .field(QQmlJS::Dom::Fields::prototypes);
    } else {
        // object is (or is inside) a QmlObject
        prototypes = qmlObject.field(QQmlJS::Dom::Fields::prototypes);
    }
    switch (prototypes.indexes()) {
    case 0:
        return {};
    case 1:
        break;
    default:
        qDebug() << "Multiple prototypes found for " << object.name() << ", taking the first one.";
        break;
    }
    QQmlJS::Dom::DomItem base = prototypes.index(0).proceedToScope();
    return base;
}

static std::optional<QQmlLSUtilsLocation> locationFromDomItem(const DomItem &item,
                                                              FileLocationRegion region)
{
    QQmlLSUtilsLocation location;
    location.filename = item.canonicalFilePath();

    auto tree = FileLocations::treeOf(item);
    // tree is null for C++ defined types, for example
    if (!tree)
        return {};

    location.sourceLocation = FileLocations::region(tree, region);
    if (!location.sourceLocation.isValid() && region != QQmlJS::Dom::MainRegion)
        location.sourceLocation = FileLocations::region(tree, MainRegion);
    return location;
}

/*!
   \internal
   \brief Returns the location of the type definition pointed by object.

   For a \c PropertyDefinition, return the location of the type of the property.
   For a \c Binding, return the bound item's type location if an QmlObject is bound, and otherwise
   the type of the property.
   For a \c QmlObject, return the location of the QmlObject's base.
   For an \c Id, return the location of the object to which the id resolves.
   For a \c Methodparameter, return the location of the type of the parameter.
   Otherwise, return std::nullopt.
 */
std::optional<QQmlLSUtilsLocation> QQmlLSUtils::findTypeDefinitionOf(const DomItem &object)
{
    DomItem typeDefinition;

    switch (object.internalKind()) {
    case QQmlJS::Dom::DomType::QmlComponent:
        typeDefinition = object.field(Fields::objects).index(0);
        break;
    case QQmlJS::Dom::DomType::QmlObject:
        typeDefinition = baseObject(object);
        break;
    case QQmlJS::Dom::DomType::Binding: {
        auto binding = object.as<Binding>();
        Q_ASSERT(binding);

        // try to grab the type from the bound object
        if (binding->valueKind() == BindingValueKind::Object) {
            typeDefinition = baseObject(object.field(Fields::value));
            break;
        } else {
            // use the type of the property it is bound on for scriptexpression etc.
            DomItem propertyDefinition;
            const QString bindingName = binding->name();
            object.containingObject().visitLookup(
                    bindingName,
                    [&propertyDefinition](const DomItem &item) {
                        if (item.internalKind() == QQmlJS::Dom::DomType::PropertyDefinition) {
                            propertyDefinition = item;
                            return false;
                        }
                        return true;
                    },
                    LookupType::PropertyDef);
            typeDefinition = propertyDefinition.field(Fields::type).proceedToScope();
            break;
        }
        Q_UNREACHABLE();
    }
    case QQmlJS::Dom::DomType::Id:
        typeDefinition = object.field(Fields::referredObject).proceedToScope();
        break;
    case QQmlJS::Dom::DomType::PropertyDefinition:
    case QQmlJS::Dom::DomType::MethodParameter:
    case QQmlJS::Dom::DomType::MethodInfo:
        typeDefinition = object.field(Fields::type).proceedToScope();
        break;
    case QQmlJS::Dom::DomType::ScriptIdentifierExpression: {
        if (DomItem type = object.filterUp(
                    [](DomType k, const DomItem &) { return k == DomType::ScriptType; },
                    FilterUpOptions::ReturnOuter)) {

            const QString name = fieldMemberExpressionBits(type.field(Fields::typeName)).join(u'.');
            switch (type.directParent().internalKind()) {
            case DomType::QmlObject:
                // is the type name of a QmlObject, like Item in `Item {...}`
                typeDefinition = baseObject(type.directParent());
                break;
            case DomType::QmlComponent:
                typeDefinition = type.directParent();
                return locationFromDomItem(typeDefinition, FileLocationRegion::IdentifierRegion);
                break;
            default:
                // is a type annotation, like Item in `function f(x: Item) { ... }`
                typeDefinition = object.path(Paths::lookupTypePath(name));
                if (typeDefinition.internalKind() == DomType::Export) {
                    typeDefinition = typeDefinition.field(Fields::type).get();
                }
            }
            break;
        }
        if (DomItem id = object.filterUp(
                    [](DomType k, const DomItem &) { return k == DomType::Id; },
                    FilterUpOptions::ReturnOuter)) {

            typeDefinition = id.field(Fields::referredObject).proceedToScope();
            break;
        }

        auto scope = QQmlLSUtils::resolveExpressionType(
                object, QQmlLSUtilsResolveOptions::ResolveActualTypeForFieldMemberExpression);
        if (!scope)
            return {};

        if (scope->type == QmlObjectIdIdentifier) {
            return QQmlLSUtilsLocation{ scope->semanticScope->filePath(),
                                        scope->semanticScope->sourceLocation() };
        }

        typeDefinition = QQmlLSUtils::sourceLocationToDomItem(
                object.containingFile(), scope->semanticScope->sourceLocation());
        return locationFromDomItem(typeDefinition.component(),
                                   FileLocationRegion::IdentifierRegion);
    }
    default:
        qDebug() << "QQmlLSUtils::findTypeDefinitionOf: Found unimplemented Type"
                 << object.internalKindStr();
        return {};
    }

    return locationFromDomItem(typeDefinition, FileLocationRegion::MainRegion);
}

static bool findDefinitionFromItem(const DomItem &item, const QString &name)
{
    if (const QQmlJSScope::ConstPtr &scope = item.semanticScope()) {
        qCDebug(QQmlLSUtilsLog) << "Searching for definition in" << item.internalKindStr();
        if (auto jsIdentifier = scope->ownJSIdentifier(name)) {
            qCDebug(QQmlLSUtilsLog) << "Found scope" << scope->baseTypeName();
            return true;
        }
    }
    return false;
}

static DomItem findJSIdentifierDefinition(const DomItem &item, const QString &name)
{
    DomItem definitionOfItem;
    item.visitUp([&name, &definitionOfItem](const DomItem &i) {
        if (findDefinitionFromItem(i, name)) {
            definitionOfItem = i;
            return false;
        }
        // early exit: no JS definitions/usages outside the ScriptExpression DOM element.
        if (i.internalKind() == DomType::ScriptExpression)
            return false;
        return true;
    });

    if (definitionOfItem)
        return definitionOfItem;

    // special case: somebody asks for usages of a function parameter from its definition
    // function parameters are defined in the method's scope
    if (DomItem res = item.filterUp([](DomType k, const DomItem &) { return k == DomType::MethodInfo; },
                                    FilterUpOptions::ReturnOuter)) {
        DomItem candidate = res.field(Fields::body).field(Fields::scriptElement);
        if (findDefinitionFromItem(candidate, name)) {
            return candidate;
        }
    }

    return definitionOfItem;
}

/*!
\internal
Represents a signal, signal handler, property, property changed signal or a property changed
handler.
 */
struct SignalOrProperty
{
    /*!
    \internal The name of the signal or property, independent of whether this is a changed signal
    or handler.
     */
    QString name;
    QQmlLSUtilsIdentifierType type;
};

/*!
\internal
\brief Find out if \c{name} is a signal, signal handler, property, property changed signal, or a
property changed handler in the given QQmlJSScope.

Heuristic to find if name is a property, property changed signal, .... because those can appear
under different names, for example \c{mySignal} and \c{onMySignal} for a signal.
This will give incorrect results as soon as properties/signals/methods are called \c{onMySignal},
\c{on<some already existing property>Changed}, ..., but the good news is that the engine also
will act weird in these cases (e.g. one cannot bind to a property called like an already existing
signal or a property changed handler).
For future reference: you can always add additional checks to check the existence of those buggy
properties/signals/methods by looking if they exist in the QQmlJSScope.
*/
static std::optional<SignalOrProperty> resolveNameInQmlScope(const QString &name,
                                                             const QQmlJSScope::ConstPtr &owner)
{
    if (owner->hasProperty(name)) {
        return SignalOrProperty{ name, PropertyIdentifier };
    }

    if (const auto propertyName = QQmlSignalNames::changedHandlerNameToPropertyName(name)) {
        if (owner->hasProperty(*propertyName)) {
            return SignalOrProperty{ *propertyName, PropertyChangedHandlerIdentifier };
        }
    }

    if (const auto signalName = QQmlSignalNames::handlerNameToSignalName(name)) {
        if (auto methods = owner->methods(*signalName); !methods.isEmpty()) {
            if (methods.front().methodType() == QQmlJSMetaMethodType::Signal) {
                return SignalOrProperty{ *signalName, SignalHandlerIdentifier };
            }
        }
    }

    if (const auto propertyName = QQmlSignalNames::changedSignalNameToPropertyName(name)) {
        if (owner->hasProperty(*propertyName)) {
            return SignalOrProperty{ *propertyName, PropertyChangedSignalIdentifier };
        }
    }

    if (auto methods = owner->methods(name); !methods.isEmpty()) {
        if (methods.front().methodType() == QQmlJSMetaMethodType::Signal) {
            return SignalOrProperty{ name, SignalIdentifier };
        }
        return SignalOrProperty{ name, MethodIdentifier };
    }
    return std::nullopt;
}

/*!
\internal
Returns a list of names, that when belonging to the same targetType, should be considered equal.
This is used to find signal handlers as usages of their corresponding signals, for example.
*/
static QStringList namesOfPossibleUsages(const QString &name,
                                        const DomItem &item,
                                         const QQmlJSScope::ConstPtr &targetType)
{
    QStringList namesToCheck = { name };
    if (item.internalKind() == DomType::EnumItem || item.internalKind() == DomType::EnumDecl)
        return namesToCheck;

    auto namings = resolveNameInQmlScope(name, targetType);
    if (!namings)
        return namesToCheck;
    switch (namings->type) {
    case PropertyIdentifier: {
        // for a property, also find bindings to its onPropertyChanged handler + propertyChanged
        // signal
        const QString propertyChangedHandler =
                QQmlSignalNames::propertyNameToChangedHandlerName(namings->name);
        namesToCheck.append(propertyChangedHandler);

        const QString propertyChangedSignal =
                QQmlSignalNames::propertyNameToChangedSignalName(namings->name);
        namesToCheck.append(propertyChangedSignal);
        break;
    }
    case PropertyChangedHandlerIdentifier: {
        // for a property changed handler, also find the usages of its property + propertyChanged
        // signal
        namesToCheck.append(namings->name);
        namesToCheck.append(QQmlSignalNames::propertyNameToChangedSignalName(namings->name));
        break;
    }
    case PropertyChangedSignalIdentifier: {
        // for a property changed signal, also find the usages of its property + onPropertyChanged
        // handlers
        namesToCheck.append(namings->name);
        namesToCheck.append(QQmlSignalNames::propertyNameToChangedHandlerName(namings->name));
        break;
    }
    case SignalIdentifier: {
        // for a signal, also find bindings to its onSignalHandler.
        namesToCheck.append(QQmlSignalNames::signalNameToHandlerName(namings->name));
        break;
    }
    case SignalHandlerIdentifier: {
        // for a signal handler, also find the usages of the signal it handles
        namesToCheck.append(namings->name);
        break;
    }
    default: {
        break;
    }
    }
    return namesToCheck;
}

template<typename Predicate>
QQmlJSScope::ConstPtr findDefiningScopeIf(QQmlJSScope::ConstPtr referrerScope, Predicate &&check)
{
    QQmlJSScope::ConstPtr result;
    QQmlJSUtils::searchBaseAndExtensionTypes(referrerScope, [&](QQmlJSScope::ConstPtr scope) {
        if (check(scope)) {
            result = scope;
            return true;
        }
        return false;
    });

    return result;
}

/*!
\internal
\brief Finds the scope where a property is first defined.

Starts looking for the name starting from the given scope and traverse through base and
extension types.
*/
static QQmlJSScope::ConstPtr findDefiningScopeForProperty(QQmlJSScope::ConstPtr referrerScope,
                                                          const QString &nameToCheck)
{
    return findDefiningScopeIf(referrerScope, [&nameToCheck](const QQmlJSScope::ConstPtr &scope) {
        return scope->hasOwnProperty(nameToCheck);
    });
}

/*!
\internal
See also findDefiningScopeForProperty().

Special case: you can also bind to a signal handler.
*/
static QQmlJSScope::ConstPtr findDefiningScopeForBinding(QQmlJSScope::ConstPtr referrerScope,
                                                         const QString &nameToCheck)
{
    return findDefiningScopeIf(referrerScope, [&nameToCheck](const QQmlJSScope::ConstPtr &scope) {
        return scope->hasOwnProperty(nameToCheck) || scope->hasOwnMethod(nameToCheck);
    });
}

/*!
\internal
See also findDefiningScopeForProperty().
*/
static QQmlJSScope::ConstPtr findDefiningScopeForMethod(QQmlJSScope::ConstPtr referrerScope,
                                                        const QString &nameToCheck)
{
    return findDefiningScopeIf(referrerScope, [&nameToCheck](const QQmlJSScope::ConstPtr &scope) {
        return scope->hasOwnMethod(nameToCheck);
    });
}

/*!
\internal
See also findDefiningScopeForProperty().
*/
static QQmlJSScope::ConstPtr findDefiningScopeForEnumeration(QQmlJSScope::ConstPtr referrerScope,
                                                             const QString &nameToCheck)
{
    return findDefiningScopeIf(referrerScope, [&nameToCheck](const QQmlJSScope::ConstPtr &scope) {
        return scope->hasOwnEnumeration(nameToCheck);
    });
}

/*!
\internal
See also findDefiningScopeForProperty().
*/
static QQmlJSScope::ConstPtr findDefiningScopeForEnumerationKey(QQmlJSScope::ConstPtr referrerScope,
                                                          const QString &nameToCheck)
{
    return findDefiningScopeIf(referrerScope, [&nameToCheck](const QQmlJSScope::ConstPtr &scope) {
        return scope->hasOwnEnumerationKey(nameToCheck);
    });
}

/*!
    Filter away the parts of the Dom not needed for find usages, by following the profiler's
   information.
    1. "propertyInfos" tries to require all inherited properties of some QmlObject. That is super
   slow (profiler says it eats 90% of the time needed by `tst_qmlls_utils findUsages`!) and is not
   needed for usages.
    2. "get" tries to resolve references, like base types saved in prototypes for example, and is not
   needed to find usages. Profiler says it eats 70% of the time needed by `tst_qmlls_utils
   findUsages`.
    3. "defaultPropertyName" also recurses through base types and is not needed to find usages.
*/
static FieldFilter filterForFindUsages()
{
    FieldFilter filter{ {},
                        {
                                { QString(), QString::fromUtf16(Fields::propertyInfos) },
                                { QString(), QString::fromUtf16(Fields::defaultPropertyName) },
                                { QString(), QString::fromUtf16(Fields::get) },
                        } };
    return filter;
};

static void findUsagesOfNonJSIdentifiers(const DomItem &item, const QString &name,
                                         QList<QQmlLSUtilsLocation> &result)
{
    const auto expressionType = QQmlLSUtils::resolveExpressionType(item, ResolveOwnerType);
    if (!expressionType)
        return;

    const QStringList namesToCheck = namesOfPossibleUsages(name, item, expressionType->semanticScope);

    const auto addLocationIfTypeMatchesTarget = [&result,
                                                 &expressionType](const DomItem &toBeResolved,
                                                                  FileLocationRegion subRegion) {
        const auto currentType = QQmlLSUtils::resolveExpressionType(
                toBeResolved, QQmlLSUtilsResolveOptions::ResolveOwnerType);
        if (!currentType)
            return;

        const QQmlJSScope::ConstPtr target = expressionType->semanticScope;
        const QQmlJSScope::ConstPtr current = currentType->semanticScope;
        if (target == current) {
            auto tree = FileLocations::treeOf(toBeResolved);
            QQmlJS::SourceLocation sourceLocation;

            sourceLocation = FileLocations::region(tree, subRegion);
            if (!sourceLocation.isValid())
                return;

            QQmlLSUtilsLocation location{ toBeResolved.canonicalFilePath(), sourceLocation };
            if (!result.contains(location))
                result.append(location);
        }
    };

    auto findUsages = [&addLocationIfTypeMatchesTarget, &name,
                       &namesToCheck](Path, const DomItem &current, bool) -> bool {
        bool continueForChildren = true;
        if (auto scope = current.semanticScope()) {
            // is the current property shadowed by some JS identifier? ignore current + its children
            if (scope->ownJSIdentifier(name)) {
                return false;
            }
        }
        switch (current.internalKind()) {
        case DomType::QmlObject:
        case DomType::Binding:
        case DomType::MethodInfo:
        case DomType::PropertyDefinition: {
            const QString propertyName = current.field(Fields::name).value().toString();
            if (namesToCheck.contains(propertyName))
                addLocationIfTypeMatchesTarget(current, IdentifierRegion);
            return continueForChildren;
        }
        case DomType::ScriptIdentifierExpression: {
            const QString identifierName = current.field(Fields::identifier).value().toString();
            if (namesToCheck.contains(identifierName))
                addLocationIfTypeMatchesTarget(current, MainRegion);
            return continueForChildren;
        }
        case DomType::ScriptLiteral: {
            const QString literal = current.field(Fields::value).value().toString();
            if (namesToCheck.contains(literal))
                addLocationIfTypeMatchesTarget(current, MainRegion);
            return continueForChildren;
        }
        case DomType::EnumItem: {
            // Only look for the first enum defined. The inner enums
            // have no way to be accessed.
            const auto parentPath = current.containingObject().pathFromOwner();
            const auto index = parentPath.last().headIndex();
            if (index != 0)
                return continueForChildren;
            const QString enumValue = current.field(Fields::name).value().toString();
            if (namesToCheck.contains(enumValue))
                addLocationIfTypeMatchesTarget(current, IdentifierRegion);
            return continueForChildren;
        }
        case DomType::EnumDecl: {
            // Only look for the first enum defined. The inner enums
            // have no way to be accessed.
            const auto parentPath = current.pathFromOwner();
            const auto index = parentPath.last().headIndex();
            if (index != 0)
                return continueForChildren;
            const QString enumValue = current.field(Fields::name).value().toString();
            if (namesToCheck.contains(enumValue))
                addLocationIfTypeMatchesTarget(current, IdentifierRegion);
            return continueForChildren;
        }
        default:
            return continueForChildren;
        };

        Q_UNREACHABLE_RETURN(continueForChildren);
    };

    const DomItem qmlFiles = item.top().field(Fields::qmlFileWithPath);
    const auto filter = filterForFindUsages();
    for (const QString &file : qmlFiles.keys()) {
        const DomItem currentFileComponents =
                qmlFiles.key(file).field(Fields::currentItem).field(Fields::components);
        currentFileComponents.visitTree(Path(), emptyChildrenVisitor,
                                        VisitOption::Recurse | VisitOption::VisitSelf, findUsages,
                                        emptyChildrenVisitor, filter);
    }
}

static QQmlLSUtilsLocation locationFromJSIdentifierDefinition(const DomItem &definitionOfItem,
                                                              const QString &name)
{
    Q_ASSERT_X(!definitionOfItem.semanticScope().isNull()
                       && definitionOfItem.semanticScope()->ownJSIdentifier(name).has_value(),
               "QQmlLSUtils::locationFromJSIdentifierDefinition",
               "JS definition does not actually define the JS identifier. "
               "Did you obtain definitionOfItem from findJSIdentifierDefinition() ?");
    QQmlJS::SourceLocation location =
            definitionOfItem.semanticScope()->ownJSIdentifier(name).value().location;

    QQmlLSUtilsLocation result = { definitionOfItem.canonicalFilePath(), location };
    return result;
}

static void findUsagesHelper(
        const DomItem &item, const QString &name, QList<QQmlLSUtilsLocation> &result)
{
    qCDebug(QQmlLSUtilsLog) << "Looking for JS identifier with name" << name;
    DomItem definitionOfItem = findJSIdentifierDefinition(item, name);

    // if there is no definition found: check if name was a property or an id instead
    if (!definitionOfItem) {
        qCDebug(QQmlLSUtilsLog) << "No defining JS-Scope found!";
        findUsagesOfNonJSIdentifiers(item, name, result);
        return;
    }

    definitionOfItem.visitTree(
            Path(), emptyChildrenVisitor, VisitOption::VisitAdopted | VisitOption::Recurse,
            [&name, &result](Path, const DomItem &item, bool) -> bool {
                qCDebug(QQmlLSUtilsLog) << "Visiting a " << item.internalKindStr();
                if (item.internalKind() == DomType::ScriptIdentifierExpression
                    && item.field(Fields::identifier).value().toString() == name) {
                    // add this usage
                    auto fileLocation = FileLocations::treeOf(item);
                    if (!fileLocation) {
                        qCWarning(QQmlLSUtilsLog) << "Failed finding filelocation of found usage";
                        return true;
                    }
                    const QQmlJS::SourceLocation location = fileLocation->info().fullRegion;
                    const QString fileName = item.canonicalFilePath();
                    result.append({ fileName, location });
                    return true;
                } else if (QQmlJSScope::ConstPtr scope = item.semanticScope();
                           scope && scope->ownJSIdentifier(name)) {
                    // current JS identifier has been redefined, do not visit children
                    return false;
                }
                return true;
            },
            emptyChildrenVisitor, filterForFindUsages());

    const QQmlLSUtilsLocation definition =
            locationFromJSIdentifierDefinition(definitionOfItem, name);
    if (!result.contains(definition))
        result.append(definition);
}

QList<QQmlLSUtilsLocation> QQmlLSUtils::findUsagesOf(const DomItem &item)
{
    QList<QQmlLSUtilsLocation> result;

    switch (item.internalKind()) {
    case DomType::ScriptIdentifierExpression: {
        const QString name = item.field(Fields::identifier).value().toString();
        findUsagesHelper(item, name, result);
        break;
    }
    case DomType::ScriptVariableDeclarationEntry: {
        const QString name = item.field(Fields::identifier).value().toString();
        findUsagesHelper(item, name, result);
        break;
    }
    case DomType::EnumDecl:
    case DomType::EnumItem:
    case DomType::QmlObject:
    case DomType::PropertyDefinition:
    case DomType::Binding:
    case DomType::MethodInfo: {
        const QString name = item.field(Fields::name).value().toString();
        findUsagesHelper(item, name, result);
        break;
    }
    case DomType::QmlComponent: {
        QString name = item.field(Fields::name).value().toString();

        // get rid of extra qualifiers
        if (const auto dotIndex = name.indexOf(u'.'); dotIndex != -1)
            name = name.sliced(dotIndex + 1);
        findUsagesHelper(item, name, result);
        break;
    }
    default:
        qCDebug(QQmlLSUtilsLog) << item.internalKindStr()
                                << "was not implemented for QQmlLSUtils::findUsagesOf";
        return result;
    }

    std::sort(result.begin(), result.end());

    if (QQmlLSUtilsLog().isDebugEnabled()) {
        qCDebug(QQmlLSUtilsLog) << "Found following usages:";
        for (auto r : result) {
            qCDebug(QQmlLSUtilsLog)
                    << r.filename << " @ " << r.sourceLocation.startLine << ":"
                    << r.sourceLocation.startColumn << " with length " << r.sourceLocation.length;
        }
    }

    return result;
}

static std::optional<QQmlLSUtilsIdentifierType>
hasMethodOrSignal(const QQmlJSScope::ConstPtr &scope, const QString &name)
{
    auto methods = scope->methods(name);
    if (methods.isEmpty())
        return {};

    const bool isSignal = methods.front().methodType() == QQmlJSMetaMethodType::Signal;
    QQmlLSUtilsIdentifierType type = isSignal ? QQmlLSUtilsIdentifierType::SignalIdentifier
                                             : QQmlLSUtilsIdentifierType::MethodIdentifier;
    return type;
}

/*!
\internal
Searches for a method by traversing the parent scopes.

We assume here that it is possible to call methods from parent scope to simplify things, as the
linting module already warns about calling methods from parent scopes.

Note: in QML, one can only call methods from the current scope, and from the QML file root scope.
Everything else needs a qualifier.
*/
static std::optional<QQmlLSUtilsExpressionType>
methodFromReferrerScope(const QQmlJSScope::ConstPtr &referrerScope, const QString &name,
                        QQmlLSUtilsResolveOptions options)
{
    for (QQmlJSScope::ConstPtr current = referrerScope; current; current = current->parentScope()) {
        if (auto type = hasMethodOrSignal(current, name)) {
            switch (options) {
            case ResolveOwnerType:
                return QQmlLSUtilsExpressionType{ name,
                                                  findDefiningScopeForMethod(current, name),
                                                  *type };
            case ResolveActualTypeForFieldMemberExpression:
                // QQmlJSScopes were not implemented for methods yet, but JS functions have methods
                // and properties see
                // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
                // for the list of properties/methods of functions. Therefore return a null scope.
                // see also code below for non-qualified method access
                return QQmlLSUtilsExpressionType{ name, {}, *type };
            }
        }

        if (const auto signalName = QQmlSignalNames::handlerNameToSignalName(name)) {
            if (auto type = hasMethodOrSignal(current, *signalName)) {
                switch (options) {
                case ResolveOwnerType:
                    return QQmlLSUtilsExpressionType{
                        name, findDefiningScopeForMethod(current, *signalName),
                        SignalHandlerIdentifier
                    };
                case ResolveActualTypeForFieldMemberExpression:
                    // Properties and methods of JS methods are not supported yet
                    return QQmlLSUtilsExpressionType{ name, {}, SignalHandlerIdentifier };
                }
            }
        }
    }
    return {};
}


/*!
\internal
See comment on methodFromReferrerScope: the same applies to properties.
*/
static std::optional<QQmlLSUtilsExpressionType>
propertyFromReferrerScope(const QQmlJSScope::ConstPtr &referrerScope, const QString &propertyName,
                          QQmlLSUtilsResolveOptions options)
{
    for (QQmlJSScope::ConstPtr current = referrerScope; current; current = current->parentScope()) {
        const auto resolved = resolveNameInQmlScope(propertyName, current);
        if (!resolved)
            continue;

        if (auto property = current->property(resolved->name); property.isValid()) {
            switch (options) {
            case ResolveOwnerType:
                return QQmlLSUtilsExpressionType{
                    propertyName, findDefiningScopeForProperty(current, propertyName),
                    resolved->type
                };
            case ResolveActualTypeForFieldMemberExpression:
                return QQmlLSUtilsExpressionType{ propertyName, property.type(),
                                                  resolved->type };
            }
        }
    }
    return {};
}

/*!
\internal
See comment on methodFromReferrerScope: the same applies to property bindings.

If resolver is not null then it is used to resolve the id with which a generalized grouped
properties starts.
*/
static std::optional<QQmlLSUtilsExpressionType>
propertyBindingFromReferrerScope(const QQmlJSScope::ConstPtr &referrerScope, const QString &name,
                                 QQmlLSUtilsResolveOptions options,
                                 QQmlJSTypeResolver *resolverForIds)
{
    auto bindings = referrerScope->propertyBindings(name);
    if (bindings.isEmpty())
        return {};

    const auto binding = bindings.front();

    if ((binding.bindingType() != QQmlSA::BindingType::AttachedProperty)
        && (binding.bindingType() != QQmlSA::BindingType::GroupProperty))
        return {};

    const bool bindingIsAttached = binding.bindingType() == QQmlSA::BindingType::AttachedProperty;

    // Generalized grouped properties, like Bindings or PropertyChanges, for example, have bindings
    // starting in an id (like `someId.someProperty: ...`).
    // If `someid` is not a property and is a deferred name, then it should be an id.
    if (!bindingIsAttached && !referrerScope->hasProperty(name)
        && referrerScope->isNameDeferred(name)) {
        if (!resolverForIds)
            return {};

        QQmlJSRegisterContent fromId = resolverForIds->scopedType(
                referrerScope, name, QQmlJSRegisterContent::InvalidLookupIndex,
                AssumeComponentsAreBound);
        if (fromId.variant() == QQmlJSRegisterContent::ObjectById)
            return QQmlLSUtilsExpressionType{ name, fromId.type(), QmlObjectIdIdentifier };

        return QQmlLSUtilsExpressionType{ name, {}, QmlObjectIdIdentifier };
    }

    const auto typeIdentifier =
            bindingIsAttached ? AttachedTypeIdentifier : GroupedPropertyIdentifier;

    const auto getScope = [&bindingIsAttached, &binding]() -> QQmlJSScope::ConstPtr {
        if (bindingIsAttached)
            return binding.attachingType();

        return binding.groupType();
    };

    switch (options) {
    case ResolveOwnerType: {
        return QQmlLSUtilsExpressionType{
            name,
            // note: always return the type of the attached type as the owner.
            // Find usages on "Keys.", for example, should yield all usages of the "Keys"
            // attached property.
            bindingIsAttached ? getScope() : findDefiningScopeForProperty(referrerScope, name),
            typeIdentifier
        };
    }
    case ResolveActualTypeForFieldMemberExpression:
        return QQmlLSUtilsExpressionType{ name, getScope(), typeIdentifier };
    }
    Q_UNREACHABLE_RETURN({});
}

/*! \internal
    Finds the scope within the special elements like Connections,
    PropertyChanges, Bindings or AnchorChanges.
*/
static QQmlJSScope::ConstPtr findScopeOfSpecialItems(QQmlJSScope::ConstPtr scope, const DomItem &item)
{
    if (!scope)
        return {};

    const QSet<QString> specialItems = {u"QQmlConnections"_s,
                                        u"QQuickPropertyChanges"_s,
                                        u"QQmlBind"_s,
                                        u"QQuickAnchorChanges"_s};

    const auto special = QQmlJSUtils::searchBaseAndExtensionTypes(
            scope, [&specialItems](QQmlJSScope::ConstPtr visitedScope) {
                const auto typeName = visitedScope->internalName();
                if (specialItems.contains(typeName))
                    return true;
                return false;
            });

    if (!special)
        return {};

    // Perform target name search if there is binding to property "target"
    QString targetName;
    if (scope->hasOwnPropertyBindings(u"target"_s)) {
        // TODO: propagate the whole binding.
        //       We can figure out the meaning of target in more cases.

        DomItem current = item.qmlObject();
        auto target = current.bindings().key(u"target"_s).index(0);
        if (target) {
            targetName = target.field(Fields::value)
                                 .field(Fields::scriptElement)
                                 .field(Fields::identifier)
                                 .value()
                                 .toString();
        }
    }

    if (!targetName.isEmpty()) {
        // target: someId
        auto resolver = item.containingFile().ownerAs<QmlFile>()->typeResolver();
        if (!resolver)
            return {};

        // Note: It does not have to be an ID. It can be a property.
        return resolver->containedType(resolver->scopedType(scope, targetName));
    } else {
        if (item.internalKind() == DomType::Binding &&
            item.field(Fields::bindingType).value().toInteger() == int(BindingType::OnBinding)) {
                // Binding on sth : {} syntax
                // Target scope is the current scope
                return scope;
        }
        return scope->parentScope();
    }

    return {};
}

static std::optional<QQmlLSUtilsExpressionType>
resolveFieldMemberExpressionType(const DomItem &item, QQmlLSUtilsResolveOptions options)
{
    const QString name = item.field(Fields::identifier).value().toString();
    DomItem parent = item.directParent();
    auto owner = QQmlLSUtils::resolveExpressionType(
            parent.field(Fields::left),
            QQmlLSUtilsResolveOptions::ResolveActualTypeForFieldMemberExpression);
    if (!owner)
        return {};

    if (auto scope = methodFromReferrerScope(owner->semanticScope, name, options))
        return *scope;

    if (auto scope = propertyBindingFromReferrerScope(owner->semanticScope, name, options, nullptr))
        return *scope;

    if (auto scope = propertyFromReferrerScope(owner->semanticScope, name, options))
        return *scope;

    // Ignore enum usages from other files for now.
    if (owner->type == QmlComponentIdentifier) {
        // Check if name is a enum value <TypeName>.<EnumValue>
        // Enumerations should live under the root element scope of the file that defines the enum,
        // therefore use the DomItem to find the root element of the qml file instead of directly
        // using owner->semanticScope.
        const auto scope = item.goToFile(owner->semanticScope->filePath())
                                   .rootQmlObject(GoTo::MostLikely)
                                   .semanticScope();
        if (scope->hasEnumerationKey(name)) {
            return QQmlLSUtilsExpressionType{name, scope, EnumeratorValueIdentifier};
        }
        // Or it is a enum name <TypeName>.<EnumName>.<EnumValue>
        else if (scope->hasEnumeration(name)) {
            return QQmlLSUtilsExpressionType{name, scope, EnumeratorIdentifier};
        }

        // check inline components <TypeName>.<InlineComponentName>
        for (auto it = owner->semanticScope->childScopesBegin(),
                  end = owner->semanticScope->childScopesEnd();
             it != end; ++it) {
            if ((*it)->inlineComponentName() == name) {
                return QQmlLSUtilsExpressionType{ name, *it, QmlComponentIdentifier };
            }
        }
        return {};
    }

    qCDebug(QQmlLSUtilsLog) << "Could not find identifier expression for" << item.internalKindStr();
    return owner;
}

static std::optional<QQmlLSUtilsExpressionType>
resolveIdentifierExpressionType(const DomItem &item, QQmlLSUtilsResolveOptions options)
{
    if (QQmlLSUtils::isFieldMemberAccess(item)) {
        return resolveFieldMemberExpressionType(item, options);
    }

    const QString name = item.field(Fields::identifier).value().toString();

    if (DomItem definitionOfItem = findJSIdentifierDefinition(item, name)) {
        Q_ASSERT_X(!definitionOfItem.semanticScope().isNull()
                            && definitionOfItem.semanticScope()->ownJSIdentifier(name),
                    "QQmlLSUtils::findDefinitionOf",
                    "JS definition does not actually define the JS identifer. "
                    "It should be empty.");
        auto scope = definitionOfItem.semanticScope();
        auto jsIdentifier = scope->ownJSIdentifier(name);
        if (jsIdentifier->scope) {
            return QQmlLSUtilsExpressionType{ name, jsIdentifier->scope.toStrongRef(),
                                                QQmlLSUtilsIdentifierType::JavaScriptIdentifier };
        } else {
            return QQmlLSUtilsExpressionType{ name, scope,
                                                QQmlLSUtilsIdentifierType::JavaScriptIdentifier };
        }
    }

    const auto referrerScope = item.nearestSemanticScope();
    if (!referrerScope)
        return {};

    // check if its a method
    if (auto scope = methodFromReferrerScope(referrerScope, name, options))
        return scope;

    const auto resolver = item.containingFile().ownerAs<QmlFile>()->typeResolver();
    if (!resolver)
        return {};

    // check if its found as a property binding
    if (auto scope = propertyBindingFromReferrerScope(referrerScope, name, options, resolver.get()))
        return *scope;

    // check if its an (unqualified) property
    if (auto scope = propertyFromReferrerScope(referrerScope, name, options))
        return *scope;

    // Returns the baseType, can't use it with options.
    if (auto scope = resolver->typeForName(name)) {
        if (scope->isSingleton())
            return QQmlLSUtilsExpressionType{ name, scope,
                                              QQmlLSUtilsIdentifierType::SingletonIdentifier };

        if (auto attachedScope = scope->attachedType()) {
            return QQmlLSUtilsExpressionType{
                name, attachedScope, QQmlLSUtilsIdentifierType::AttachedTypeIdentifier
            };
        }

        // its a (inline) component!
        return QQmlLSUtilsExpressionType{ name, scope, QmlComponentIdentifier };
    }

    // check if its an id
    QQmlJSRegisterContent fromId =
            resolver->scopedType(referrerScope, name, QQmlJSRegisterContent::InvalidLookupIndex,
                                 AssumeComponentsAreBound);
    if (fromId.variant() == QQmlJSRegisterContent::ObjectById)
        return QQmlLSUtilsExpressionType{ name, fromId.type(), QmlObjectIdIdentifier };

    const QQmlJSScope::ConstPtr jsGlobal = resolver->jsGlobalObject();
    // check if its a JS global method
    if (auto scope = methodFromReferrerScope(jsGlobal, name, options))
        return scope;

    // check if its an JS global property
    if (auto scope = propertyFromReferrerScope(jsGlobal, name, options))
        return *scope;

    return {};
}

static std::optional<QQmlLSUtilsExpressionType>
resolveSignalOrPropertyExpressionType(const QString &name, const QQmlJSScope::ConstPtr &scope,
                                      QQmlLSUtilsResolveOptions options)
{
    auto signalOrProperty = resolveNameInQmlScope(name, scope);
    if (!signalOrProperty)
        return {};

    switch (signalOrProperty->type) {
    case PropertyIdentifier:
        switch (options) {
        case ResolveOwnerType:
            return QQmlLSUtilsExpressionType{ name, findDefiningScopeForProperty(scope, name),
                                              signalOrProperty->type };
        case ResolveActualTypeForFieldMemberExpression:
            return QQmlLSUtilsExpressionType{ name, scope->property(name).type(),
                                              signalOrProperty->type };
        }
        Q_UNREACHABLE_RETURN({});
    case PropertyChangedHandlerIdentifier:
        switch (options) {
        case ResolveOwnerType:
            return QQmlLSUtilsExpressionType{
                name, findDefiningScopeForProperty(scope, signalOrProperty->name),
                signalOrProperty->type
            };
        case ResolveActualTypeForFieldMemberExpression:
            // Properties and methods are not implemented on methods.
            Q_UNREACHABLE_RETURN({});
        }
        Q_UNREACHABLE_RETURN({});
    case SignalHandlerIdentifier:
    case PropertyChangedSignalIdentifier:
    case SignalIdentifier:
    case MethodIdentifier:
        switch (options) {
        case ResolveOwnerType: {
            return QQmlLSUtilsExpressionType{ name, findDefiningScopeForMethod(scope, name),
                                              signalOrProperty->type };
        }
        case ResolveActualTypeForFieldMemberExpression:
            // Properties and methods are not implemented on methods.
            Q_UNREACHABLE_RETURN({});
        }
        Q_UNREACHABLE_RETURN({});
    default:
        Q_UNREACHABLE_RETURN({});
    }
}

/*!
   \internal
    Resolves the type of the given DomItem, when possible (e.g., when there are enough type
    annotations).
*/
std::optional<QQmlLSUtilsExpressionType>
QQmlLSUtils::resolveExpressionType(const QQmlJS::Dom::DomItem &item,
                                   QQmlLSUtilsResolveOptions options)
{
    switch (item.internalKind()) {
    case DomType::ScriptIdentifierExpression: {
        return resolveIdentifierExpressionType(item, options);
    }
    case DomType::PropertyDefinition: {
        auto propertyDefinition = item.as<PropertyDefinition>();
        if (propertyDefinition && propertyDefinition->semanticScope()) {
            const auto &scope = propertyDefinition->semanticScope();
            switch (options) {
            case ResolveOwnerType:
                return QQmlLSUtilsExpressionType{ propertyDefinition->name, scope,
                                                  PropertyIdentifier };
            case ResolveActualTypeForFieldMemberExpression:
                // There should not be any PropertyDefinition inside a FieldMemberExpression.
                Q_UNREACHABLE_RETURN({});
            }
            Q_UNREACHABLE_RETURN({});
        }
        return {};
    }
    case DomType::Binding: {
        auto binding = item.as<Binding>();
        if (binding) {
            std::optional<QQmlJSScope::ConstPtr> owner = item.qmlObject().semanticScope();
            if (!owner)
                return {};
            const QString name = binding->name();

            if (name == u"id")
                return QQmlLSUtilsExpressionType{ name, owner.value(), QmlObjectIdIdentifier };

            if (QQmlJSScope::ConstPtr targetScope = findScopeOfSpecialItems(owner.value(), item)) {
                const auto signalOrProperty = resolveNameInQmlScope(name, targetScope);
                if (!signalOrProperty)
                    return {};
                switch (options) {
                case ResolveOwnerType:
                    return QQmlLSUtilsExpressionType{
                        name, findDefiningScopeForBinding(targetScope, signalOrProperty->name),
                        signalOrProperty->type
                    };
                case ResolveActualTypeForFieldMemberExpression:
                    // Bindings can't be inside of FieldMemberExpressions.
                    Q_UNREACHABLE_RETURN({});
                }
            }
            if (auto result = resolveSignalOrPropertyExpressionType(name, owner.value(), options)) {
                return result;
            }
            qDebug(QQmlLSUtilsLog) << "QQmlLSUtils::resolveExpressionType() could not resolve the"
                                      "type of a Binding.";
        }

        return {};
    }
    case DomType::QmlObject: {
        auto object = item.as<QmlObject>();
        if (!object)
            return {};
        if (auto scope = object->semanticScope()) {
            const auto name = item.name();
            const bool isComponent = name.front().isUpper();
            if (isComponent)
                scope = scope->baseType();
            const QQmlLSUtilsIdentifierType type =
                    isComponent ? QmlComponentIdentifier : GroupedPropertyIdentifier;
            switch (options) {
            case ResolveOwnerType:
                return QQmlLSUtilsExpressionType{ name, scope, type };
            case ResolveActualTypeForFieldMemberExpression:
                return QQmlLSUtilsExpressionType{ name, scope, type};
            }
        }
        return {};
    }
    case DomType::QmlComponent: {
        auto component = item.as<QmlComponent>();
        if (!component)
            return {};
        const auto scope = component->semanticScope();
        if (!scope)
            return {};

        QString name = item.name();
        if (auto dotIndex = name.indexOf(u'.'); dotIndex != -1)
            name = name.sliced(dotIndex + 1);
        switch (options) {
        case ResolveOwnerType:
            return QQmlLSUtilsExpressionType{ name, scope, QmlComponentIdentifier };
        case ResolveActualTypeForFieldMemberExpression:
            return QQmlLSUtilsExpressionType{ name, scope, QmlComponentIdentifier };
        }
        Q_UNREACHABLE_RETURN({});
    }
    case DomType::MethodInfo: {
        auto object = item.as<MethodInfo>();
        if (object && object->semanticScope()) {
            std::optional<QQmlJSScope::ConstPtr> scope = object->semanticScope();
            if (!scope)
                return {};

            if (QQmlJSScope::ConstPtr targetScope =
                        findScopeOfSpecialItems(scope.value()->parentScope(), item)) {
                const auto signalOrProperty = resolveNameInQmlScope(object->name, targetScope);
                if (!signalOrProperty)
                    return {};

                switch (options) {
                case ResolveOwnerType:
                    return QQmlLSUtilsExpressionType{ object->name,
                                                      findDefiningScopeForMethod(
                                                              targetScope, signalOrProperty->name),
                                                      signalOrProperty->type };
                case ResolveActualTypeForFieldMemberExpression:
                    // not supported for methods
                    return {};
                }
            }

            // in case scope is the semantic scope for the function bodies: grab the owner's scope
            // this happens for all methods but not for signals (they do not have a body)
            if (scope.value()->scopeType() == QQmlJSScope::ScopeType::JSFunctionScope)
                scope = scope.value()->parentScope();

            if (auto result = resolveSignalOrPropertyExpressionType(object->name, scope.value(),
                                                                    options)) {
                return result;
            }
            qDebug(QQmlLSUtilsLog) << "QQmlLSUtils::resolveExpressionType() could not resolve the"
                                      "type of a MethodInfo.";
        }

        return {};
    }
    case DomType::ScriptBinaryExpression: {
        if (isFieldMemberExpression(item)) {
            return resolveExpressionType(item.field(Fields::right), options);
        }
        return {};
    }
    case DomType::ScriptLiteral: {
        /* special case
        Binding { target: someId; property: "someProperty"}
        */
        const auto scope = item.qmlObject().semanticScope();
        const auto name = item.field(Fields::value).value().toString();
        if (QQmlJSScope::ConstPtr targetScope = findScopeOfSpecialItems(scope, item)) {
            const auto signalOrProperty = resolveNameInQmlScope(name, targetScope);
            if (!signalOrProperty)
                return {};
            switch (options) {
            case ResolveOwnerType:
                return QQmlLSUtilsExpressionType{
                    name, findDefiningScopeForProperty(targetScope, signalOrProperty->name),
                    signalOrProperty->type
                };
            case ResolveActualTypeForFieldMemberExpression:
                // ScriptLiteral's can't be inside of FieldMemberExpression's, especially when they
                // are inside a special item.
                Q_UNREACHABLE_RETURN({});
            }
        }
        return {};
    }
    case DomType::EnumItem: {
        const QString enumValue = item.field(Fields::name).value().toString();
         QQmlJSScope::ConstPtr referrerScope = item.rootQmlObject(GoTo::MostLikely).semanticScope();
         if (!referrerScope->hasEnumerationKey(enumValue))
             return {};
         switch (options) {
             // special case: use the owner's scope here, as enums do not have their own
             // QQmlJSScope.
         case ResolveActualTypeForFieldMemberExpression:
         case ResolveOwnerType:
             return QQmlLSUtilsExpressionType{
                 enumValue, findDefiningScopeForEnumerationKey(referrerScope, enumValue),
                 EnumeratorValueIdentifier
             };
         }
         Q_UNREACHABLE_RETURN({});
    }
    case DomType::EnumDecl: {
        const QString enumName = item.field(Fields::name).value().toString();
        QQmlJSScope::ConstPtr referrerScope = item.rootQmlObject(GoTo::MostLikely).semanticScope();
        if (!referrerScope->hasEnumeration(enumName))
            return {};
        switch (options) {
        // special case: use the owner's scope here, as enums do not have their own QQmlJSScope.
        case ResolveActualTypeForFieldMemberExpression:
        case ResolveOwnerType:
            return QQmlLSUtilsExpressionType{
                enumName, findDefiningScopeForEnumeration(referrerScope, enumName),
                EnumeratorIdentifier
            };
        }

        Q_UNREACHABLE_RETURN({});
    }
    default: {
        qCDebug(QQmlLSUtilsLog) << "Type" << item.internalKindStr()
                                << "is unimplemented in QQmlLSUtils::resolveExpressionType";
        return {};
    }
    }
    Q_UNREACHABLE();
}

DomItem QQmlLSUtils::sourceLocationToDomItem(const DomItem &file,
                                             const QQmlJS::SourceLocation &location)
{
    // QQmlJS::SourceLocation starts counting at 1 but the utils and the LSP start at 0.
    auto items = QQmlLSUtils::itemsFromTextLocation(file, location.startLine - 1,
                                                    location.startColumn - 1);
    switch (items.size()) {
    case 0:
        return {};
    case 1:
        return items.front().domItem;
    case 2: {
        // special case: because location points to the beginning of the type definition,
        // itemsFromTextLocation might also return the type on its left, in case it is directly
        // adjacent to it. In this case always take the right (=with the higher column-number)
        // item.
        auto &first = items.front();
        auto &second = items.back();
        Q_ASSERT_X(first.fileLocation->info().fullRegion.startLine
                           == second.fileLocation->info().fullRegion.startLine,
                   "QQmlLSUtils::findTypeDefinitionOf(DomItem)",
                   "QQmlLSUtils::itemsFromTextLocation returned non-adjacent items.");
        if (first.fileLocation->info().fullRegion.startColumn
            > second.fileLocation->info().fullRegion.startColumn)
            return first.domItem;
        else
            return second.domItem;
        break;
    }
    default:
        qDebug() << "Found multiple candidates for type of scriptidentifierexpression";
        break;
    }
    return {};
}

static std::optional<QQmlLSUtilsLocation>
findMethodDefinitionOf(const DomItem &file, QQmlJS::SourceLocation location, const QString &name)
{
    DomItem owner = QQmlLSUtils::sourceLocationToDomItem(file, location).qmlObject();
    DomItem method = owner.field(Fields::methods).key(name).index(0);
    auto fileLocation = FileLocations::treeOf(method);
    if (!fileLocation)
        return {};

    auto regions = fileLocation->info().regions;

    if (auto it = regions.constFind(IdentifierRegion); it != regions.constEnd()) {
        QQmlLSUtilsLocation result;
        result.sourceLocation = *it;
        result.filename = method.canonicalFilePath();
        return result;
    }

    return {};
}

static std::optional<QQmlLSUtilsLocation>
findPropertyDefinitionOf(const DomItem &file, QQmlJS::SourceLocation propertyDefinitionLocation,
                         const QString &name)
{
    DomItem propertyOwner =
            QQmlLSUtils::sourceLocationToDomItem(file, propertyDefinitionLocation).qmlObject();
    DomItem propertyDefinition = propertyOwner.field(Fields::propertyDefs).key(name).index(0);
    auto fileLocation = FileLocations::treeOf(propertyDefinition);
    if (!fileLocation)
        return {};

    auto regions = fileLocation->info().regions;

    if (auto it = regions.constFind(IdentifierRegion); it != regions.constEnd()) {
        QQmlLSUtilsLocation result;
        result.sourceLocation = *it;
        result.filename = propertyDefinition.canonicalFilePath();
        return result;
    }

    return {};
}

std::optional<QQmlLSUtilsLocation> QQmlLSUtils::findDefinitionOf(const DomItem &item)
{
    auto resolvedExpression =
            resolveExpressionType(item, QQmlLSUtilsResolveOptions::ResolveOwnerType);

    if (!resolvedExpression || !resolvedExpression->name || !resolvedExpression->semanticScope) {
        qCDebug(QQmlLSUtilsLog) << "QQmlLSUtils::findDefinitionOf: Type could not be resolved.";
        return {};
    }

    switch (resolvedExpression->type) {
    case JavaScriptIdentifier: {
        const QQmlJS::SourceLocation location =
                resolvedExpression->semanticScope->ownJSIdentifier(*resolvedExpression->name)
                        .value()
                        .location;

        return QQmlLSUtilsLocation{ resolvedExpression->semanticScope->filePath(), location };
    }

    case PropertyIdentifier: {
        const DomItem ownerFile = item.goToFile(resolvedExpression->semanticScope->filePath());
        const QQmlJS::SourceLocation ownerLocation =
                resolvedExpression->semanticScope->sourceLocation();
        return findPropertyDefinitionOf(ownerFile, ownerLocation, *resolvedExpression->name);
    }
    case PropertyChangedSignalIdentifier:
    case PropertyChangedHandlerIdentifier:
    case SignalIdentifier:
    case SignalHandlerIdentifier:
    case MethodIdentifier: {
        const DomItem ownerFile = item.goToFile(resolvedExpression->semanticScope->filePath());
        const QQmlJS::SourceLocation ownerLocation =
                resolvedExpression->semanticScope->sourceLocation();
        return findMethodDefinitionOf(ownerFile, ownerLocation, *resolvedExpression->name);
    }
    case QmlObjectIdIdentifier: {
        DomItem qmlObject = QQmlLSUtils::sourceLocationToDomItem(
                item.containingFile(), resolvedExpression->semanticScope->sourceLocation());
        // in the Dom, the id is saved in a QMultiHash inside the Component of an QmlObject.
        const DomItem domId = qmlObject.component()
                                      .field(Fields::ids)
                                      .key(*resolvedExpression->name)
                                      .index(0)
                                      .field(Fields::value);
        if (!domId) {
            qCDebug(QQmlLSUtilsLog)
                    << "QmlComponent in Dom structure has no id, was it misconstructed?";
            return {};
        }

        QQmlLSUtilsLocation result;
        result.sourceLocation = FileLocations::treeOf(domId)->info().fullRegion;
        result.filename = domId.canonicalFilePath();
        return result;
    }
    case QmlComponentIdentifier: {
        QQmlLSUtilsLocation result;
        result.sourceLocation = resolvedExpression->semanticScope->sourceLocation();
        result.filename = resolvedExpression->semanticScope->filePath();
        return result;
    }
    case SingletonIdentifier:
    case EnumeratorIdentifier:
    case EnumeratorValueIdentifier:
    case AttachedTypeIdentifier:
    case GroupedPropertyIdentifier:
        qCDebug(QQmlLSUtilsLog) << "QQmlLSUtils::findDefinitionOf was not implemented for type"
                                << resolvedExpression->type;
        return {};
    }
    Q_UNREACHABLE_RETURN({});
}

static QQmlJSScope::ConstPtr propertyOwnerFrom(const QQmlJSScope::ConstPtr &type,
                                               const QString &name)
{
    Q_ASSERT(!name.isEmpty());
    Q_ASSERT(type);

    QQmlJSScope::ConstPtr typeWithDefinition = type;
    while (typeWithDefinition && !typeWithDefinition->hasOwnProperty(name))
        typeWithDefinition = typeWithDefinition->baseType();

    if (!typeWithDefinition) {
        qCDebug(QQmlLSUtilsLog)
                << "QQmlLSUtils::checkNameForRename cannot find property definition,"
                    " ignoring.";
    }

    return typeWithDefinition;
}

static QQmlJSScope::ConstPtr methodOwnerFrom(const QQmlJSScope::ConstPtr &type,
                                             const QString &name)
{
    Q_ASSERT(!name.isEmpty());
    Q_ASSERT(type);

    QQmlJSScope::ConstPtr typeWithDefinition = type;
    while (typeWithDefinition && !typeWithDefinition->hasOwnMethod(name))
        typeWithDefinition = typeWithDefinition->baseType();

    if (!typeWithDefinition) {
        qCDebug(QQmlLSUtilsLog)
                << "QQmlLSUtils::checkNameForRename cannot find method definition,"
                    " ignoring.";
    }

    return typeWithDefinition;
}

static QQmlJSScope::ConstPtr
expressionTypeWithDefinition(const QQmlLSUtilsExpressionType &ownerType)
{
    switch (ownerType.type) {
    case PropertyIdentifier:
        return propertyOwnerFrom(ownerType.semanticScope, *ownerType.name);
    case PropertyChangedHandlerIdentifier: {
        const auto propertyName =
                QQmlSignalNames::changedHandlerNameToPropertyName(*ownerType.name);
        return propertyOwnerFrom(ownerType.semanticScope, *propertyName);
        break;
    }
    case PropertyChangedSignalIdentifier: {
        const auto propertyName = QQmlSignalNames::changedSignalNameToPropertyName(*ownerType.name);
        return propertyOwnerFrom(ownerType.semanticScope, *propertyName);
    }
    case MethodIdentifier:
    case SignalIdentifier:
        return methodOwnerFrom(ownerType.semanticScope, *ownerType.name);
    case SignalHandlerIdentifier: {
        const auto signalName = QQmlSignalNames::handlerNameToSignalName(*ownerType.name);
        return methodOwnerFrom(ownerType.semanticScope, *signalName);
    }
    case JavaScriptIdentifier:
    case QmlObjectIdIdentifier:
    case SingletonIdentifier:
    case EnumeratorIdentifier:
    case EnumeratorValueIdentifier:
    case AttachedTypeIdentifier:
    case GroupedPropertyIdentifier:
    case QmlComponentIdentifier:
        return ownerType.semanticScope;
    }
    return {};
}

std::optional<QQmlLSUtilsErrorMessage> QQmlLSUtils::checkNameForRename(
        const DomItem &item, const QString &dirtyNewName,
        const std::optional<QQmlLSUtilsExpressionType> &ownerType)
{
    if (!ownerType) {
        if (const auto resolved = QQmlLSUtils::resolveExpressionType(item, ResolveOwnerType))
            return checkNameForRename(item, dirtyNewName, resolved);
    }

    // general checks for ECMAscript identifiers
    if (!isValidEcmaScriptIdentifier(dirtyNewName))
        return QQmlLSUtilsErrorMessage{ 0, u"Invalid EcmaScript identifier!"_s };

    const auto userSemanticScope = item.nearestSemanticScope();

    if (!ownerType || !userSemanticScope) {
        return QQmlLSUtilsErrorMessage{ 0, u"Requested item cannot be renamed"_s };
    }

    // type specific checks
    switch (ownerType->type) {
    case PropertyChangedSignalIdentifier: {
        if (!QQmlSignalNames::isChangedSignalName(dirtyNewName)) {
            return QQmlLSUtilsErrorMessage{ 0, u"Invalid name for a property changed signal."_s };
        }
        break;
    }
    case PropertyChangedHandlerIdentifier: {
        if (!QQmlSignalNames::isChangedHandlerName(dirtyNewName)) {
            return QQmlLSUtilsErrorMessage{
                0, u"Invalid name for a property changed handler identifier."_s
            };
        }
        break;
    }
    case SignalHandlerIdentifier: {
        if (!QQmlSignalNames::isHandlerName(dirtyNewName)) {
            return QQmlLSUtilsErrorMessage{ 0, u"Invalid name for a signal handler identifier."_s };
        }
        break;
    }
    // TODO: any other specificities?
    case QmlObjectIdIdentifier:
        if (dirtyNewName.front().isLetter() && !dirtyNewName.front().isLower()) {
            return QQmlLSUtilsErrorMessage{
                0, u"Object id names cannot start with an upper case letter."_s
            };
        }
        break;
    case JavaScriptIdentifier:
    case PropertyIdentifier:
    case SignalIdentifier:
    case MethodIdentifier:
    default:
        break;
    };

    auto typeWithDefinition = expressionTypeWithDefinition(*ownerType);

    if (!typeWithDefinition) {
        return QQmlLSUtilsErrorMessage{
            0,
            u"Renaming has not been implemented for the requested item."_s,
        };
    }

    // is it not defined in QML?
    if (!typeWithDefinition->isComposite()) {
        return QQmlLSUtilsErrorMessage{ 0, u"Cannot rename items defined in non-QML files."_s };
    }

    // is it defined in the current module?
    const QString moduleOfDefinition = ownerType->semanticScope->moduleName();
    const QString moduleOfCurrentItem = userSemanticScope->moduleName();
    if (moduleOfDefinition != moduleOfCurrentItem) {
        return QQmlLSUtilsErrorMessage{
            0,
            u"Cannot rename items defined in the %1 module fromits usage in the %2 module."_s
                    .arg(moduleOfDefinition, moduleOfCurrentItem),
        };
    }

    return {};
}

static std::optional<QString> oldNameFrom(const DomItem &item)
{
    switch (item.internalKind()) {
    case DomType::ScriptIdentifierExpression: {
        return item.field(Fields::identifier).value().toString();
    }
    case DomType::ScriptVariableDeclarationEntry: {
        return item.field(Fields::identifier).value().toString();
    }
    case DomType::PropertyDefinition:
    case DomType::Binding:
    case DomType::MethodInfo: {
        return item.field(Fields::name).value().toString();
    }
    default:
        qCDebug(QQmlLSUtilsLog) << item.internalKindStr()
                                << "was not implemented for QQmlLSUtils::renameUsagesOf";
        return std::nullopt;
    }
    Q_UNREACHABLE_RETURN(std::nullopt);
}

static std::optional<QString> newNameFrom(const QString &dirtyNewName,
                                          QQmlLSUtilsIdentifierType alternative)
{
    // When renaming signal/property changed handlers and property changed signals:
    // Get the actual corresponding signal name (for signal handlers) or property name (for
    // property changed signal + handlers) that will be used for the renaming.
    switch (alternative) {
    case SignalHandlerIdentifier: {
        return QQmlSignalNames::handlerNameToSignalName(dirtyNewName);
    }
    case PropertyChangedHandlerIdentifier: {
        return QQmlSignalNames::changedHandlerNameToPropertyName(dirtyNewName);
    }
    case PropertyChangedSignalIdentifier: {
        return QQmlSignalNames::changedSignalNameToPropertyName(dirtyNewName);
    }
    case SignalIdentifier:
    case PropertyIdentifier:
    default:
        return std::nullopt;
    }
    Q_UNREACHABLE_RETURN(std::nullopt);
}

/*!
\internal
\brief Rename the appearance of item to newName.

Special cases:
\list
    \li Renaming a property changed signal or property changed handler does the same as renaming
    the underlying property, except that newName gets
    \list
        \li its "on"-prefix and "Changed"-suffix chopped of if item is a property changed handlers
        \li its "Changed"-suffix chopped of if item is a property changed signals
    \endlist
    \li Renaming a signal handler does the same as renaming a signal, but the "on"-prefix in newName
    is chopped of.

    All of the chopping operations are done using the static helpers from QQmlSignalNames.
\endlist
*/
QList<QQmlLSUtilsEdit> QQmlLSUtils::renameUsagesOf(
        const DomItem &item, const QString &dirtyNewName,
        const std::optional<QQmlLSUtilsExpressionType> &targetType)
{
    QList<QQmlLSUtilsEdit> results;
    const QList<QQmlLSUtilsLocation> locations = findUsagesOf(item);
    if (locations.isEmpty())
        return results;

    auto oldName = oldNameFrom(item);
    if (!oldName)
        return results;

    QQmlJSScope::ConstPtr semanticScope;
    if (targetType) {
        semanticScope = targetType->semanticScope;
    } else if (const auto resolved = QQmlLSUtils::resolveExpressionType(
                       item, QQmlLSUtilsResolveOptions::ResolveOwnerType)) {
        semanticScope = resolved->semanticScope;
    } else {
        return results;
    }

    QString newName;
    if (const auto resolved = resolveNameInQmlScope(*oldName, semanticScope)) {
        newName = newNameFrom(dirtyNewName, resolved->type).value_or(dirtyNewName);
        oldName = resolved->name;
    } else {
        newName = dirtyNewName;
    }

    const qsizetype oldNameLength = oldName->length();
    const qsizetype oldHandlerNameLength =
            QQmlSignalNames::signalNameToHandlerName(*oldName).length();
    const qsizetype oldChangedSignalNameLength =
            QQmlSignalNames::propertyNameToChangedSignalName(*oldName).length();
    const qsizetype oldChangedHandlerNameLength =
            QQmlSignalNames::propertyNameToChangedHandlerName(*oldName).length();

    const QString newHandlerName = QQmlSignalNames::signalNameToHandlerName(newName);
    const QString newChangedSignalName = QQmlSignalNames::propertyNameToChangedSignalName(newName);
    const QString newChangedHandlerName =
            QQmlSignalNames::propertyNameToChangedHandlerName(newName);

    // set the new name at the found usages, but add "on"-prefix and "Changed"-suffix if needed
    for (const auto &location : locations) {
        const qsizetype currentLength = location.sourceLocation.length;
        QQmlLSUtilsEdit edit;
        edit.location = location;
        if (oldNameLength == currentLength) {
            // normal case, nothing to do
            edit.replacement = newName;

        } else if (oldHandlerNameLength == currentLength) {
            // signal handler location
            edit.replacement = newHandlerName;

        } else if (oldChangedSignalNameLength == currentLength) {
            // property changed signal location
            edit.replacement = newChangedSignalName;

        } else if (oldChangedHandlerNameLength == currentLength) {
            // property changed handler location
            edit.replacement = newChangedHandlerName;

        } else {
            qCDebug(QQmlLSUtilsLog) << "Found usage with wrong identifier length, ignoring...";
            continue;
        }
        results.append(edit);
    }

    return results;
}

QQmlLSUtilsLocation QQmlLSUtilsLocation::from(const QString &fileName, const QString &code,
                                              quint32 startLine, quint32 startCharacter,
                                              quint32 length)
{
    quint32 offset = QQmlLSUtils::textOffsetFrom(code, startLine - 1, startCharacter - 1);

    QQmlLSUtilsLocation location{
        fileName, QQmlJS::SourceLocation{ offset, length, startLine, startCharacter }
    };
    return location;
}

QQmlLSUtilsEdit QQmlLSUtilsEdit::from(const QString &fileName, const QString &code,
                                      quint32 startLine, quint32 startCharacter, quint32 length,
                                      const QString &newName)
{
    QQmlLSUtilsEdit rename;
    rename.location = QQmlLSUtilsLocation::from(fileName, code, startLine, startCharacter, length);
    rename.replacement = newName;
    return rename;
}

bool QQmlLSUtils::isValidEcmaScriptIdentifier(QStringView identifier)
{
    QQmlJS::Lexer lexer(nullptr);
    lexer.setCode(identifier.toString(), 0);
    const int token = lexer.lex();
    if (token != static_cast<int>(QQmlJS::Lexer::T_IDENTIFIER))
        return false;
    // make sure there is nothing following the lexed identifier
    const int eofToken = lexer.lex();
    return eofToken == static_cast<int>(QQmlJS::Lexer::EOF_SYMBOL);
}


/*!
\internal
Returns the name of the cmake program along with the arguments needed to build the
qmltyperegistration. This command generates the .qmltypes, qmldir and .qrc files required for qmlls
to provide correct information on C++ defined QML elements.

We assume here that CMake is available in the path. This should be the case for linux and macOS by
default.
For windows, having CMake in the path is not too unrealistic, for example,
https://doc.qt.io/qt-6/windows-building.html#step-2-install-build-requirements claims that you need
to have CMake in your path to build Qt. So a developer machine running qmlls has a high chance of
having CMake in their path, if CMake is installed and used.
*/
QPair<QString, QStringList> QQmlLSUtils::cmakeBuildCommand(const QString &path)
{
    const QPair<QString, QStringList> result{
        u"cmake"_s, { u"--build"_s, path, u"-t"_s, u"all_qmltyperegistrations"_s }
    };
    return result;
}


QByteArray QQmlLSUtils::getDocumentationFromLocation(const DomItem &file, const QQmlLSUtilsTextPosition &position)
{
    QByteArray result;
    const auto [line, character] = position;
    const auto itemLocation = itemsFromTextLocation(file,  line, character);

    // TODO:
    // Process found item's internalKind and fetch its documentation.
    Q_UNUSED(itemLocation);

    return result;
}

QT_END_NAMESPACE