asm-lsp 0.10.1

Language Server for x86/x86_64, ARM, RISCV, and z80 Assembly Code
Documentation
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
use std::{
    borrow::ToOwned,
    cmp::Ordering,
    collections::{HashMap, HashSet},
    convert::TryFrom as _,
    fmt::Write as _,
    fs::{File, create_dir_all},
    io::BufRead,
    path::{Path, PathBuf},
    process::Command,
    str::FromStr as _,
    string::ToString as _,
    sync::LazyLock,
};

use anyhow::{Result, anyhow};
use compile_commands::{CompilationDatabase, CompileArgs, CompileCommand, SourceFile};
use dirs::config_dir;
use log::{error, info, log, log_enabled, warn};
use lsp_server::{Connection, Message, RequestId, Response};
use lsp_textdocument::FullTextDocument;
use lsp_types::notification::Notification as _;
use lsp_types::{
    CompletionItem, CompletionItemKind, CompletionList, CompletionParams, CompletionTriggerKind,
    Diagnostic, DocumentSymbol, DocumentSymbolParams, Documentation, GotoDefinitionParams,
    GotoDefinitionResponse, Hover, HoverContents, HoverParams, InitializeParams, Location,
    MarkupContent, MarkupKind, MessageType, Position, Range, ReferenceParams, SignatureHelp,
    SignatureHelpParams, SignatureInformation, SymbolKind, TextDocumentContentChangeEvent,
    TextDocumentPositionParams, Uri,
};
use regex::Regex;
use symbolic::common::{Language, Name, NameMangling};
use symbolic_demangle::{Demangle, DemangleOptions};
use tree_sitter::InputEdit;

use crate::{
    Arch, ArchOrAssembler, Assembler, Completable, CompletionItems, Config, ConfigOptions,
    Directive, DocumentStore, Hoverable, Instruction, NameToInstructionMap, RootConfig,
    ServerStore, TreeEntry, types::Column, ustr,
};

/// Prints information about the server
///
/// - Server version
/// - Attempts to find the global configuration directories on the host machine,
///   and indicates whether a `.asm-lsp.toml` config file is present
pub fn run_info() {
    println!("asm-lsp-{}\n", env!("CARGO_PKG_VERSION"));
    let mut global_cfgs: Vec<PathBuf> = get_global_cfg_dirs()
        .iter()
        .filter_map(|p| (*p).clone())
        .collect();
    println!("Default config architecture: {}", Arch::default());
    println!(
        "Global config director{}:",
        if global_cfgs.len() > 1 { "ies" } else { "y" }
    );
    for cfg_path in &mut global_cfgs {
        cfg_path.push("asm-lsp");
        print!("\t{}", cfg_path.display());
        cfg_path.push(".asm-lsp.toml");
        if cfg_path.exists() {
            println!(" -- Config detected");
        } else {
            println!(" -- No config detected");
        }
    }
}

/// Sends an  response indicating no information was available to
/// the lsp client via `connection`
///
/// # Errors
///
/// Returns `Err` if the response fails to send via `connection`
pub fn send_empty_resp(connection: &Connection, id: RequestId) -> Result<()> {
    let empty_resp = Response {
        id,
        result: None,
        error: Some(lsp_server::ResponseError {
            code: lsp_server::ErrorCode::RequestFailed as i32,
            message: "No information available".to_string(),
            data: None,
        }),
    };

    Ok(connection.sender.send(Message::Response(empty_resp))?)
}

/// Sends a notification with to the client
/// Param `message` is the owned type `String` to help reduce redundant allocations
///
/// # Errors
///
/// Returns `Err` if the response fails to send via `connection`
///
/// # Panics
///
/// Panics if JSON encoding of the notification fails
pub fn send_notification(message: String, typ: MessageType, connection: &Connection) -> Result<()> {
    let msg_params = lsp_types::ShowMessageParams { typ, message };
    let result = serde_json::to_value(msg_params).unwrap();
    let err_notif = lsp_server::Notification {
        method: lsp_types::notification::ShowMessage::METHOD.to_string(),
        params: result,
    };
    Ok(connection.sender.send(Message::Notification(err_notif))?)
}

/// Find the ([start], [end]) indices and the cursor's offset in a word
/// on the given line
///
/// Borrowed from RLS
/// characters besides the default alphanumeric and '_'
#[must_use]
pub fn find_word_at_pos(line: &str, col: Column) -> ((Column, Column), usize) {
    let line_ = format!("{line} ");
    // TODO: Let's just pass in a config, this could get messy
    // NOTE: '*' is added as an allowed character to account for the the program
    // counter pseudo variable of the Ca65 assembler. It's included unconditionally
    // here for simplicity, but if this proves to be an issue we can pass in a `config`
    // and only use it if the Ca65 assembler is enabled
    //
    // NOTE: In a similar manner to above, '$' is added as an allowed character to account
    // for mips registers
    let is_ident_char =
        |c: char| c.is_alphanumeric() || c == '_' || c == '.' || c == '*' || c == '$';

    let start = line_
        .chars()
        .enumerate()
        .take(col)
        .filter(|&(_, c)| !is_ident_char(c))
        .last()
        .map_or(0, |(i, _)| i + 1);

    let mut end = line_
        .chars()
        .enumerate()
        .skip(col)
        .filter(|&(_, c)| !is_ident_char(c));

    let end = end.next();
    ((start, end.map_or(col, |(i, _)| i)), col - start)
}

pub enum UriConversion {
    Canonicalized(PathBuf),
    Unchecked(PathBuf),
}

/// Sanitizes the URI path sent by an LSP client
///
/// - "%3A" is replaced by ':' on windows, as this is likely escaped
///   by the emacs client on windows/mingw/msys2
/// - Returning `UriConversion::Canonicalized` indicates a path was able to be
///   canonicalized. This indicates the path is valid and said file exists on disk
/// - Returning `UriConversion::Unchecked` indicates that the path couldn't be
///   canonicalized
///
/// # Panics
///
/// Will panic if `uri` cannot be interpreted as valid utf-8 after being percent-decoded
#[must_use]
pub fn process_uri(uri: &Uri) -> UriConversion {
    let mut clean_path: String =
        url_escape::percent_encoding::percent_decode_str(uri.path().as_str())
            .decode_utf8()
            .unwrap_or_else(|e| {
                panic!(
                    "Invalid encoding for uri \"{}\" -- {e}",
                    uri.path().as_str()
                )
            })
            .to_string();

    // HACK: On Windows, sometimes a leading '/',  e.g. /C:/Users/foo/bar/...
    // is passed as part of the path -- Stuff like Git bash and MSYS2 will accept
    // /C/Users/foo/bar/..., but *not* if the colon is present. Vanila windows
    // will not accept a leading slash at all, but requires the colon after the
    // drive letter, like C:/Users/foo/... So we do our best to clean up here
    if cfg!(windows) && clean_path.contains(':') {
        clean_path = clean_path.strip_prefix('/').unwrap_or(&clean_path).into();
    }

    let Ok(path) = PathBuf::from_str(&clean_path);
    path.canonicalize()
        .map_or(UriConversion::Unchecked(path), |canonicalized| {
            // HACK: On Windows, when a path is canonicalized, sometimes it gets prefixed
            // with "\\?\" -- https://stackoverflow.com/questions/41233684/why-does-my-canonicalized-path-get-prefixed-with
            // That's great and all, but it looks like common tools (like gcc) don't handle
            // this correctly, and you get something like the following:
            // Error: can't open //test.s for reading: No such file or directory
            // The solution? Just cut out the prefix and hope that doesn't break anything else
            if cfg!(windows) {
                #[allow(clippy::option_if_let_else)]
                if let Some(tmp) = canonicalized.to_str().unwrap().strip_prefix("\\\\?\\") {
                    warn!("Stripping Windows canonicalization prefix \"\\\\?\\\" from path");
                    UriConversion::Canonicalized(tmp.into())
                } else {
                    UriConversion::Canonicalized(canonicalized)
                }
            } else {
                UriConversion::Canonicalized(canonicalized)
            }
        })
}

/// Returns the word undernearth the cursor given the specified `TextDocumentPositionParams`
///
/// # Errors
///
/// Will return `Err` if the file cannot be opened
///
/// # Panics
///
/// Will panic if the position parameters specify a line past the end of the file's
/// contents
pub fn get_word_from_file_params(pos_params: &TextDocumentPositionParams) -> Result<String> {
    let uri = &pos_params.text_document.uri;
    let line = pos_params.position.line as usize;
    let col = pos_params.position.character as usize;

    let filepath = PathBuf::from(uri.as_str());
    match filepath.canonicalize() {
        Ok(file) => {
            let file = match File::open(file) {
                Ok(opened) => opened,
                Err(e) => return Err(anyhow!("Couldn't open file -> {:?} -- Error: {e}", uri)),
            };
            let buf_reader = std::io::BufReader::new(file);

            let line_conts = buf_reader.lines().nth(line).unwrap().unwrap();
            let ((start, end), _) = find_word_at_pos(&line_conts, col);
            Ok(String::from(&line_conts[start..end]))
        }
        Err(e) => Err(anyhow!("Filepath get error -- Error: {e}")),
    }
}

/// Returns a string slice to the word in doc specified by the position params,
/// and the cursor's offset into the word
#[must_use]
pub fn get_word_from_pos_params<'a>(
    doc: &'a FullTextDocument,
    pos_params: &TextDocumentPositionParams,
) -> (&'a str, usize) {
    let line_contents = doc.get_content(Some(Range {
        start: Position {
            line: pos_params.position.line,
            character: 0,
        },
        end: Position {
            line: pos_params.position.line,
            character: u32::MAX,
        },
    }));

    let ((word_start, word_end), cursor_offset) =
        find_word_at_pos(line_contents, pos_params.position.character as usize);
    (&line_contents[word_start..word_end], cursor_offset)
}

/// Fetches default include directories, as well as any additional directories
/// as specified by a `compile_commands.json` or `compile_flags.txt` file in the
/// appropriate location
///
/// # Panics
#[must_use]
pub fn get_include_dirs(compile_cmds: &CompilationDatabase) -> HashMap<SourceFile, Vec<PathBuf>> {
    let mut include_map = HashMap::from([(SourceFile::All, Vec::new())]);

    let global_dirs = include_map.get_mut(&SourceFile::All).unwrap();
    for dir in get_default_include_dirs() {
        global_dirs.push(dir);
    }

    for (source_file, ref dir) in get_additional_include_dirs(compile_cmds) {
        include_map
            .entry(source_file)
            .and_modify(|dirs| dirs.push(dir.to_owned()))
            .or_insert_with(|| vec![dir.to_owned()]);
    }

    info!("Include directory map: {:?}", include_map);

    include_map
}

/// Returns a vector of default #include directories
#[must_use]
fn get_default_include_dirs() -> Vec<PathBuf> {
    let mut include_dirs = HashSet::new();
    // repeat "cpp" and "clang" so that each command can be run with
    // both set of args specified in `cmd_args`
    let cmds = &["cpp", "cpp", "clang", "clang"];
    let cmd_args = &[
        ["-v", "-E", "-x", "c", "/dev/null", "-o", "/dev/null"],
        ["-v", "-E", "-x", "c++", "/dev/null", "-o", "/dev/null"],
    ];

    for (cmd, args) in cmds.iter().zip(cmd_args.iter().cycle()) {
        if let Ok(cmd_output) = std::process::Command::new(cmd)
            .args(args)
            .stderr(std::process::Stdio::piped())
            .output()
            && cmd_output.status.success()
        {
            let output_str: String = ustr::get_string(cmd_output.stderr);

            output_str
                .lines()
                .skip_while(|line| !line.contains("#include \"...\" search starts here:"))
                .skip(1)
                .take_while(|line| {
                    !(line.contains("End of search list.")
                        || line.contains("#include <...> search starts here:"))
                })
                .filter_map(|line| PathBuf::from(line.trim()).canonicalize().ok())
                .for_each(|path| {
                    include_dirs.insert(path);
                });

            output_str
                .lines()
                .skip_while(|line| !line.contains("#include <...> search starts here:"))
                .skip(1)
                .take_while(|line| !line.contains("End of search list."))
                .filter_map(|line| PathBuf::from(line.trim()).canonicalize().ok())
                .for_each(|path| {
                    include_dirs.insert(path);
                });
        }
    }

    include_dirs.iter().cloned().collect::<Vec<PathBuf>>()
}

/// Returns a vector of source files and their associated additional include directories,
/// as specified by `compile_cmds`
#[must_use]
fn get_additional_include_dirs(compile_cmds: &CompilationDatabase) -> Vec<(SourceFile, PathBuf)> {
    let mut additional_dirs = Vec::new();

    for entry in compile_cmds {
        let Ok(entry_dir) = entry.directory.canonicalize() else {
            continue;
        };

        let source_file = match &entry.file {
            SourceFile::All => SourceFile::All,
            SourceFile::File(file) => {
                if file.is_absolute() {
                    entry.file.clone()
                } else if let Ok(dir) = entry_dir.join(file).canonicalize() {
                    SourceFile::File(dir)
                } else {
                    continue;
                }
            }
        };

        let mut check_dir = false;
        if let Some(args) = &entry.arguments {
            // `arguments` run as the compilation step for the translation unit `file`
            // We will try to canonicalize non-absolute paths as relative to `file`,
            // but this isn't possible if we have a SourceFile::All. Just don't
            // add the include directory and issue a warning in this case
            match args {
                CompileArgs::Flags(args) | CompileArgs::Arguments(args) => {
                    for arg in args.iter().map(|arg| arg.trim()) {
                        if check_dir {
                            // current arg is preceeded by lone '-I'
                            let dir = PathBuf::from(arg);
                            if dir.is_absolute() {
                                additional_dirs.push((source_file.clone(), dir));
                            } else if let SourceFile::File(ref source_path) = source_file {
                                if let Ok(full_include_path) = source_path.join(dir).canonicalize()
                                {
                                    additional_dirs.push((source_file.clone(), full_include_path));
                                }
                            } else {
                                warn!(
                                    "Additional relative include directories cannot be extracted for a compilation database entry targeting 'All'"
                                );
                            }
                            check_dir = false;
                        } else if arg.eq("-I") {
                            // -Irelative is stored as two separate args if parsed from `compile_flags.txt`
                            check_dir = true;
                        } else if arg.len() > 2 && arg.starts_with("-I") {
                            // '-Irelative'
                            let dir = PathBuf::from(&arg[2..]);
                            if dir.is_absolute() {
                                additional_dirs.push((source_file.clone(), dir));
                            } else if let SourceFile::File(ref source_path) = source_file {
                                if let Ok(full_include_path) = source_path.join(dir).canonicalize()
                                {
                                    additional_dirs.push((source_file.clone(), full_include_path));
                                }
                            } else {
                                warn!(
                                    "Additional relative include directories cannot be extracted for a compilation database entry targeting 'All'"
                                );
                            }
                        }
                    }
                }
            }
        } else if entry.command.is_some()
            && let Some(args) = entry.args_from_cmd()
        {
            for arg in args {
                if arg.starts_with("-I") && arg.len() > 2 {
                    // "All paths specified in the `command` or `file` fields must be either absolute or relative to..." the `directory` field
                    let incl_path = PathBuf::from(&arg[2..]);
                    if incl_path.is_absolute() {
                        additional_dirs.push((source_file.clone(), incl_path));
                    } else {
                        let dir = entry_dir.join(incl_path);
                        if let Ok(full_include_path) = dir.canonicalize() {
                            additional_dirs.push((source_file.clone(), full_include_path));
                        }
                    }
                }
            }
        }
    }

    additional_dirs
}

/// Attempts to find either the `compile_commands.json` or `compile_flags.txt`
/// file in the project's root or build directories, returning either file as a
/// `CompilationDatabase` object
///
/// If both are present, `compile_commands.json` will override `compile_flags.txt`
pub fn get_compile_cmds_from_file(params: &InitializeParams) -> Option<CompilationDatabase> {
    if let Some(mut path) = get_project_root(params) {
        // Check the project root directory first
        let db = get_compilation_db_files(&path);
        if db.is_some() {
            return db;
        }

        // "The convention is to name the file compile_commands.json and put it at the top of the
        // build directory."
        path.push("build");
        let db = get_compilation_db_files(&path);
        if db.is_some() {
            return db;
        }
    }

    None
}

fn get_compilation_db_files(path: &Path) -> Option<CompilationDatabase> {
    // first check for compile_commands.json
    let cmp_cmd_path = path.join("compile_commands.json");
    if let Ok(conts) = std::fs::read_to_string(cmp_cmd_path)
        && let Ok(cmds) = serde_json::from_str(&conts)
    {
        return Some(cmds);
    }
    // then check for compile_flags.txt
    let cmp_flag_path = path.join("compile_flags.txt");
    if let Ok(conts) = std::fs::read_to_string(cmp_flag_path) {
        return Some(compile_commands::from_compile_flags_txt(path, &conts));
    }

    None
}

/// Returns the compile command associated with `uri` if it exists, or the default
/// one from `compile_cmds` otherwise
///
/// - If the user specified a `compiler` *and* flags in their config, use that
/// - If the user specified a `compiler` but no flags in their config (`None`,
///   *not* an empty `Vec`), try to find flags from `compile_flags.txt` in
///   `compile_cmds` and combine the two
/// - If the user didn't specify any compiler info in the relevant config, return
///   the default commands from `compile_cmds`
///
/// # Panics
///
/// Will panic if `req_uri` can't be canonicalized
///
/// NOTE: Several fields within the returned `CompilationDatabase` are intentionally left
/// uninitialized to avoid unnecessary allocations. If you're using this function
/// in a new place, please reconsider this assumption
pub fn get_compile_cmd_for_req(
    config: &RootConfig,
    req_uri: &Uri,
    compile_cmds: &CompilationDatabase,
) -> CompilationDatabase {
    let request_path = match process_uri(req_uri) {
        UriConversion::Canonicalized(p) => p,
        UriConversion::Unchecked(p) => {
            error!(
                "Failed to canonicalize request path {}, using {}",
                req_uri.path().as_str(),
                p.display()
            );
            p
        }
    };
    let config = config.get_config(req_uri);
    match (config.get_compiler(), config.get_compile_flags_txt()) {
        (Some(compiler), Some(flags)) => {
            // Fill out the full command invocation
            let mut args = vec![compiler.to_owned()];
            args.append(&mut flags.clone());
            args.push(request_path.to_str().unwrap_or_default().to_string());
            vec![CompileCommand {
                file: SourceFile::File(request_path),
                directory: PathBuf::new(),
                arguments: Some(CompileArgs::Arguments(args)),
                command: None,
                output: None,
            }]
        }
        (Some(compiler), None) => {
            // Fill out the full command invocation, check if `compile_cmds`
            // has flags to tack on
            let mut args = vec![compiler.to_owned()];
            // Check if we have flags as the first compile command from files,
            // `compile_flags.txt` files get loaded as a single `CompileCommand`
            // object as structured in the below `if` block
            if compile_cmds.len() == 1
                && let CompileCommand {
                    arguments: Some(CompileArgs::Flags(flags)),
                    ..
                } = &compile_cmds[0]
            {
                args.append(&mut flags.clone());
            }
            args.push(request_path.to_str().unwrap_or_default().to_string());
            vec![CompileCommand {
                file: SourceFile::File(request_path),
                directory: PathBuf::new(),
                arguments: Some(CompileArgs::Arguments(args)),
                command: None,
                output: None,
            }]
        }
        (None, Some(flags)) => {
            // Fill out flags, no compiler
            vec![CompileCommand {
                file: SourceFile::File(request_path),
                directory: PathBuf::new(),
                arguments: Some(CompileArgs::Flags(flags.clone())),
                command: None,
                output: None,
            }]
        }
        (None, None) => {
            // Grab the default command from `compile_cmds`
            compile_cmds.clone()
        }
    }
}

/// Returns a default `CompileCommand` for the provided `uri`.
///
/// - If the user specified a compiler in their config, it will be used.
/// - Otherwise, the command will be constructed with a single flag consisting of
///   the provided `uri`
///
/// NOTE: Several fields within the returned `CompileCommand` are intentionally left
/// uninitialized to avoid unnecessary allocations. If you're using this function
/// in a new place, please reconsider this assumption
pub fn get_default_compile_cmd(uri: &Uri, cfg: &Config) -> CompileCommand {
    cfg.get_compiler().as_ref().map_or_else(
        || CompileCommand {
            file: SourceFile::All, // Field isn't checked when called, intentionally left in odd state here
            directory: PathBuf::new(), // Field isn't checked when called, intentionally left uninitialized here
            arguments: Some(CompileArgs::Flags(vec![uri.path().to_string()])),
            command: None,
            output: None,
        },
        |compiler| CompileCommand {
            file: SourceFile::All, // Field isn't checked when called, intentionally left in odd state here
            directory: PathBuf::new(), // Field isn't checked when called, intentionally left uninitialized here
            arguments: Some(CompileArgs::Arguments(vec![
                (*compiler).to_string(),
                uri.path().to_string(),
            ])),
            command: None,
            output: None,
        },
    )
}

/// Attempts to run the given compile command and parses the resulting output. Any
/// relevant output will be translated into a `Diagnostic` object and pushed into
/// `diagnostics`
pub fn apply_compile_cmd(
    cfg: &Config,
    diagnostics: &mut Vec<Diagnostic>,
    uri: &Uri,
    compile_cmd: &CompileCommand,
) {
    info!("Attempting to apply compile command: {compile_cmd:?}");
    // TODO: Consolidate this logic, a little tricky because we need to capture
    // compile_cmd.arguments by reference, but we get an owned Vec out of args_from_cmd()...
    if let Some(ref args) = compile_cmd.arguments {
        match args {
            CompileArgs::Flags(flags) => {
                let compilers = cfg
                    .get_compiler()
                    .as_ref()
                    .map_or_else(|| vec!["gcc", "clang"], |compiler| vec![compiler]);

                for compiler in compilers {
                    match Command::new(compiler) // default or user-supplied compiler
                        .args(flags) // user supplied args
                        .arg(uri.path().as_str()) // the source file in question
                        .output()
                    {
                        Ok(result) => {
                            let output_str = ustr::get_string(result.stderr);
                            get_diagnostics(diagnostics, &output_str, cfg);
                        }
                        Err(e) => {
                            warn!(
                                "Failed to launch compile command process with {compiler} -- Error: {e}"
                            );
                        }
                    }
                }
            }
            CompileArgs::Arguments(arguments) => {
                if arguments.len() < 2 {
                    return;
                }
                let output = match Command::new(&arguments[0]).args(&arguments[1..]).output() {
                    Ok(result) => result,
                    Err(e) => {
                        error!("Failed to launch compile command process -- Error: {e}");
                        return;
                    }
                };
                let output_str = ustr::get_string(output.stderr);
                get_diagnostics(diagnostics, &output_str, cfg);
            }
        }
    } else if let Some(args) = compile_cmd.args_from_cmd() {
        if args.len() < 2 {
            return;
        }
        let output = match Command::new(&args[0]).args(&args[1..]).output() {
            Ok(result) => result,
            Err(e) => {
                error!("Failed to launch compile command process -- Error: {e}");
                return;
            }
        };
        let output_str = ustr::get_string(output.stderr);
        get_diagnostics(diagnostics, &output_str, cfg);
    }
}

/// Attempts to parse `tool_output`, translating it into `Diagnostic` objects
/// and placing them into `diagnostics`
///
/// Looks for diagnostics of the following form:
///
/// <file name>:<line number>: Error: <Error message>
///
/// As more assemblers are incorporated, this can be updated
///
/// # Panics
fn get_diagnostics(diagnostics: &mut Vec<Diagnostic>, tool_output: &str, cfg: &Config) {
    // Special handingling for FASM assembler diagnostics
    if cfg.is_assembler_enabled(Assembler::Fasm) {
        // https://flatassembler.net/docs.php?article=manual - 1.1.3 Compile messages
        static FASM_SOURCE_LOC: LazyLock<Regex> =
            LazyLock::new(|| Regex::new(r"^(.+) \[(\d+)\]:$").unwrap());
        // TODO: Look into including macro defintion locations as related information
        // static FASM_MACRO_INSTR_LOC: LazyLock<Regex> =
        //     LazyLock::new(|| Regex::new(r"^(.+) \[(\d+)\]: .+ \[(\d+\)]:$").unwrap());
        static FASM_ERR_MSG: LazyLock<Regex> =
            LazyLock::new(|| Regex::new(r"^error: (.+)").unwrap());

        let mut source_line: Option<u32> = None;
        let mut source_start_col: Option<u32> = None;
        let mut source_end_col: Option<u32> = None;
        let mut lines = tool_output.lines();
        while let Some(line) = lines.next() {
            // for line in tool_output.lines() {
            if let Some(caps) = FASM_SOURCE_LOC.captures(line) {
                // the entire capture is always at the 0th index,
                // then we have 2 more explicit capture groups
                if caps.len() == 3 {
                    let Ok(line_number) = caps[2].parse::<u32>() else {
                        continue;
                    };
                    source_line = Some(line_number);
                    if let Some(src) = lines.next() {
                        let len = src.len() as u32;
                        source_start_col = Some(len - src.trim_start().len() as u32);
                        source_end_col = Some(len);
                    }
                }
            } else if let Some(caps) = FASM_ERR_MSG.captures(line) {
                if caps.len() != 2 {
                    continue;
                }
                if let Some(line_number) = source_line {
                    let err_msg = caps[1].to_string();
                    let start_col = source_start_col.unwrap_or(0);
                    let end_col = source_end_col.unwrap_or(0);
                    diagnostics.push(Diagnostic::new_simple(
                        Range {
                            start: Position {
                                line: line_number - 1,
                                character: start_col,
                            },
                            end: Position {
                                line: line_number - 1,
                                character: end_col,
                            },
                        },
                        err_msg,
                    ));
                }
                source_line = None;
            }
        }
    } else {
        // TODO: Consolidate/ clean this up...regexes are hard
        static DIAG_REG_LINE_COLUMN: LazyLock<Regex> =
            LazyLock::new(|| Regex::new(r"^.*:(\d+):(\d+):\s+(.*)$").unwrap());
        static DIAG_REG_LINE_ONLY: LazyLock<Regex> =
            LazyLock::new(|| Regex::new(r"^.*:(\d+):\s+(.*)$").unwrap());
        static ALT_DIAG_REG_LINE_ONLY: LazyLock<Regex> =
            LazyLock::new(|| Regex::new(r"^.*\((\d+)\):\s+(.*)$").unwrap());
        for line in tool_output.lines() {
            // first check if we have an error message of the form:
            // :<line>:<column>: <error message here>
            if let Some(caps) = DIAG_REG_LINE_COLUMN.captures(line) {
                // the entire capture is always at the 0th index,
                // then we have 3 more explicit capture groups
                if caps.len() == 4 {
                    let Ok(line_number) = caps[1].parse::<u32>() else {
                        continue;
                    };
                    let Ok(column_number) = caps[2].parse::<u32>() else {
                        continue;
                    };
                    let err_msg = &caps[3];
                    diagnostics.push(Diagnostic::new_simple(
                        Range {
                            start: Position {
                                line: line_number - 1,
                                character: column_number,
                            },
                            end: Position {
                                line: line_number - 1,
                                character: column_number,
                            },
                        },
                        String::from(err_msg),
                    ));
                    continue;
                }
            }
            // if the above check for lines *and* columns didn't match, see if we
            // have an error message of the form:
            // :<line>: <error message here>
            if let Some(caps) = DIAG_REG_LINE_ONLY.captures(line) {
                if caps.len() < 3 {
                    // the entire capture is always at the 0th index,
                    // then we have 2 more explicit capture groups
                    continue;
                }
                let Ok(line_number) = caps[1].parse::<u32>() else {
                    continue;
                };
                let err_msg = &caps[2];
                diagnostics.push(Diagnostic::new_simple(
                    Range {
                        start: Position {
                            line: line_number - 1,
                            character: 0,
                        },
                        end: Position {
                            line: line_number - 1,
                            character: 0,
                        },
                    },
                    String::from(err_msg),
                ));
            }

            // ca65 has a slightly different format
            // file(<line>): <error message here>
            if let Some(caps) = ALT_DIAG_REG_LINE_ONLY.captures(line) {
                if caps.len() < 3 {
                    // the entire capture is always at the 0th index,
                    // then we have 2 more explicit capture groups
                    continue;
                }
                let Ok(line_number) = caps[1].parse::<u32>() else {
                    continue;
                };
                let err_msg = &caps[2];
                diagnostics.push(Diagnostic::new_simple(
                    Range {
                        start: Position {
                            line: line_number - 1,
                            character: 0,
                        },
                        end: Position {
                            line: line_number - 1,
                            character: 0,
                        },
                    },
                    String::from(err_msg),
                ));
            }
        }
    }
}

/// Function allowing us to connect tree sitter's logging with the log crate
#[allow(clippy::needless_pass_by_value)]
pub fn tree_sitter_logger(log_type: tree_sitter::LogType, message: &str) {
    // map tree-sitter log types to log levels, for now set everything to Trace
    let log_level = match log_type {
        tree_sitter::LogType::Parse | tree_sitter::LogType::Lex => log::Level::Trace,
    };

    // tree-sitter logs are incredibly verbose, only forward them to the logger
    // if we *really* need to see what's going on
    if log_enabled!(log_level) {
        log!(log_level, "{}", message);
    }
}

/// Convert an `lsp_types::TextDocumentContentChangeEvent` to a `tree_sitter::InputEdit`
///
/// # Errors
///
/// Returns `Err` if `change.range` is `None`, or if a `usize`->`u32` numeric conversion
/// failed
pub fn text_doc_change_to_ts_edit(
    change: &TextDocumentContentChangeEvent,
    doc: &FullTextDocument,
) -> Result<InputEdit> {
    let range = change.range.ok_or_else(|| anyhow!("Invalid edit range"))?;
    let start = range.start;
    let end = range.end;

    let start_byte = doc.offset_at(start) as usize;
    let new_end_byte = start_byte + change.text.len();
    let new_end_pos = doc.position_at(u32::try_from(new_end_byte)?);

    Ok(tree_sitter::InputEdit {
        start_byte,
        old_end_byte: doc.offset_at(end) as usize,
        new_end_byte,
        start_position: tree_sitter::Point {
            row: start.line as usize,
            column: start.character as usize,
        },
        old_end_position: tree_sitter::Point {
            row: end.line as usize,
            column: end.character as usize,
        },
        new_end_position: tree_sitter::Point {
            row: new_end_pos.line as usize,
            column: new_end_pos.character as usize,
        },
    })
}

/// Given a `NameTo_SomeItem_` map, returns a `Vec<CompletionItem>` for the items
/// contained within the map
#[must_use]
pub fn get_completes<T: Completable, U: ArchOrAssembler>(
    map: &HashMap<(U, String), T>,
    kind: Option<CompletionItemKind>,
) -> Vec<(U, CompletionItem)> {
    map.iter()
        .map(|((arch_or_asm, name), item_info)| {
            let value = item_info.to_string();

            (
                *arch_or_asm,
                CompletionItem {
                    label: (*name).to_string(),
                    kind,
                    documentation: Some(Documentation::MarkupContent(MarkupContent {
                        kind: MarkupKind::Markdown,
                        value,
                    })),
                    ..Default::default()
                },
            )
        })
        .collect()
}

#[must_use]
pub fn get_hover_resp(
    params: &HoverParams,
    config: &Config,
    word: &str,
    cursor_offset: usize,
    doc_store: &mut DocumentStore,
    store: &ServerStore,
) -> Option<Hover> {
    let instr_lookup = get_hover_resp_by_arch(word, &store.names_to_info.instructions, config);
    if instr_lookup.is_some() {
        return instr_lookup;
    }

    // directive lookup
    {
        if config.is_assembler_enabled(Assembler::Gas)
            || config.is_assembler_enabled(Assembler::Masm)
            || config.is_assembler_enabled(Assembler::Ca65)
            || config.is_assembler_enabled(Assembler::Avr)
            || config.is_assembler_enabled(Assembler::Fasm)
            || config.is_assembler_enabled(Assembler::Mars)
        {
            // all gas, AVR, and Mars directives have a '.' prefix, some masm directives do
            let directive_lookup =
                get_directive_hover_resp(word, &store.names_to_info.directives, config);
            if directive_lookup.is_some() {
                return directive_lookup;
            }
        } else if config.is_assembler_enabled(Assembler::Nasm) {
            // most nasm directives have no prefix, 2 have a '.' prefix
            let directive_lookup =
                get_directive_hover_resp(word, &store.names_to_info.directives, config);
            if directive_lookup.is_some() {
                return directive_lookup;
            }
            // Some nasm directives have a % prefix
            let prefixed = format!("%{word}");
            let directive_lookup =
                get_directive_hover_resp(&prefixed, &store.names_to_info.directives, config);
            if directive_lookup.is_some() {
                return directive_lookup;
            }
        }
    }

    let reg_lookup = if config.is_isa_enabled(Arch::ARM64) {
        word.find('.').map_or_else(
            || get_hover_resp_by_arch(word, &store.names_to_info.registers, config),
            |dot| {
                if cursor_offset <= dot {
                    // main vector register info on ARM64
                    let main_register = &word[0..dot];
                    get_hover_resp_by_arch(main_register, &store.names_to_info.registers, config)
                } else {
                    // if Vector = V21.2D -> lower Register = D21
                    // lower vector register info on ARM64
                    let reg_len = 3;
                    let mut lower_register = String::with_capacity(reg_len);
                    let reg_letter = dot + 2;
                    lower_register.push_str(&word[reg_letter..]);
                    let reg_num = 1..dot;
                    lower_register.push_str(&word[reg_num]);
                    get_hover_resp_by_arch(&lower_register, &store.names_to_info.registers, config)
                }
            },
        )
    } else {
        get_hover_resp_by_arch(word, &store.names_to_info.registers, config)
    };

    if reg_lookup.is_some() {
        return reg_lookup;
    }

    let label_data = get_label_resp(
        word,
        &params.text_document_position_params.text_document.uri,
        doc_store,
    );
    if label_data.is_some() {
        return label_data;
    }

    let demang = get_demangle_resp(word);
    if demang.is_some() {
        return demang;
    }

    let include_path = get_include_resp(
        &params.text_document_position_params.text_document.uri,
        word,
        &store.include_dirs,
    );
    if include_path.is_some() {
        return include_path;
    }

    None
}

fn search_for_hoverable_by_arch<'a, T: Hoverable>(
    word: &'a str,
    map: &'a HashMap<(Arch, String), T>,
    config: &Config,
) -> (Option<&'a T>, Option<&'a T>) {
    match config.instruction_set {
        Arch::X86_AND_X86_64 => {
            let x86_resp = map.get(&(Arch::X86, word.to_string()));
            let x86_64_resp = map.get(&(Arch::X86_64, word.to_string()));
            (x86_resp, x86_64_resp)
        }
        arch => (map.get(&(arch, word.to_string())), None),
    }
}

fn search_for_dir_by_assembler<'a>(
    word: &'a str,
    dir_map: &'a HashMap<(Assembler, String), Directive>,
    config: &Config,
) -> Option<&'a Directive> {
    dir_map.get(&(config.assembler, word.to_string()))
}

fn get_hover_resp_by_arch<T: Hoverable>(
    word: &str,
    map: &HashMap<(Arch, String), T>,
    config: &Config,
) -> Option<Hover> {
    // ensure hovered text is always lowercase
    let hovered_word = word.to_ascii_lowercase();
    let instr_resp = search_for_hoverable_by_arch(&hovered_word, map, config);
    let value = match instr_resp {
        (Some(resp1), Some(resp2)) => {
            format!("{resp1}\n\n{resp2}")
        }
        (Some(resp), None) | (None, Some(resp)) => {
            format!("{resp}")
        }
        (None, None) => return None,
    };

    Some(Hover {
        contents: HoverContents::Markup(MarkupContent {
            kind: MarkupKind::Markdown,
            value,
        }),
        range: None,
    })
}

fn get_directive_hover_resp(
    word: &str,
    dir_map: &HashMap<(Assembler, String), Directive>,
    config: &Config,
) -> Option<Hover> {
    let hovered_word = word.to_ascii_lowercase();
    search_for_dir_by_assembler(&hovered_word, dir_map, config).map(|dir_resp| Hover {
        contents: HoverContents::Markup(MarkupContent {
            kind: MarkupKind::Markdown,
            value: dir_resp.to_string(),
        }),
        range: None,
    })
}

/// Returns the data associated with a given label `word`
fn get_label_resp(word: &str, uri: &Uri, doc_store: &mut DocumentStore) -> Option<Hover> {
    if let Some(doc) = doc_store.text_store.get_document(uri) {
        let curr_doc = doc.get_content(None).as_bytes();
        if let Some(ref mut tree_entry) = doc_store.tree_store.get_mut(uri) {
            tree_entry.tree = tree_entry.parser.parse(curr_doc, tree_entry.tree.as_ref());
            if let Some(ref tree) = tree_entry.tree {
                static QUERY_LABEL_DATA: LazyLock<tree_sitter::Query> = LazyLock::new(|| {
                    tree_sitter::Query::new(
                        &tree_sitter_asm::language(),
                        "(
                            (label (ident) @label)
                            .
                            (meta
	                            (
                                    [
                                        (int)
                                        (string)
                                        (float)
                                    ]
                                )
                            ) @data
                        )",
                    )
                    .unwrap()
                });
                let mut cursor = tree_sitter::QueryCursor::new();
                let matches_iter = cursor.matches(&QUERY_LABEL_DATA, tree.root_node(), curr_doc);

                for match_ in matches_iter {
                    let caps = match_.captures;
                    if caps.len() != 2
                        || caps[0].node.end_byte() >= curr_doc.len()
                        || caps[1].node.end_byte() >= curr_doc.len()
                    {
                        continue;
                    }
                    let label_text = caps[0].node.utf8_text(curr_doc);
                    let label_data = caps[1].node.utf8_text(curr_doc);
                    match (label_text, label_data) {
                        (Ok(label), Ok(data))
                            // Some labels have a preceding '.' that we need to account for
                            if label.eq(word) || label.trim_start_matches('.').eq(word) =>
                        {
                            return Some(Hover {
                                contents: HoverContents::Markup(MarkupContent {
                                    kind: MarkupKind::Markdown,
                                    value: format!("`{data}`"),
                                }),
                                range: None,
                            });
                        }
                        _ => {}
                    }
                }
            }
        }
    }
    None
}

fn get_demangle_resp(word: &str) -> Option<Hover> {
    let name = Name::new(word, NameMangling::Mangled, Language::Unknown);
    let demangled = name.demangle(DemangleOptions::complete());
    if let Some(demang) = demangled {
        let value = demang;
        return Some(Hover {
            contents: HoverContents::Markup(MarkupContent {
                kind: MarkupKind::Markdown,
                value,
            }),
            range: None,
        });
    }

    None
}

fn get_include_resp(
    source_file: &Uri,
    filename: &str,
    include_dirs: &HashMap<SourceFile, Vec<PathBuf>>,
) -> Option<Hover> {
    let mut paths = String::new();

    type DirIter<'a> = Box<dyn Iterator<Item = &'a PathBuf> + 'a>;
    let mut dir_iter = include_dirs.get(&SourceFile::All).map_or_else(
        || Box::new(std::iter::empty()) as DirIter,
        |dirs| Box::new(dirs.iter()) as DirIter,
    );

    if let Ok(src_path) = PathBuf::from(source_file.as_str()).canonicalize()
        && let Some(dirs) = include_dirs.get(&SourceFile::File(src_path))
    {
        dir_iter = Box::new(dir_iter.chain(dirs.iter()));
    }

    for dir in dir_iter {
        match std::fs::read_dir(dir) {
            Ok(dir_reader) => {
                for file in dir_reader {
                    match file {
                        Ok(f) => {
                            if f.file_name() == filename {
                                writeln!(&mut paths, "file://{}", f.path().display()).unwrap();
                            }
                        }
                        Err(e) => {
                            error!(
                                "Failed to read item in {} - Error {e}",
                                dir.as_path().display()
                            );
                        }
                    }
                }
            }
            Err(e) => {
                error!(
                    "Failed to create directory reader for {} - Error {e}",
                    dir.as_path().display()
                );
            }
        }
    }

    if paths.is_empty() {
        None
    } else {
        Some(Hover {
            contents: HoverContents::Markup(MarkupContent {
                kind: MarkupKind::Markdown,
                value: paths,
            }),
            range: None,
        })
    }
}

/// Filter out duplicate completion suggestions, and those that aren't allowed
/// by `config`
fn filtered_comp_list_arch(
    comps: &[(Arch, CompletionItem)],
    config: &Config,
) -> Vec<CompletionItem> {
    let mut seen = HashSet::new();
    comps
        .iter()
        .filter(|(arch, comp_item)| {
            if !config.is_isa_enabled(*arch) {
                return false;
            }
            if seen.contains(&comp_item.label) {
                false
            } else {
                seen.insert(&comp_item.label);
                true
            }
        })
        .map(|(_, comp_item)| comp_item)
        .cloned()
        .collect()
}

/// Filter out duplicate completion suggestions, and those that aren't allowed
/// by `config`
/// 'prefix' allows the caller to optionally require completion items to start with
/// a given character
fn filtered_comp_list_assem(
    comps: &[(Assembler, CompletionItem)],
    config: &Config,
    prefix: Option<char>,
) -> Vec<CompletionItem> {
    let mut seen = HashSet::new();
    comps
        .iter()
        .filter(|(assem, comp_item)| {
            if !config.is_assembler_enabled(*assem) {
                return false;
            }
            if let Some(c) = prefix
                && !comp_item.label.starts_with(c)
            {
                return false;
            }
            if seen.contains(&comp_item.label) {
                false
            } else {
                seen.insert(&comp_item.label);
                true
            }
        })
        .map(|(_, comp_item)| comp_item)
        .cloned()
        .collect()
}

macro_rules! cursor_matches {
    ($cursor_line:expr,$cursor_char:expr,$query_start:expr,$query_end:expr) => {{
        $query_start.row == $cursor_line
            && $query_end.row == $cursor_line
            && $query_start.column <= $cursor_char
            && $query_end.column >= $cursor_char
    }};
}

pub fn get_comp_resp(
    curr_doc: &str,
    tree_entry: &mut TreeEntry,
    params: &CompletionParams,
    config: &Config,
    completion_items: &CompletionItems,
) -> Option<CompletionList> {
    let cursor_line = params.text_document_position.position.line as usize;
    let cursor_char = params.text_document_position.position.character as usize;

    if let Some(ctx) = params.context.as_ref()
        && ctx.trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER
    {
        match ctx
            .trigger_character
            .as_ref()
            .map(std::convert::AsRef::as_ref)
        {
            // prepend GAS registers, some NASM directives with "%"
            Some("%") => {
                let mut items = Vec::new();
                if config.is_isa_enabled(Arch::X86) || config.is_isa_enabled(Arch::X86_64) {
                    items.append(&mut filtered_comp_list_arch(
                        &completion_items.registers,
                        config,
                    ));
                }
                if config.is_assembler_enabled(Assembler::Nasm) {
                    items.append(&mut filtered_comp_list_assem(
                        &completion_items.directives,
                        config,
                        Some('%'),
                    ));
                }

                if !items.is_empty() {
                    return Some(CompletionList {
                        is_incomplete: true,
                        items,
                    });
                }
            }
            // prepend all GAS, all Ca65, all AVR, all Mars, some MASM, some NASM directives with "."
            Some(".") => {
                if config.is_assembler_enabled(Assembler::Gas)
                    || config.is_assembler_enabled(Assembler::Masm)
                    || config.is_assembler_enabled(Assembler::Nasm)
                    || config.is_assembler_enabled(Assembler::Ca65)
                    || config.is_assembler_enabled(Assembler::Avr)
                    || config.is_assembler_enabled(Assembler::Mars)
                {
                    return Some(CompletionList {
                        is_incomplete: true,
                        items: filtered_comp_list_assem(
                            &completion_items.directives,
                            config,
                            Some('.'),
                        ),
                    });
                }
            }
            // prepend all Mips registers with "$"
            Some("$") => {
                if config.is_isa_enabled(Arch::Mips) {
                    return Some(CompletionList {
                        is_incomplete: true,
                        items: filtered_comp_list_arch(&completion_items.registers, config),
                    });
                }
            }
            _ => {}
        }
    }

    // TODO: filter register completions by width allowed by corresponding instruction
    tree_entry.tree = tree_entry.parser.parse(curr_doc, tree_entry.tree.as_ref());
    if let Some(ref tree) = tree_entry.tree {
        static QUERY_DIRECTIVE: LazyLock<tree_sitter::Query> = LazyLock::new(|| {
            tree_sitter::Query::new(
                &tree_sitter_asm::language(),
                "(meta kind: (meta_ident) @directive)",
            )
            .unwrap()
        });
        let mut line_cursor = tree_sitter::QueryCursor::new();
        line_cursor.set_point_range(std::ops::Range {
            start: tree_sitter::Point {
                row: cursor_line,
                column: 0,
            },
            end: tree_sitter::Point {
                row: cursor_line,
                column: usize::MAX,
            },
        });
        let curr_doc = curr_doc.as_bytes();

        let matches_iter = line_cursor.matches(&QUERY_DIRECTIVE, tree.root_node(), curr_doc);

        for match_ in matches_iter {
            let caps = match_.captures;
            for cap in caps {
                let arg_start = cap.node.range().start_point;
                let arg_end = cap.node.range().end_point;
                if cursor_matches!(cursor_line, cursor_char, arg_start, arg_end) {
                    let items =
                        filtered_comp_list_assem(&completion_items.directives, config, None);
                    return Some(CompletionList {
                        is_incomplete: true,
                        items,
                    });
                }
            }
        }

        // tree-sitter-asm currently parses label arguments to instructions as *registers*
        // We'll collect all of labels in the document (that are being parsed as labels, at least)
        // and suggest those along with the register completions
        static QUERY_LABEL: LazyLock<tree_sitter::Query> = LazyLock::new(|| {
            tree_sitter::Query::new(&tree_sitter_asm::language(), "(label (ident) @label)").unwrap()
        });

        // need a separate cursor to search the entire document
        let mut doc_cursor = tree_sitter::QueryCursor::new();
        let captures = doc_cursor.captures(&QUERY_LABEL, tree.root_node(), curr_doc);
        let mut labels = HashSet::new();
        for caps in captures.map(|c| c.0) {
            for cap in caps.captures {
                if cap.node.end_byte() >= curr_doc.len() {
                    continue;
                }
                if let Ok(text) = cap.node.utf8_text(curr_doc) {
                    labels.insert(text);
                }
            }
        }

        static QUERY_INSTR_ANY: LazyLock<tree_sitter::Query> = LazyLock::new(|| {
            tree_sitter::Query::new(
                &tree_sitter_asm::language(),
                "[
                    (instruction kind: (word) @instr_name)
                    (
                        instruction kind: (word) @instr_name
                            [
                                (
                                    [
                                     (ident (reg) @r1)
                                     (ptr (int) (reg) @r1)
                                     (ptr (reg) @r1)
                                     (ptr (int))
                                     (ptr)
                                    ]
                                    [
                                     (ident (reg) @r2)
                                     (ptr (int) (reg) @r2)
                                     (ptr (reg) @r2)
                                     (ptr (int))
                                     (ptr)
                                    ]
                                )
                                (
                                    [
                                     (ident (reg) @r1)
                                     (ptr (int) (reg) @r1)
                                     (ptr (reg) @r1)
                                    ]
                                )
                            ]
                    )
                ]",
            )
            .unwrap()
        });

        let matches_iter = line_cursor.matches(&QUERY_INSTR_ANY, tree.root_node(), curr_doc);
        for match_ in matches_iter {
            let caps = match_.captures;
            for (cap_num, cap) in caps.iter().enumerate() {
                let arg_start = cap.node.range().start_point;
                let arg_end = cap.node.range().end_point;
                if cursor_matches!(cursor_line, cursor_char, arg_start, arg_end) {
                    // an instruction is always capture #0 for this query, any capture
                    // number after must be a register or label
                    let is_instr = cap_num == 0;
                    let mut items = filtered_comp_list_arch(
                        if is_instr {
                            &completion_items.instructions
                        } else {
                            &completion_items.registers
                        },
                        config,
                    );
                    if is_instr {
                        // Sometimes tree-sitter-asm parses a directive as an instruction, so we'll
                        // suggest both in this case
                        items.append(&mut filtered_comp_list_assem(
                            &completion_items.directives,
                            config,
                            None,
                        ));
                    } else {
                        items.append(
                            &mut labels
                                .iter()
                                .map(|l| CompletionItem {
                                    label: (*l).to_string(),
                                    kind: Some(CompletionItemKind::VARIABLE),
                                    ..Default::default()
                                })
                                .collect(),
                        );
                    }
                    return Some(CompletionList {
                        is_incomplete: true,
                        items,
                    });
                }
            }
        }
    }

    None
}

const fn lsp_pos_of_point(pos: tree_sitter::Point) -> lsp_types::Position {
    Position {
        line: pos.row as u32,
        character: pos.column as u32,
    }
}

/// Explore `node`, push immediate children into `res`.
fn explore_node(
    curr_doc: &str,
    node: tree_sitter::Node,
    res: &mut Vec<DocumentSymbol>,
    label_kind_id: u16,
    ident_kind_id: u16,
) {
    if node.kind_id() == label_kind_id {
        let mut children = vec![];
        let mut cursor = node.walk();

        // description for this node
        let mut descr = String::new();

        if cursor.goto_first_child() {
            loop {
                let sub_node = cursor.node();
                if sub_node.kind_id() == ident_kind_id
                    && let Ok(text) = sub_node.utf8_text(curr_doc.as_bytes())
                {
                    descr = text.to_string();
                }

                explore_node(
                    curr_doc,
                    sub_node,
                    &mut children,
                    label_kind_id,
                    ident_kind_id,
                );
                if !cursor.goto_next_sibling() {
                    break;
                }
            }
        }

        let range = lsp_types::Range::new(
            lsp_pos_of_point(node.start_position()),
            lsp_pos_of_point(node.end_position()),
        );

        #[allow(deprecated)]
        let doc = DocumentSymbol {
            name: descr,
            detail: None,
            kind: SymbolKind::FUNCTION,
            tags: None,
            deprecated: Some(false),
            range,
            selection_range: range,
            children: if children.is_empty() {
                None
            } else {
                Some(children)
            },
        };
        res.push(doc);
    } else {
        let mut cursor = node.walk();

        if cursor.goto_first_child() {
            loop {
                explore_node(curr_doc, cursor.node(), res, label_kind_id, ident_kind_id);
                if !cursor.goto_next_sibling() {
                    break;
                }
            }
        }
    }
}

/// Get a tree of symbols describing the document's structure.
pub fn get_document_symbols(
    curr_doc: &str,
    tree_entry: &mut TreeEntry,
    _params: &DocumentSymbolParams,
) -> Option<Vec<DocumentSymbol>> {
    static LABEL_KIND_ID: LazyLock<u16> =
        LazyLock::new(|| tree_sitter_asm::language().id_for_node_kind("label", true));
    static IDENT_KIND_ID: LazyLock<u16> =
        LazyLock::new(|| tree_sitter_asm::language().id_for_node_kind("ident", true));
    tree_entry.tree = tree_entry.parser.parse(curr_doc, tree_entry.tree.as_ref());

    tree_entry.tree.as_ref().map(|tree| {
        let mut res: Vec<DocumentSymbol> = vec![];
        let mut cursor = tree.walk();
        loop {
            explore_node(
                curr_doc,
                cursor.node(),
                &mut res,
                *LABEL_KIND_ID,
                *IDENT_KIND_ID,
            );
            if !cursor.goto_next_sibling() {
                break;
            }
        }
        res
    })
}

/// Produces a signature help response if the appropriate instruction forms can
/// be found
pub fn get_sig_help_resp(
    curr_doc: &str,
    params: &SignatureHelpParams,
    config: &Config,
    tree_entry: &mut TreeEntry,
    instr_info: &NameToInstructionMap,
) -> Option<SignatureHelp> {
    let cursor_line = params.text_document_position_params.position.line as usize;

    tree_entry.tree = tree_entry.parser.parse(curr_doc, tree_entry.tree.as_ref());
    if let Some(ref tree) = tree_entry.tree {
        // Instruction with any (including zero) argument(s)
        static QUERY_INSTR_ANY_ARGS: LazyLock<tree_sitter::Query> = LazyLock::new(|| {
            tree_sitter::Query::new(
                &tree_sitter_asm::language(),
                "(instruction kind: (word) @instr_name)",
            )
            .unwrap()
        });

        let mut line_cursor = tree_sitter::QueryCursor::new();
        line_cursor.set_point_range(std::ops::Range {
            start: tree_sitter::Point {
                row: cursor_line,
                column: 0,
            },
            end: tree_sitter::Point {
                row: cursor_line,
                column: usize::MAX,
            },
        });
        let curr_doc = curr_doc.as_bytes();

        let matches: Vec<tree_sitter::QueryMatch<'_, '_>> = line_cursor
            .matches(&QUERY_INSTR_ANY_ARGS, tree.root_node(), curr_doc)
            .collect();
        if let Some(match_) = matches.first() {
            let caps = match_.captures;
            if caps.len() == 1
                && caps[0].node.end_byte() < curr_doc.len()
                && let Ok(instr_name) = caps[0].node.utf8_text(curr_doc)
            {
                let mut value = String::new();
                let (instr1, instr2) = search_for_hoverable_by_arch(instr_name, instr_info, config);
                let instructions = vec![instr1, instr2];
                for instr in instructions.into_iter().flatten() {
                    for form in &instr.forms {
                        match instr.arch {
                            Arch::X86 | Arch::X86_64 => {
                                if let Some(ref gas_name) = form.gas_name
                                    && instr_name.eq_ignore_ascii_case(gas_name)
                                {
                                    writeln!(&mut value, "**{}**\n{form}", instr.arch).unwrap();
                                } else if let Some(ref go_name) = form.go_name
                                    && instr_name.eq_ignore_ascii_case(go_name)
                                {
                                    writeln!(&mut value, "**{}**\n{form}", instr.arch).unwrap();
                                }
                            }
                            Arch::Z80 => {
                                for form in &instr.forms {
                                    if let Some(ref z80_name) = form.z80_name
                                        && instr_name.eq_ignore_ascii_case(z80_name)
                                    {
                                        writeln!(&mut value, "{form}").unwrap();
                                    }
                                }
                            }
                            Arch::ARM | Arch::RISCV => {
                                for form in &instr.asm_templates {
                                    writeln!(&mut value, "{form}").unwrap();
                                }
                            }
                            _ => {}
                        }
                    }
                }
                if !value.is_empty() {
                    return Some(SignatureHelp {
                        signatures: vec![SignatureInformation {
                            label: instr_name.to_string(),
                            documentation: Some(Documentation::MarkupContent(MarkupContent {
                                kind: MarkupKind::Markdown,
                                value,
                            })),
                            parameters: None,
                            active_parameter: None,
                        }],
                        active_signature: None,
                        active_parameter: None,
                    });
                }
            }
        }
    }

    None
}

pub fn get_goto_def_resp(
    curr_doc: &FullTextDocument,
    tree_entry: &mut TreeEntry,
    params: &GotoDefinitionParams,
) -> Option<GotoDefinitionResponse> {
    let doc = curr_doc.get_content(None).as_bytes();
    tree_entry.tree = tree_entry.parser.parse(doc, tree_entry.tree.as_ref());

    if let Some(ref tree) = tree_entry.tree {
        static QUERY_LABEL: LazyLock<tree_sitter::Query> = LazyLock::new(|| {
            tree_sitter::Query::new(&tree_sitter_asm::language(), "(label) @label").unwrap()
        });

        let is_not_ident_char = |c: char| !(c.is_alphanumeric() || c == '_');
        let mut cursor = tree_sitter::QueryCursor::new();
        let matches = cursor.matches(&QUERY_LABEL, tree.root_node(), doc);

        let (word, _) = get_word_from_pos_params(curr_doc, &params.text_document_position_params);

        for match_ in matches {
            for cap in match_.captures {
                if cap.node.end_byte() >= doc.len() {
                    continue;
                }
                let text = cap
                    .node
                    .utf8_text(doc)
                    .unwrap_or("")
                    .trim()
                    .trim_matches(is_not_ident_char);

                if word.eq(text) {
                    let start = cap.node.start_position();
                    let end = cap.node.end_position();
                    return Some(GotoDefinitionResponse::Scalar(Location {
                        uri: params
                            .text_document_position_params
                            .text_document
                            .uri
                            .clone(),
                        range: Range {
                            start: lsp_pos_of_point(start),
                            end: lsp_pos_of_point(end),
                        },
                    }));
                }
            }
        }
    }

    None
}

pub fn get_ref_resp(
    params: &ReferenceParams,
    curr_doc: &FullTextDocument,
    tree_entry: &mut TreeEntry,
) -> Vec<Location> {
    let mut refs: HashSet<Location> = HashSet::new();
    let doc = curr_doc.get_content(None).as_bytes();
    tree_entry.tree = tree_entry.parser.parse(doc, tree_entry.tree.as_ref());

    if let Some(ref tree) = tree_entry.tree {
        static QUERY_LABEL: LazyLock<tree_sitter::Query> = LazyLock::new(|| {
            tree_sitter::Query::new(
                &tree_sitter_asm::language(),
                "(label (ident (reg (word)))) @label",
            )
            .unwrap()
        });

        static QUERY_WORD: LazyLock<tree_sitter::Query> = LazyLock::new(|| {
            tree_sitter::Query::new(&tree_sitter_asm::language(), "(ident) @ident").unwrap()
        });

        let is_not_ident_char = |c: char| !(c.is_alphanumeric() || c == '_');
        let (word, _) = get_word_from_pos_params(curr_doc, &params.text_document_position);
        let uri = &params.text_document_position.text_document.uri;

        let mut cursor = tree_sitter::QueryCursor::new();
        if params.context.include_declaration {
            let label_matches = cursor.matches(&QUERY_LABEL, tree.root_node(), doc);
            for match_ in label_matches {
                for cap in match_.captures {
                    // HACK: Temporary solution for what I believe is a bug in tree-sitter core
                    if cap.node.end_byte() >= doc.len() {
                        continue;
                    }
                    let text = cap
                        .node
                        .utf8_text(doc)
                        .unwrap_or("")
                        .trim()
                        .trim_matches(is_not_ident_char);

                    if word.eq(text) {
                        let start = lsp_pos_of_point(cap.node.start_position());
                        let end = lsp_pos_of_point(cap.node.end_position());
                        refs.insert(Location {
                            uri: uri.clone(),
                            range: Range { start, end },
                        });
                    }
                }
            }
        }

        let word_matches = cursor.matches(&QUERY_WORD, tree.root_node(), doc);
        for match_ in word_matches {
            for cap in match_.captures {
                // HACK: Temporary solution for what I believe is a bug in tree-sitter core
                if cap.node.end_byte() >= doc.len() {
                    continue;
                }
                let text = cap
                    .node
                    .utf8_text(doc)
                    .unwrap_or("")
                    .trim()
                    .trim_matches(is_not_ident_char);

                if word.eq(text) {
                    let start = lsp_pos_of_point(cap.node.start_position());
                    let end = lsp_pos_of_point(cap.node.end_position());
                    refs.insert(Location {
                        uri: uri.clone(),
                        range: Range { start, end },
                    });
                }
            }
        }
    }

    refs.into_iter().collect()
}

/// Searches for global config in ~/.config/asm-lsp, then the project's directory
/// Project specific configs will override global configs
///
/// If no valid config files can be found, this function will cause the program
/// to exit with code -1
///
/// # Errors
///
/// Will return `Err` if an invalid configuration file is found
pub fn get_root_config(params: &InitializeParams) -> Result<RootConfig> {
    let report_err = |msg: &str| -> Result<RootConfig> {
        error!("{msg}");
        Err(anyhow!(msg.to_string()))
    };
    let mut config = match (get_global_config(), get_project_config(params)) {
        // If we have a valid project config, ignore bad global configs
        (_, Some(Ok(proj_cfg))) => proj_cfg,
        (Some(Ok(global_cfg)), None) => global_cfg,
        (Some(Ok(_)) | None, Some(Err(e))) => {
            return report_err(&format!("Inavlid project config file -- {e}"));
        }
        (Some(Err(e)), None) => {
            return report_err(&format!("Invalid global config file -- {e}"));
        }
        (Some(Err(e_global)), Some(Err(e_project))) => {
            return report_err(&format!(
                "Invalid project and global config files -- {e_project} -- {e_global}"
            ));
        }
        (None, None) => {
            info!("No configuration files found, using default options");
            RootConfig::default()
        }
    };

    // Validate project paths and enforce default diagnostics settings
    if let Some(ref mut projects) = config.projects {
        if let Some(ref project_root) = get_project_root(params) {
            let mut project_idx = 0;
            while project_idx < projects.len() {
                let mut project_path = project_root.clone();
                project_path.push(&projects[project_idx].path);
                let Ok(canonicalized_project_path) = project_path.canonicalize() else {
                    return report_err(&format!(
                        "Failed to canonicalize project path \"{}\".",
                        project_path.display()
                    ));
                };
                projects[project_idx].path = canonicalized_project_path;
                if let Some(ref mut opts) = projects[project_idx].config.opts {
                    // Want diagnostics enabled by default
                    if opts.diagnostics.is_none() {
                        opts.diagnostics = Some(true);
                    }
                    // Want default diagnostics enabled by default
                    if opts.default_diagnostics.is_none() {
                        opts.default_diagnostics = Some(true);
                    }
                } else {
                    projects[project_idx].config.opts = Some(ConfigOptions::default());
                }

                project_idx += 1;
            }
        } else {
            return report_err("Unable to detect project root directory.");
        }

        // sort project configurations so when we select a project config at request
        // time, we find configs controlling specific files first, and then configs
        // for a sub-directory of another config before the parent config
        projects.sort_unstable_by(|c1, c2| {
            // - If both are files, we don't care
            // - If one is file and other is directory, file goes first
            // - Else (just assuming both are directories for the default case),
            //   go by the length metric (parent directories get placed *after*
            //   their children)
            let c1_dir = c1.path.is_dir();
            let c1_file = c1.path.is_file();
            let c2_dir = c2.path.is_dir();
            let c2_file = c2.path.is_file();
            if c1_file && c2_file {
                Ordering::Equal
            } else if c1_dir && c2_file {
                Ordering::Greater
            } else if c1_file && c2_dir {
                Ordering::Less
            } else {
                c2.path
                    .to_string_lossy()
                    .len()
                    .cmp(&c1.path.to_string_lossy().len())
            }
        });

        // Check if the user specified multiple configs pointing to the same
        // file or directory
        let mut path_check = HashSet::new();
        for project in projects {
            if path_check.contains(&project.path) {
                return report_err(&format!(
                    "Multiple project configurations for \"{}\".",
                    project.path.display()
                ));
            }
            path_check.insert(&project.path);
        }
    }

    // Enforce default diagnostics settings for default config
    if let Some(ref mut default_cfg) = config.default_config {
        if let Some(ref mut opts) = default_cfg.opts {
            // Want diagnostics enabled by default
            if opts.diagnostics.is_none() {
                opts.diagnostics = Some(true);
            }
            // Want default diagnostics enabled by default
            if opts.default_diagnostics.is_none() {
                opts.default_diagnostics = Some(true);
            }
        } else {
            default_cfg.opts = Some(ConfigOptions::default());
        }
    } else {
        info!("No `default_config` specified, filling in default options");
        // provide a default empty configuration for sub-directories
        // not specified in `projects`
        config.default_config = Some(Config::default());
    }

    Ok(config)
}

#[must_use]
pub fn get_global_cfg_dirs() -> Vec<Option<PathBuf>> {
    if cfg!(target_os = "macos") {
        // `$HOME`/Library/Application Support/ and `$HOME`/.config/
        vec![config_dir(), alt_mac_config_dir()]
    } else {
        vec![config_dir()]
    }
}

/// Checks ~/.config/asm-lsp for a config file, creating directories along the way as necessary
fn get_global_config() -> Option<Result<RootConfig>> {
    let mut paths = get_global_cfg_dirs();

    for cfg_path in paths.iter_mut().flatten() {
        cfg_path.push("asm-lsp");
        info!(
            "Creating directories along {} as necessary...",
            cfg_path.display()
        );
        match create_dir_all(&cfg_path) {
            Ok(()) => {
                cfg_path.push(".asm-lsp.toml");
                if let Ok(config) = std::fs::read_to_string(&cfg_path) {
                    let cfg_path_s = cfg_path.display();
                    match toml::from_str::<RootConfig>(&config) {
                        Ok(config) => {
                            info!(
                                "Parsing global asm-lsp config from file -> {}",
                                cfg_path.display()
                            );
                            return Some(Ok(config));
                        }
                        Err(e) => {
                            error!("Failed to parse global config file {cfg_path_s} - Error: {e}");
                            return Some(Err(e.into()));
                        }
                    }
                }
            }
            Err(e) => {
                error!(
                    "Failed to create global config directory {} - Error: {e}",
                    cfg_path.display()
                );
            }
        }
    }

    None
}

// Returns `$HOME`/.config/ for usage on MacOS, as this isn't the default
// config directory
#[must_use]
pub fn alt_mac_config_dir() -> Option<PathBuf> {
    home::home_dir().map(|mut path| {
        path.push(".config");
        path
    })
}

/// Attempts to find the project's root directory given its `InitializeParams`
// 1. if we have workspace folders, then iterate through them and assign the first valid one to
//    the root path
// 2. If we don't have worksace folders or none of them is a valid path, check the (deprecated)
//    root_uri field
// 3. If both workspace folders and root_uri didn't provide a path, check the (deprecated)
//    root_path field
fn get_project_root(params: &InitializeParams) -> Option<PathBuf> {
    // first check workspace folders
    if let Some(folders) = &params.workspace_folders {
        // if there's multiple, just visit in order until we find a valid folder
        for folder in folders {
            let Ok(parsed) = PathBuf::from_str(folder.uri.path().as_str());
            if let Ok(parsed_path) = parsed.canonicalize() {
                info!("Detected project root: {}", parsed_path.display());
                return Some(parsed_path);
            }
        }
    }

    // if workspace folders weren't set or came up empty, we check the root_uri
    #[allow(deprecated)]
    if let Some(root_uri) = &params.root_uri {
        let Ok(parsed) = PathBuf::from_str(root_uri.path().as_str());
        if let Ok(parsed_path) = parsed.canonicalize() {
            info!("Detected project root: {}", parsed_path.display());
            return Some(parsed_path);
        }
    }

    // if both `workspace_folders` and `root_uri` weren't set or came up empty, we check the root_path
    #[allow(deprecated)]
    if let Some(root_path) = &params.root_path {
        let Ok(parsed) = PathBuf::from_str(root_path.as_str());
        if let Ok(parsed_path) = parsed.canonicalize() {
            return Some(parsed_path);
        }
    }

    warn!("Failed to detect project root");
    None
}

/// checks for a config specific to the project's root directory
///
/// # Errors
///
/// Returns `Err` if the file cannot be deserialized
fn get_project_config(params: &InitializeParams) -> Option<Result<RootConfig>> {
    if let Some(mut path) = get_project_root(params) {
        path.push(".asm-lsp.toml");
        match std::fs::read_to_string(&path) {
            Ok(config) => match toml::from_str::<RootConfig>(&config) {
                Ok(config) => {
                    info!(
                        "Parsing asm-lsp project config from file -> {}",
                        path.display()
                    );
                    return Some(Ok(config));
                }
                Err(e) => {
                    error!(
                        "Failed to parse project config file {} - Error: {e}",
                        path.display()
                    );
                    return Some(Err(e.into()));
                }
            },
            Err(e) => {
                error!("Failed to read config file {} - Error: {e}", path.display());
            }
        }
    }

    None
}

#[must_use]
pub fn instr_filter_targets(instr: &Instruction, config: &Config) -> Instruction {
    let mut instr = instr.clone();

    let forms = instr
        .forms
        .iter()
        .filter(|form| {
            (form.gas_name.is_some() && config.is_assembler_enabled(Assembler::Gas))
                || (form.go_name.is_some() && config.is_assembler_enabled(Assembler::Go))
        })
        .map(|form| {
            let mut filtered = form.clone();
            // handle cases where gas and go both have names on the same form
            if !config.is_assembler_enabled(Assembler::Gas) {
                filtered.gas_name = None;
            }
            if !config.is_assembler_enabled(Assembler::Go) {
                filtered.go_name = None;
            }
            filtered
        })
        .collect();

    instr.forms = forms;
    instr
}