kcl-lib 0.2.146

KittyCAD Language implementation and tools
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
//! Functions for the `kcl` lsp server.
#![allow(dead_code)]

use std::cell::Cell;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex;

use anyhow::Result;
#[cfg(feature = "cli")]
use clap::Parser;
use dashmap::DashMap;
use tokio::sync::RwLock;
use tower_lsp::Client;
use tower_lsp::LanguageServer;
use tower_lsp::jsonrpc::Result as RpcResult;
use tower_lsp::lsp_types::CodeAction;
use tower_lsp::lsp_types::CodeActionKind;
use tower_lsp::lsp_types::CodeActionOptions;
use tower_lsp::lsp_types::CodeActionOrCommand;
use tower_lsp::lsp_types::CodeActionParams;
use tower_lsp::lsp_types::CodeActionProviderCapability;
use tower_lsp::lsp_types::CodeActionResponse;
use tower_lsp::lsp_types::ColorInformation;
use tower_lsp::lsp_types::ColorPresentation;
use tower_lsp::lsp_types::ColorPresentationParams;
use tower_lsp::lsp_types::ColorProviderCapability;
use tower_lsp::lsp_types::CompletionItem;
use tower_lsp::lsp_types::CompletionItemKind;
use tower_lsp::lsp_types::CompletionOptions;
use tower_lsp::lsp_types::CompletionParams;
use tower_lsp::lsp_types::CompletionResponse;
use tower_lsp::lsp_types::CreateFilesParams;
use tower_lsp::lsp_types::DeleteFilesParams;
use tower_lsp::lsp_types::Diagnostic;
use tower_lsp::lsp_types::DiagnosticOptions;
use tower_lsp::lsp_types::DiagnosticServerCapabilities;
use tower_lsp::lsp_types::DiagnosticSeverity;
use tower_lsp::lsp_types::DidChangeConfigurationParams;
use tower_lsp::lsp_types::DidChangeTextDocumentParams;
use tower_lsp::lsp_types::DidChangeWatchedFilesParams;
use tower_lsp::lsp_types::DidChangeWorkspaceFoldersParams;
use tower_lsp::lsp_types::DidCloseTextDocumentParams;
use tower_lsp::lsp_types::DidOpenTextDocumentParams;
use tower_lsp::lsp_types::DidSaveTextDocumentParams;
use tower_lsp::lsp_types::DocumentColorParams;
use tower_lsp::lsp_types::DocumentDiagnosticParams;
use tower_lsp::lsp_types::DocumentDiagnosticReport;
use tower_lsp::lsp_types::DocumentDiagnosticReportResult;
use tower_lsp::lsp_types::DocumentFilter;
use tower_lsp::lsp_types::DocumentFormattingParams;
use tower_lsp::lsp_types::DocumentSymbol;
use tower_lsp::lsp_types::DocumentSymbolParams;
use tower_lsp::lsp_types::DocumentSymbolResponse;
use tower_lsp::lsp_types::Documentation;
use tower_lsp::lsp_types::FoldingRange;
use tower_lsp::lsp_types::FoldingRangeParams;
use tower_lsp::lsp_types::FoldingRangeProviderCapability;
use tower_lsp::lsp_types::FullDocumentDiagnosticReport;
use tower_lsp::lsp_types::Hover as LspHover;
use tower_lsp::lsp_types::HoverContents;
use tower_lsp::lsp_types::HoverParams;
use tower_lsp::lsp_types::HoverProviderCapability;
use tower_lsp::lsp_types::InitializeParams;
use tower_lsp::lsp_types::InitializeResult;
use tower_lsp::lsp_types::InitializedParams;
use tower_lsp::lsp_types::InlayHint;
use tower_lsp::lsp_types::InlayHintParams;
use tower_lsp::lsp_types::InsertTextFormat;
use tower_lsp::lsp_types::MarkupContent;
use tower_lsp::lsp_types::MarkupKind;
use tower_lsp::lsp_types::MessageType;
use tower_lsp::lsp_types::OneOf;
use tower_lsp::lsp_types::Position;
use tower_lsp::lsp_types::PrepareRenameResponse;
use tower_lsp::lsp_types::RelatedFullDocumentDiagnosticReport;
use tower_lsp::lsp_types::RenameFilesParams;
use tower_lsp::lsp_types::RenameParams;
use tower_lsp::lsp_types::SemanticToken;
use tower_lsp::lsp_types::SemanticTokenModifier;
use tower_lsp::lsp_types::SemanticTokenType;
use tower_lsp::lsp_types::SemanticTokens;
use tower_lsp::lsp_types::SemanticTokensFullOptions;
use tower_lsp::lsp_types::SemanticTokensLegend;
use tower_lsp::lsp_types::SemanticTokensOptions;
use tower_lsp::lsp_types::SemanticTokensParams;
use tower_lsp::lsp_types::SemanticTokensRegistrationOptions;
use tower_lsp::lsp_types::SemanticTokensResult;
use tower_lsp::lsp_types::SemanticTokensServerCapabilities;
use tower_lsp::lsp_types::ServerCapabilities;
use tower_lsp::lsp_types::SignatureHelp;
use tower_lsp::lsp_types::SignatureHelpOptions;
use tower_lsp::lsp_types::SignatureHelpParams;
use tower_lsp::lsp_types::StaticRegistrationOptions;
use tower_lsp::lsp_types::TextDocumentItem;
use tower_lsp::lsp_types::TextDocumentPositionParams;
use tower_lsp::lsp_types::TextDocumentRegistrationOptions;
use tower_lsp::lsp_types::TextDocumentSyncCapability;
use tower_lsp::lsp_types::TextDocumentSyncKind;
use tower_lsp::lsp_types::TextDocumentSyncOptions;
use tower_lsp::lsp_types::TextEdit;
use tower_lsp::lsp_types::WorkDoneProgressOptions;
use tower_lsp::lsp_types::WorkspaceEdit;
use tower_lsp::lsp_types::WorkspaceFolder;
use tower_lsp::lsp_types::WorkspaceFoldersServerCapabilities;
use tower_lsp::lsp_types::WorkspaceServerCapabilities;

use crate::ModuleId;
use crate::Program;
use crate::SourceRange;
use crate::docs::kcl_doc::ArgData;
use crate::docs::kcl_doc::ModData;
use crate::exec::KclValue;
use crate::execution::cache;
use crate::lsp::LspSuggestion;
use crate::lsp::ToLspRange;
use crate::lsp::backend::Backend as _;
use crate::lsp::kcl::hover::Hover;
use crate::lsp::kcl::hover::HoverOpts;
use crate::lsp::util::IntoDiagnostic;
use crate::parsing::PIPE_OPERATOR;
use crate::parsing::ast::types::Expr;
use crate::parsing::ast::types::VariableKind;
use crate::parsing::token::RESERVED_WORDS;
use crate::parsing::token::TokenStream;

pub mod custom_notifications;
mod hover;

const SEMANTIC_TOKEN_TYPES: [SemanticTokenType; 10] = [
    SemanticTokenType::NUMBER,
    SemanticTokenType::VARIABLE,
    SemanticTokenType::KEYWORD,
    SemanticTokenType::TYPE,
    SemanticTokenType::STRING,
    SemanticTokenType::OPERATOR,
    SemanticTokenType::COMMENT,
    SemanticTokenType::FUNCTION,
    SemanticTokenType::PARAMETER,
    SemanticTokenType::PROPERTY,
];

const SEMANTIC_TOKEN_MODIFIERS: [SemanticTokenModifier; 5] = [
    SemanticTokenModifier::DECLARATION,
    SemanticTokenModifier::DEFINITION,
    SemanticTokenModifier::DEFAULT_LIBRARY,
    SemanticTokenModifier::READONLY,
    SemanticTokenModifier::STATIC,
];

/// A subcommand for running the server.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "cli", derive(Parser))]
pub struct Server {
    /// Port that the server should listen
    #[cfg_attr(feature = "cli", clap(long, default_value = "8080"))]
    pub socket: i32,

    /// Listen over stdin and stdout instead of a tcp socket.
    #[cfg_attr(feature = "cli", clap(short, long, default_value = "false"))]
    pub stdio: bool,
}

/// The lsp server backend.
#[derive(Clone)]
pub struct Backend {
    /// The client for the backend.
    pub client: Client,
    /// The file system client to use.
    pub fs: Arc<crate::fs::FileManager>,
    /// The workspace folders.
    pub workspace_folders: DashMap<String, WorkspaceFolder>,
    /// The stdlib completions for the language.
    pub stdlib_completions: HashMap<String, CompletionItem>,
    /// The stdlib completions inside a sketch block, where `solver::*`
    /// shadows the regular sketch stdlib.
    pub sketch_block_stdlib_completions: HashMap<String, CompletionItem>,
    /// The stdlib signatures for the language.
    pub stdlib_signatures: HashMap<String, SignatureHelp>,
    /// The stdlib signatures inside a sketch block.
    pub sketch_block_stdlib_signatures: HashMap<String, SignatureHelp>,
    /// For all KwArg functions in std, a map from their arg names to arg help snippets (markdown format).
    pub stdlib_args: HashMap<String, HashMap<String, LspArgData>>,
    /// KwArg docs inside a sketch block.
    pub sketch_block_stdlib_args: HashMap<String, HashMap<String, LspArgData>>,
    /// KCL keywords
    pub kcl_keywords: HashMap<String, CompletionItem>,
    /// Token maps.
    pub(super) token_map: DashMap<String, TokenStream>,
    /// AST maps.
    pub ast_map: DashMap<String, crate::Program>,
    /// Current code.
    pub code_map: DashMap<String, Vec<u8>>,
    /// Diagnostics.
    pub diagnostics_map: DashMap<String, Vec<Diagnostic>>,
    /// Symbols map.
    pub symbols_map: DashMap<String, Vec<DocumentSymbol>>,
    /// Semantic tokens map.
    pub semantic_tokens_map: DashMap<String, Vec<SemanticToken>>,
    /// The Zoo API client.
    pub zoo_client: kittycad::Client,
    /// Optional executor context to use if we want to execute the code.
    pub executor_ctx: Arc<RwLock<Option<crate::execution::ExecutorContext>>>,
    /// If we are currently allowed to execute the ast.
    pub can_execute: Arc<RwLock<bool>>,

    pub is_initialized: Arc<RwLock<bool>>,
}

impl Backend {
    #[cfg(target_arch = "wasm32")]
    pub fn new_wasm(
        client: Client,
        executor_ctx: Option<crate::execution::ExecutorContext>,
        fs: crate::fs::wasm::FileSystemManager,
        zoo_client: kittycad::Client,
    ) -> Result<Self, String> {
        Self::with_file_manager(client, executor_ctx, crate::fs::FileManager::new(fs), zoo_client)
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub fn new(
        client: Client,
        executor_ctx: Option<crate::execution::ExecutorContext>,
        zoo_client: kittycad::Client,
    ) -> Result<Self, String> {
        Self::with_file_manager(client, executor_ctx, crate::fs::FileManager::new(), zoo_client)
    }

    fn with_file_manager(
        client: Client,
        executor_ctx: Option<crate::execution::ExecutorContext>,
        fs: crate::fs::FileManager,
        zoo_client: kittycad::Client,
    ) -> Result<Self, String> {
        let kcl_std = crate::docs::kcl_doc::walk_prelude();
        let stdlib_completions = get_completions_from_stdlib(&kcl_std).map_err(|e| e.to_string())?;
        let sketch_block_stdlib_completions =
            get_completions_from_stdlib_for_sketch_block(&kcl_std).map_err(|e| e.to_string())?;
        let stdlib_signatures = get_signatures_from_stdlib(&kcl_std);
        let sketch_block_stdlib_signatures = get_signatures_from_stdlib_for_sketch_block(&kcl_std);
        let stdlib_args = get_arg_maps_from_stdlib(&kcl_std);
        let sketch_block_stdlib_args = get_arg_maps_from_stdlib_for_sketch_block(&kcl_std);
        let kcl_keywords = get_keywords();

        Ok(Self {
            client,
            fs: Arc::new(fs),
            stdlib_completions,
            sketch_block_stdlib_completions,
            stdlib_signatures,
            sketch_block_stdlib_signatures,
            stdlib_args,
            sketch_block_stdlib_args,
            kcl_keywords,
            zoo_client,
            can_execute: Arc::new(RwLock::new(executor_ctx.is_some())),
            executor_ctx: Arc::new(RwLock::new(executor_ctx)),
            workspace_folders: Default::default(),
            token_map: Default::default(),
            ast_map: Default::default(),
            code_map: Default::default(),
            diagnostics_map: Default::default(),
            symbols_map: Default::default(),
            semantic_tokens_map: Default::default(),
            is_initialized: Default::default(),
        })
    }

    fn is_in_sketch_block(ast: &crate::Program, position: usize) -> bool {
        let in_sketch_block = Cell::new(false);
        let _ = crate::walk::walk(&ast.ast, |node| {
            if let crate::walk::Node::SketchBlock(sketch_block) = node
                && SourceRange::from(&sketch_block.body).contains(position)
            {
                in_sketch_block.set(true);
                return Ok::<bool, anyhow::Error>(false);
            }

            Ok::<bool, anyhow::Error>(true)
        });

        in_sketch_block.get()
    }

    fn stdlib_completions_for_position<'a>(
        &'a self,
        ast: &crate::Program,
        position: usize,
    ) -> &'a HashMap<String, CompletionItem> {
        if Self::is_in_sketch_block(ast, position) {
            &self.sketch_block_stdlib_completions
        } else {
            &self.stdlib_completions
        }
    }

    fn stdlib_signatures_for_position<'a>(
        &'a self,
        ast: &crate::Program,
        position: usize,
    ) -> &'a HashMap<String, SignatureHelp> {
        if Self::is_in_sketch_block(ast, position) {
            &self.sketch_block_stdlib_signatures
        } else {
            &self.stdlib_signatures
        }
    }

    fn stdlib_args_for_position<'a>(
        &'a self,
        ast: &crate::Program,
        position: usize,
    ) -> &'a HashMap<String, HashMap<String, LspArgData>> {
        if Self::is_in_sketch_block(ast, position) {
            &self.sketch_block_stdlib_args
        } else {
            &self.stdlib_args
        }
    }

    fn remove_from_ast_maps(&self, filename: &str) {
        self.ast_map.remove(filename);
        self.symbols_map.remove(filename);
    }

    fn try_arg_completions(
        &self,
        program: &crate::Program,
        position: usize,
        current_code: &str,
    ) -> Option<impl Iterator<Item = CompletionItem>> {
        let curr_expr = program.ast.get_expr_for_position(position)?;
        let hover =
            curr_expr.get_hover_value_for_position(position, current_code, &HoverOpts::default_for_signature_help())?;

        // Now we can tell if the user's cursor is inside a callable function.
        // If so, get its name (the function name being called.)
        let maybe_callee = match hover {
            Hover::Function { name, range: _ } => Some(name),
            Hover::Signature {
                name,
                parameter_index: _,
                range: _,
            } => Some(name),
            Hover::Comment { .. } => None,
            Hover::Variable { .. } => None,
            Hover::KwArg {
                callee_name,
                name: _,
                range: _,
            } => Some(callee_name),
            Hover::Type { .. } => None,
        };
        let stdlib_args = self.stdlib_args_for_position(program, position);
        let callee_args = maybe_callee.and_then(|fn_name| stdlib_args.get(&fn_name))?;

        let arg_label_completions = callee_args
            .iter()
            // Don't suggest labels for unlabelled args!
            .filter(|(_arg_name, arg_data)| arg_data.props.is_labelled())
            .map(|(arg_name, arg_data)| CompletionItem {
                label: arg_name.to_owned(),
                label_details: None,
                kind: Some(CompletionItemKind::PROPERTY),
                detail: arg_data.props.ty.clone(),
                documentation: arg_data.props.docs.clone().map(|docs| {
                    Documentation::MarkupContent(MarkupContent {
                        kind: MarkupKind::Markdown,
                        value: docs,
                    })
                }),
                deprecated: None,
                preselect: None,
                sort_text: Some(arg_name.to_owned()),
                filter_text: Some(arg_name.to_owned()),
                insert_text: {
                    // let snippet = "${0:x}";
                    if let Some(snippet) = arg_data.props.get_autocomplete_snippet(0).map(|(_i, snippet)| snippet) {
                        Some(snippet)
                    } else {
                        Some(format!("{arg_name} = "))
                    }
                },
                insert_text_format: Some(InsertTextFormat::SNIPPET),
                insert_text_mode: None,
                text_edit: None,
                additional_text_edits: None,
                command: None,
                commit_characters: None,
                data: None,
                tags: None,
            });
        Some(arg_label_completions)
    }
}

// Implement the shared backend trait for the language server.
#[async_trait::async_trait]
impl crate::lsp::backend::Backend for Backend {
    fn client(&self) -> &Client {
        &self.client
    }

    fn fs(&self) -> &Arc<crate::fs::FileManager> {
        &self.fs
    }

    async fn is_initialized(&self) -> bool {
        *self.is_initialized.read().await
    }

    async fn set_is_initialized(&self, is_initialized: bool) {
        *self.is_initialized.write().await = is_initialized;
    }

    async fn workspace_folders(&self) -> Vec<WorkspaceFolder> {
        // TODO: fix clone
        self.workspace_folders.iter().map(|i| i.clone()).collect()
    }

    async fn add_workspace_folders(&self, folders: Vec<WorkspaceFolder>) {
        for folder in folders {
            self.workspace_folders.insert(folder.name.to_string(), folder);
        }
    }

    async fn remove_workspace_folders(&self, folders: Vec<WorkspaceFolder>) {
        for folder in folders {
            self.workspace_folders.remove(&folder.name);
        }
    }

    fn code_map(&self) -> &DashMap<String, Vec<u8>> {
        &self.code_map
    }

    async fn insert_code_map(&self, uri: String, text: Vec<u8>) {
        self.code_map.insert(uri, text);
    }

    async fn remove_from_code_map(&self, uri: String) -> Option<Vec<u8>> {
        self.code_map.remove(&uri).map(|x| x.1)
    }

    async fn clear_code_state(&self) {
        self.code_map.clear();
        self.token_map.clear();
        self.ast_map.clear();
        self.diagnostics_map.clear();
        self.symbols_map.clear();
        self.semantic_tokens_map.clear();
    }

    fn current_diagnostics_map(&self) -> &DashMap<String, Vec<Diagnostic>> {
        &self.diagnostics_map
    }

    async fn inner_on_change(&self, params: TextDocumentItem, force: bool) {
        if force {
            crate::bust_cache().await;
        }

        let filename = params.uri.to_string();
        // We already updated the code map in the shared backend.

        // Lets update the tokens.
        let module_id = ModuleId::default();
        let tokens = match crate::parsing::token::lex(&params.text, module_id) {
            Ok(tokens) => tokens,
            Err(err) => {
                self.add_to_diagnostics(&params, &[err], true).await;
                self.token_map.remove(&filename);
                self.remove_from_ast_maps(&filename);
                self.semantic_tokens_map.remove(&filename);
                return;
            }
        };

        // Get the previous tokens.
        let tokens_changed = match self.token_map.get(&filename) {
            Some(previous_tokens) => *previous_tokens != tokens,
            _ => true,
        };

        let had_diagnostics = self.has_diagnostics(params.uri.as_ref()).await;

        // Check if the tokens are the same.
        if !tokens_changed && !force && !had_diagnostics {
            // We return early here because the tokens are the same.
            return;
        }

        if tokens_changed {
            // Update our token map.
            self.token_map.insert(params.uri.to_string(), tokens.clone());
            // Update our semantic tokens.
            self.update_semantic_tokens(&tokens, &params).await;
        }

        // Lets update the ast.

        let (ast, errs) = match crate::parsing::parse_tokens(tokens.clone()).0 {
            Ok(result) => result,
            Err(err) => {
                self.add_to_diagnostics(&params, &[err], true).await;
                self.remove_from_ast_maps(&filename);
                return;
            }
        };

        self.add_to_diagnostics(&params, &errs, true).await;

        if errs.iter().any(|e| e.severity == crate::errors::Severity::Fatal) {
            self.remove_from_ast_maps(&filename);
            return;
        }

        let Some(mut ast) = ast else {
            self.remove_from_ast_maps(&filename);
            return;
        };

        // Here we will want to store the digest and compare, but for now
        // we're doing this in a non-load-bearing capacity so we can remove
        // this if it backfires and only hork the LSP.
        ast.compute_digest();

        // Save it as a program.
        let ast = crate::Program {
            ast,
            original_file_contents: params.text.clone(),
        };

        // Check if the ast changed.
        let ast_changed = match self.ast_map.get(&filename) {
            Some(old_ast) => {
                // Check if the ast changed.
                *old_ast.ast != *ast.ast
            }
            None => true,
        };

        if !ast_changed && !force && !had_diagnostics {
            // Return early if the ast did not change and we don't need to force.
            return;
        }

        if ast_changed {
            self.ast_map.insert(params.uri.to_string(), ast.clone());
            // Update the symbols map.
            self.symbols_map.insert(
                params.uri.to_string(),
                ast.ast.get_lsp_symbols(&params.text).unwrap_or_default(),
            );

            // Update our semantic tokens.
            self.update_semantic_tokens(&tokens, &params).await;

            let mut discovered_findings: Vec<_> = ast.lint_all().into_iter().flatten().collect();
            // Filter out Z0005 (old sketch syntax) from LSP diagnostics
            // TODO: Remove this filter once the transpiler is complete and all tests are updated
            discovered_findings.retain(|finding| finding.finding.code != "Z0005");
            self.add_to_diagnostics(&params, &discovered_findings, false).await;
        }

        // Send the notification to the client that the ast was updated.
        if self.can_execute().await || self.executor_ctx().await.is_none() {
            // Only send the notification if we can execute.
            // Otherwise it confuses the client.
            self.client
                .send_notification::<custom_notifications::AstUpdated>(ast.ast.clone())
                .await;
        }

        // Execute the code if we have an executor context.
        // This function automatically executes if we should & updates the diagnostics if we got
        // errors.
        if self.execute(&params, &ast).await.is_err() {
            return;
        }

        // If we made it here we can clear the diagnostics.
        self.clear_diagnostics_map(&params.uri, Some(DiagnosticSeverity::ERROR))
            .await;
    }
}

impl Backend {
    pub async fn can_execute(&self) -> bool {
        *self.can_execute.read().await
    }

    pub async fn executor_ctx(&self) -> tokio::sync::RwLockReadGuard<'_, Option<crate::execution::ExecutorContext>> {
        self.executor_ctx.read().await
    }

    async fn update_semantic_tokens(&self, tokens: &TokenStream, params: &TextDocumentItem) {
        // Update the semantic tokens map.
        let mut semantic_tokens = vec![];
        let mut last_position = Position::new(0, 0);
        for token in tokens.as_slice() {
            let Ok(token_type) = SemanticTokenType::try_from(token.token_type) else {
                // We continue here because not all tokens can be converted this way, we will get
                // the rest from the ast.
                continue;
            };

            let mut token_type_index = match self.get_semantic_token_type_index(&token_type) {
                Some(index) => index,
                // This is actually bad this should not fail.
                // The test for listing all semantic token types should make this never happen.
                None => {
                    self.client
                        .log_message(
                            MessageType::ERROR,
                            format!("token type `{token_type:?}` not accounted for"),
                        )
                        .await;
                    continue;
                }
            };

            let source_range: SourceRange = token.into();
            let position = source_range.start_to_lsp_position(&params.text);

            // Calculate the token modifiers.
            // Get the value at the current position.
            let token_modifiers_bitset = match self.ast_map.get(params.uri.as_str()) {
                Some(ast) => {
                    let token_index = Arc::new(Mutex::new(token_type_index));
                    let modifier_index: Arc<Mutex<u32>> = Arc::new(Mutex::new(0));
                    crate::walk::walk(&ast.ast, |node: crate::walk::Node| {
                        let Ok(node_range): Result<SourceRange, _> = (&node).try_into() else {
                            return Ok(true);
                        };

                        if !node_range.contains(source_range.start()) {
                            return Ok(true);
                        }

                        let get_modifier = |modifier: Vec<SemanticTokenModifier>| -> Result<bool> {
                            let mut mods = modifier_index.lock().map_err(|_| anyhow::anyhow!("mutex"))?;
                            let Some(token_modifier_index) = self.get_semantic_token_modifier_index(modifier) else {
                                return Ok(true);
                            };
                            if *mods == 0 {
                                *mods = token_modifier_index;
                            } else {
                                *mods |= token_modifier_index;
                            }
                            Ok(false)
                        };

                        match node {
                            crate::walk::Node::TagDeclarator(_) => {
                                return get_modifier(vec![
                                    SemanticTokenModifier::DEFINITION,
                                    SemanticTokenModifier::STATIC,
                                ]);
                            }
                            crate::walk::Node::VariableDeclarator(variable) => {
                                let sr: SourceRange = (&variable.id).into();
                                if sr.contains(source_range.start()) {
                                    if let Expr::FunctionExpression(_) = &variable.init {
                                        let mut ti = token_index.lock().map_err(|_| anyhow::anyhow!("mutex"))?;
                                        *ti = match self.get_semantic_token_type_index(&SemanticTokenType::FUNCTION) {
                                            Some(index) => index,
                                            None => token_type_index,
                                        };
                                    }

                                    return get_modifier(vec![
                                        SemanticTokenModifier::DECLARATION,
                                        SemanticTokenModifier::READONLY,
                                    ]);
                                }
                            }
                            crate::walk::Node::Parameter(_) => {
                                let mut ti = token_index.lock().map_err(|_| anyhow::anyhow!("mutex"))?;
                                *ti = match self.get_semantic_token_type_index(&SemanticTokenType::PARAMETER) {
                                    Some(index) => index,
                                    None => token_type_index,
                                };
                                return Ok(false);
                            }
                            crate::walk::Node::MemberExpression(member_expression) => {
                                let sr: SourceRange = (&member_expression.property).into();
                                if sr.contains(source_range.start()) {
                                    let mut ti = token_index.lock().map_err(|_| anyhow::anyhow!("mutex"))?;
                                    *ti = match self.get_semantic_token_type_index(&SemanticTokenType::PROPERTY) {
                                        Some(index) => index,
                                        None => token_type_index,
                                    };
                                    return Ok(false);
                                }
                            }
                            crate::walk::Node::ObjectProperty(object_property) => {
                                let sr: SourceRange = (&object_property.key).into();
                                if sr.contains(source_range.start()) {
                                    let mut ti = token_index.lock().map_err(|_| anyhow::anyhow!("mutex"))?;
                                    *ti = match self.get_semantic_token_type_index(&SemanticTokenType::PROPERTY) {
                                        Some(index) => index,
                                        None => token_type_index,
                                    };
                                }
                                return get_modifier(vec![SemanticTokenModifier::DECLARATION]);
                            }
                            crate::walk::Node::CallExpressionKw(call_expr) => {
                                let sr: SourceRange = (&call_expr.callee).into();
                                if sr.contains(source_range.start()) {
                                    let mut ti = token_index.lock().map_err(|_| anyhow::anyhow!("mutex"))?;
                                    *ti = match self.get_semantic_token_type_index(&SemanticTokenType::FUNCTION) {
                                        Some(index) => index,
                                        None => token_type_index,
                                    };

                                    if self.stdlib_completions.contains_key(&call_expr.callee.name.name) {
                                        // This is a stdlib function.
                                        return get_modifier(vec![SemanticTokenModifier::DEFAULT_LIBRARY]);
                                    }

                                    return Ok(false);
                                }
                            }
                            _ => {}
                        }
                        Ok(true)
                    })
                    .unwrap_or_default();

                    let t = match token_index.lock() {
                        Ok(guard) => *guard,
                        _ => 0,
                    };
                    token_type_index = t;

                    match modifier_index.lock() {
                        Ok(guard) => *guard,
                        _ => 0,
                    }
                }
                _ => 0,
            };

            // We need to check if we are on the last token of the line.
            // If we are starting from the end of the last line just add 1 to the line.
            // Check if we are on the last token of the line.
            if let Some(line) = params.text.lines().nth(position.line as usize)
                && line.len() == position.character as usize
            {
                // We are on the last token of the line.
                // We need to add a new line.
                let semantic_token = SemanticToken {
                    delta_line: position.line - last_position.line + 1,
                    delta_start: 0,
                    length: (token.end - token.start) as u32,
                    token_type: token_type_index,
                    token_modifiers_bitset,
                };

                semantic_tokens.push(semantic_token);

                last_position = Position::new(position.line + 1, 0);
                continue;
            }

            let semantic_token = SemanticToken {
                delta_line: position.line - last_position.line,
                delta_start: if position.line != last_position.line {
                    position.character
                } else {
                    position.character - last_position.character
                },
                length: (token.end - token.start) as u32,
                token_type: token_type_index,
                token_modifiers_bitset,
            };

            semantic_tokens.push(semantic_token);

            last_position = position;
        }
        self.semantic_tokens_map.insert(params.uri.to_string(), semantic_tokens);
    }

    async fn clear_diagnostics_map(&self, uri: &url::Url, severity: Option<DiagnosticSeverity>) {
        let Some(mut items) = self.diagnostics_map.get_mut(uri.as_str()) else {
            return;
        };

        // If we only want to clear a specific severity, do that.
        if let Some(severity) = severity {
            items.retain(|x| x.severity != Some(severity));
        } else {
            items.clear();
        }

        if items.is_empty() {
            #[cfg(not(target_arch = "wasm32"))]
            {
                self.client.publish_diagnostics(uri.clone(), items.clone(), None).await;
            }

            // We need to drop the items here.
            drop(items);

            self.diagnostics_map.remove(uri.as_str());
        } else {
            // We don't need to update the map since we used get_mut.

            #[cfg(not(target_arch = "wasm32"))]
            {
                self.client.publish_diagnostics(uri.clone(), items.clone(), None).await;
            }
        }
    }

    async fn add_to_diagnostics<DiagT: IntoDiagnostic + std::fmt::Debug>(
        &self,
        params: &TextDocumentItem,
        diagnostics: &[DiagT],
        clear_all_before_add: bool,
    ) {
        if diagnostics.is_empty() {
            return;
        }

        if clear_all_before_add {
            self.clear_diagnostics_map(&params.uri, None).await;
        } else if diagnostics.iter().all(|x| x.severity() == DiagnosticSeverity::ERROR) {
            // If the diagnostic is an error, it will be the only error we get since that halts
            // execution.
            // Clear the diagnostics before we add a new one.
            self.clear_diagnostics_map(&params.uri, Some(DiagnosticSeverity::ERROR))
                .await;
        } else if diagnostics
            .iter()
            .all(|x| x.severity() == DiagnosticSeverity::INFORMATION)
        {
            // If the diagnostic is a lint, we will pass them all to add at once so we need to
            // clear the old ones.
            self.clear_diagnostics_map(&params.uri, Some(DiagnosticSeverity::INFORMATION))
                .await;
        }

        let mut items = match self.diagnostics_map.get(params.uri.as_str()) {
            Some(items) => {
                // TODO: Would be awesome to fix the clone here.
                items.clone()
            }
            _ => {
                vec![]
            }
        };

        for diagnostic in diagnostics {
            let lsp_d = diagnostic.to_lsp_diagnostics(&params.text);
            // Make sure we don't duplicate diagnostics.
            for d in lsp_d {
                if !items.iter().any(|x| x == &d) {
                    items.push(d);
                }
            }
        }

        self.diagnostics_map.insert(params.uri.to_string(), items.clone());

        self.client.publish_diagnostics(params.uri.clone(), items, None).await;
    }

    async fn execute(&self, params: &TextDocumentItem, ast: &Program) -> Result<()> {
        // Check if we can execute.
        if !self.can_execute().await {
            return Ok(());
        }

        // Execute the code if we have an executor context.
        let ctx = self.executor_ctx().await;
        let Some(ref executor_ctx) = *ctx else {
            return Ok(());
        };

        if !self.is_initialized().await {
            // We are not initialized yet.
            return Ok(());
        }

        // Use run_mock for mock contexts, run_with_caching for live contexts
        let result = if executor_ctx.is_mock() {
            executor_ctx
                .run_mock(ast, &crate::execution::MockConfig::default())
                .await
        } else {
            executor_ctx.run_with_caching(ast.clone()).await
        };

        match result {
            Err(err) => {
                self.add_to_diagnostics(params, &[err], false).await;

                // Since we already published the diagnostics we don't really care about the error
                // string.
                Err(anyhow::anyhow!("failed to execute code"))
            }
            Ok(_) => Ok(()),
        }
    }

    pub fn get_semantic_token_type_index(&self, token_type: &SemanticTokenType) -> Option<u32> {
        SEMANTIC_TOKEN_TYPES
            .iter()
            .position(|x| *x == *token_type)
            .map(|y| y as u32)
    }

    pub fn get_semantic_token_modifier_index(&self, token_types: Vec<SemanticTokenModifier>) -> Option<u32> {
        if token_types.is_empty() {
            return None;
        }

        let mut modifier = None;
        for token_type in token_types {
            if let Some(index) = SEMANTIC_TOKEN_MODIFIERS
                .iter()
                .position(|x| *x == token_type)
                .map(|y| y as u32)
            {
                modifier = match modifier {
                    Some(modifier) => Some(modifier | index),
                    None => Some(index),
                };
            }
        }
        modifier
    }

    pub async fn update_can_execute(
        &self,
        params: custom_notifications::UpdateCanExecuteParams,
    ) -> RpcResult<custom_notifications::UpdateCanExecuteResponse> {
        let mut can_execute = self.can_execute.write().await;

        if *can_execute == params.can_execute {
            return Ok(custom_notifications::UpdateCanExecuteResponse {});
        }

        *can_execute = params.can_execute;

        Ok(custom_notifications::UpdateCanExecuteResponse {})
    }

    /// Returns the new string for the code after rename.
    pub fn inner_prepare_rename(
        &self,
        params: &TextDocumentPositionParams,
        new_name: &str,
    ) -> RpcResult<Option<(String, String)>> {
        let filename = params.text_document.uri.to_string();

        let Some(current_code) = self.code_map.get(&filename) else {
            return Ok(None);
        };
        let Ok(current_code) = std::str::from_utf8(&current_code) else {
            return Ok(None);
        };

        // Parse the ast.
        // I don't know if we need to do this again since it should be updated in the context.
        // But I figure better safe than sorry since this will write back out to the file.
        let module_id = ModuleId::default();
        let Ok(mut ast) = crate::parsing::parse_str(current_code, module_id).parse_errs_as_err() else {
            return Ok(None);
        };

        // Let's convert the position to a character index.
        let pos = position_to_char_index(params.position, current_code);
        // Now let's perform the rename on the ast.
        ast.rename_symbol(new_name, pos);
        // Now recast it.
        let recast = ast.recast_top(&Default::default(), 0);

        Ok(Some((current_code.to_string(), recast)))
    }
}

#[tower_lsp::async_trait]
impl LanguageServer for Backend {
    async fn initialize(&self, params: InitializeParams) -> RpcResult<InitializeResult> {
        self.client
            .log_message(MessageType::INFO, format!("initialize: {params:?}"))
            .await;

        Ok(InitializeResult {
            capabilities: ServerCapabilities {
                color_provider: Some(ColorProviderCapability::Simple(true)),
                code_action_provider: Some(CodeActionProviderCapability::Options(CodeActionOptions {
                    code_action_kinds: Some(vec![CodeActionKind::QUICKFIX]),
                    resolve_provider: Some(false),
                    work_done_progress_options: WorkDoneProgressOptions::default(),
                })),
                completion_provider: Some(CompletionOptions {
                    resolve_provider: Some(false),
                    trigger_characters: Some(vec![".".to_string()]),
                    work_done_progress_options: Default::default(),
                    all_commit_characters: None,
                    ..Default::default()
                }),
                diagnostic_provider: Some(DiagnosticServerCapabilities::Options(DiagnosticOptions {
                    ..Default::default()
                })),
                document_formatting_provider: Some(OneOf::Left(true)),
                folding_range_provider: Some(FoldingRangeProviderCapability::Simple(true)),
                hover_provider: Some(HoverProviderCapability::Simple(true)),
                inlay_hint_provider: Some(OneOf::Left(true)),
                rename_provider: Some(OneOf::Left(true)),
                semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensRegistrationOptions(
                    SemanticTokensRegistrationOptions {
                        text_document_registration_options: {
                            TextDocumentRegistrationOptions {
                                document_selector: Some(vec![DocumentFilter {
                                    language: Some("kcl".to_string()),
                                    scheme: Some("file".to_string()),
                                    pattern: None,
                                }]),
                            }
                        },
                        semantic_tokens_options: SemanticTokensOptions {
                            work_done_progress_options: WorkDoneProgressOptions::default(),
                            legend: SemanticTokensLegend {
                                token_types: SEMANTIC_TOKEN_TYPES.to_vec(),
                                token_modifiers: SEMANTIC_TOKEN_MODIFIERS.to_vec(),
                            },
                            range: Some(false),
                            full: Some(SemanticTokensFullOptions::Bool(true)),
                        },
                        static_registration_options: StaticRegistrationOptions::default(),
                    },
                )),
                signature_help_provider: Some(SignatureHelpOptions {
                    trigger_characters: None,
                    retrigger_characters: None,
                    ..Default::default()
                }),
                text_document_sync: Some(TextDocumentSyncCapability::Options(TextDocumentSyncOptions {
                    open_close: Some(true),
                    change: Some(TextDocumentSyncKind::FULL),
                    ..Default::default()
                })),
                workspace: Some(WorkspaceServerCapabilities {
                    workspace_folders: Some(WorkspaceFoldersServerCapabilities {
                        supported: Some(true),
                        change_notifications: Some(OneOf::Left(true)),
                    }),
                    file_operations: None,
                }),
                ..Default::default()
            },
            ..Default::default()
        })
    }

    async fn initialized(&self, params: InitializedParams) {
        self.do_initialized(params).await
    }

    async fn shutdown(&self) -> RpcResult<()> {
        self.do_shutdown().await
    }

    async fn did_change_workspace_folders(&self, params: DidChangeWorkspaceFoldersParams) {
        self.do_did_change_workspace_folders(params).await
    }

    async fn did_change_configuration(&self, params: DidChangeConfigurationParams) {
        self.do_did_change_configuration(params).await
    }

    async fn did_change_watched_files(&self, params: DidChangeWatchedFilesParams) {
        self.do_did_change_watched_files(params).await
    }

    async fn did_create_files(&self, params: CreateFilesParams) {
        self.do_did_create_files(params).await
    }

    async fn did_rename_files(&self, params: RenameFilesParams) {
        self.do_did_rename_files(params).await
    }

    async fn did_delete_files(&self, params: DeleteFilesParams) {
        self.do_did_delete_files(params).await
    }

    async fn did_open(&self, params: DidOpenTextDocumentParams) {
        self.do_did_open(params).await
    }

    async fn did_change(&self, params: DidChangeTextDocumentParams) {
        self.do_did_change(params).await;
    }

    async fn did_save(&self, params: DidSaveTextDocumentParams) {
        self.do_did_save(params).await
    }

    async fn did_close(&self, params: DidCloseTextDocumentParams) {
        self.do_did_close(params).await;
    }

    async fn hover(&self, params: HoverParams) -> RpcResult<Option<LspHover>> {
        let filename = params.text_document_position_params.text_document.uri.to_string();

        let Some(current_code) = self.code_map.get(&filename) else {
            return Ok(None);
        };
        let Ok(current_code) = std::str::from_utf8(&current_code) else {
            return Ok(None);
        };

        let pos = position_to_char_index(params.text_document_position_params.position, current_code);

        // Let's iterate over the AST and find the node that contains the cursor.
        let Some(ast) = self.ast_map.get(&filename) else {
            return Ok(None);
        };

        let Some(hover) = ast
            .ast
            .get_hover_value_for_position(pos, current_code, &HoverOpts::default_for_hover())
        else {
            return Ok(None);
        };
        let stdlib_completions = self.stdlib_completions_for_position(&ast, pos);
        let stdlib_args = self.stdlib_args_for_position(&ast, pos);

        match hover {
            Hover::Function { name, range } => {
                let (sig, docs) = if let Some(Some(result)) = with_cached_var(&name, |value| {
                    match value {
                        // User-defined function
                        KclValue::Function { value, .. } if !value.is_std() => {
                            // TODO get docs from comments
                            Some((value.ast.signature(), ""))
                        }
                        _ => None,
                    }
                })
                .await
                {
                    result
                } else {
                    // Get the docs for this function.
                    let Some(completion) = stdlib_completions.get(&name) else {
                        return Ok(None);
                    };
                    let Some(docs) = &completion.documentation else {
                        return Ok(None);
                    };

                    let docs = match docs {
                        Documentation::String(docs) => docs,
                        Documentation::MarkupContent(MarkupContent { value, .. }) => value,
                    };

                    let docs = if docs.len() > 320 {
                        let end = docs.find("\n\n").or_else(|| docs.find("\n\r\n")).unwrap_or(320);
                        &docs[..end]
                    } else {
                        &**docs
                    };

                    let Some(label_details) = &completion.label_details else {
                        return Ok(None);
                    };

                    let sig = if let Some(detail) = &label_details.detail {
                        detail.clone()
                    } else {
                        String::new()
                    };

                    (sig, docs)
                };

                Ok(Some(LspHover {
                    contents: HoverContents::Markup(MarkupContent {
                        kind: MarkupKind::Markdown,
                        value: format!("```\n{name}{sig}\n```\n\n{docs}"),
                    }),
                    range: Some(range),
                }))
            }
            Hover::Type { name, range } => {
                let Some(completion) = stdlib_completions.get(&name) else {
                    return Ok(None);
                };
                let Some(docs) = &completion.documentation else {
                    return Ok(None);
                };

                let docs = match docs {
                    Documentation::String(docs) => docs,
                    Documentation::MarkupContent(MarkupContent { value, .. }) => value,
                };

                let docs = if docs.len() > 320 {
                    let end = docs.find("\n\n").or_else(|| docs.find("\n\r\n")).unwrap_or(320);
                    &docs[..end]
                } else {
                    &**docs
                };

                Ok(Some(LspHover {
                    contents: HoverContents::Markup(MarkupContent {
                        kind: MarkupKind::Markdown,
                        value: format!("```\n{name}\n```\n\n{docs}"),
                    }),
                    range: Some(range),
                }))
            }
            Hover::KwArg {
                name,
                callee_name,
                range,
            } => {
                // TODO handle user-defined functions too

                let Some(arg_map) = stdlib_args.get(&callee_name) else {
                    return Ok(None);
                };

                let Some(arg_entry) = arg_map.get(&name) else {
                    return Ok(None);
                };

                Ok(Some(LspHover {
                    contents: HoverContents::Markup(MarkupContent {
                        kind: MarkupKind::Markdown,
                        value: arg_entry.tip.clone(),
                    }),
                    range: Some(range),
                }))
            }
            Hover::Variable {
                name,
                ty: Some(ty),
                range,
            } => Ok(Some(LspHover {
                contents: HoverContents::Markup(MarkupContent {
                    kind: MarkupKind::Markdown,
                    value: format!("```\n{name}: {ty}\n```"),
                }),
                range: Some(range),
            })),
            Hover::Variable { name, ty: None, range } => Ok(with_cached_var(&name, |value| {
                let mut text: String = format!("```\n{name}");
                if let Some(ty) = value.principal_type() {
                    text.push_str(&format!(": {}", ty.human_friendly_type()));
                }
                if let Some(v) = value.value_str() {
                    text.push_str(&format!(" = {v}"));
                }
                text.push_str("\n```");

                LspHover {
                    contents: HoverContents::Markup(MarkupContent {
                        kind: MarkupKind::Markdown,
                        value: text,
                    }),
                    range: Some(range),
                }
            })
            .await),
            Hover::Signature { .. } => Ok(None),
            Hover::Comment { value, range } => Ok(Some(LspHover {
                contents: HoverContents::Markup(MarkupContent {
                    kind: MarkupKind::Markdown,
                    value,
                }),
                range: Some(range),
            })),
        }
    }

    async fn completion(&self, params: CompletionParams) -> RpcResult<Option<CompletionResponse>> {
        let mut completions = vec![CompletionItem {
            label: PIPE_OPERATOR.to_string(),
            label_details: None,
            kind: Some(CompletionItemKind::OPERATOR),
            detail: Some("A pipe operator.".to_string()),
            documentation: Some(Documentation::MarkupContent(MarkupContent {
                kind: MarkupKind::Markdown,
                value: "A pipe operator.".to_string(),
            })),
            deprecated: Some(false),
            preselect: None,
            sort_text: None,
            filter_text: None,
            insert_text: Some("|> ".to_string()),
            insert_text_format: Some(InsertTextFormat::PLAIN_TEXT),
            insert_text_mode: None,
            text_edit: None,
            additional_text_edits: None,
            command: None,
            commit_characters: None,
            data: None,
            tags: None,
        }];

        // Get the current line up to cursor
        let Some(current_code) = self
            .code_map
            .get(params.text_document_position.text_document.uri.as_ref())
        else {
            return Ok(Some(CompletionResponse::Array(completions)));
        };
        let Ok(current_code) = std::str::from_utf8(&current_code) else {
            return Ok(Some(CompletionResponse::Array(completions)));
        };

        // Get the current line up to cursor, with bounds checking
        if let Some(line) = current_code
            .lines()
            .nth(params.text_document_position.position.line as usize)
        {
            let char_pos = params.text_document_position.position.character as usize;
            if char_pos <= line.len() {
                let line_prefix = &line[..char_pos];
                // Get last word
                let last_word = line_prefix
                    .split(|c: char| c.is_whitespace() || c.is_ascii_punctuation())
                    .next_back()
                    .unwrap_or("");

                // If the last word starts with a digit, return no completions
                if !last_word.is_empty() && last_word.chars().next().unwrap().is_ascii_digit() {
                    return Ok(None);
                }
            }
        }

        // Add more to the completions if we have more.
        let Some(ast) = self
            .ast_map
            .get(params.text_document_position.text_document.uri.as_ref())
        else {
            completions.extend(self.stdlib_completions.values().cloned());
            completions.extend(self.kcl_keywords.values().cloned());
            return Ok(Some(CompletionResponse::Array(completions)));
        };

        let position = position_to_char_index(params.text_document_position.position, current_code);
        if ast.ast.in_comment(position) {
            // If we are in a code comment we don't want to show completions.
            return Ok(None);
        }

        completions.extend(self.stdlib_completions_for_position(&ast, position).values().cloned());
        completions.extend(self.kcl_keywords.values().cloned());

        // If we're inside a CallExpression or something where a function parameter label could be completed,
        // then complete it.
        // Let's find the AST node that the user's cursor is in.
        if let Some(arg_label_completions) = self.try_arg_completions(&ast, position, current_code) {
            completions.extend(arg_label_completions);
        }

        // Get the completion items for the ast.
        let Ok(variables) = ast.ast.completion_items(position) else {
            return Ok(Some(CompletionResponse::Array(completions)));
        };

        // Get our variables from our AST to include in our completions.
        completions.extend(variables);

        Ok(Some(CompletionResponse::Array(completions)))
    }

    async fn diagnostic(&self, params: DocumentDiagnosticParams) -> RpcResult<DocumentDiagnosticReportResult> {
        let filename = params.text_document.uri.to_string();

        // Get the current diagnostics for this file.
        let Some(items) = self.diagnostics_map.get(&filename) else {
            // Send an empty report.
            return Ok(DocumentDiagnosticReportResult::Report(DocumentDiagnosticReport::Full(
                RelatedFullDocumentDiagnosticReport {
                    related_documents: None,
                    full_document_diagnostic_report: FullDocumentDiagnosticReport {
                        result_id: None,
                        items: vec![],
                    },
                },
            )));
        };

        Ok(DocumentDiagnosticReportResult::Report(DocumentDiagnosticReport::Full(
            RelatedFullDocumentDiagnosticReport {
                related_documents: None,
                full_document_diagnostic_report: FullDocumentDiagnosticReport {
                    result_id: None,
                    items: items.clone(),
                },
            },
        )))
    }

    async fn signature_help(&self, params: SignatureHelpParams) -> RpcResult<Option<SignatureHelp>> {
        let filename = params.text_document_position_params.text_document.uri.to_string();

        let Some(current_code) = self.code_map.get(&filename) else {
            return Ok(None);
        };
        let Ok(current_code) = std::str::from_utf8(&current_code) else {
            return Ok(None);
        };

        let pos = position_to_char_index(params.text_document_position_params.position, current_code);

        let ast = self.ast_map.get(&filename);
        let stdlib_signatures = ast
            .as_ref()
            .map(|ast| self.stdlib_signatures_for_position(ast, pos))
            .unwrap_or(&self.stdlib_signatures);

        // Get the character at the position.
        let Some(ch) = current_code.chars().nth(pos) else {
            return Ok(None);
        };

        let check_char = |ch: char| {
            // If  we are on a (, then get the string in front of the (
            // and try to get the signature.
            // We do these before the ast check because we might not have a valid ast.
            if ch == '(' {
                // If the current character is not a " " then get the next space after
                // our position so we can split on that.
                // Find the next space after the current position.
                let next_space = if ch != ' ' {
                    if let Some(next_space) = current_code[pos..].find(' ') {
                        pos + next_space
                    } else if let Some(next_space) = current_code[pos..].find('(') {
                        pos + next_space
                    } else {
                        pos
                    }
                } else {
                    pos
                };
                let p2 = std::cmp::max(pos, next_space);

                let last_word = current_code[..p2].split_whitespace().last()?;

                // Get the function name.
                return stdlib_signatures.get(last_word);
            } else if ch == ',' {
                // If we have a comma, then get the string in front of
                // the closest ( and try to get the signature.

                // Find the last ( before the comma.
                let last_paren = current_code[..pos].rfind('(')?;
                // Get the string in front of the (.
                let last_word = current_code[..last_paren].split_whitespace().last()?;
                // Get the function name.
                return stdlib_signatures.get(last_word);
            }

            None
        };

        if let Some(signature) = check_char(ch) {
            return Ok(Some(signature.clone()));
        }

        // Check if we have context.
        if let Some(context) = params.context
            && let Some(character) = context.trigger_character
        {
            for character in character.chars() {
                // Check if we are on a ( or a ,.
                if (character == '(' || character == ',')
                    && let Some(signature) = check_char(character)
                {
                    return Ok(Some(signature.clone()));
                }
            }
        }

        let Some(ast) = ast else {
            return Ok(None);
        };

        let Some(value) = ast.ast.get_expr_for_position(pos) else {
            return Ok(None);
        };

        let Some(hover) =
            value.get_hover_value_for_position(pos, current_code, &HoverOpts::default_for_signature_help())
        else {
            return Ok(None);
        };

        match hover {
            Hover::Function { name, range: _ } => {
                // Get the docs for this function.
                let Some(signature) = stdlib_signatures.get(&name) else {
                    return Ok(None);
                };

                Ok(Some(signature.clone()))
            }
            Hover::Signature {
                name,
                parameter_index,
                range: _,
            } => {
                let Some(signature) = stdlib_signatures.get(&name) else {
                    return Ok(None);
                };

                let mut signature = signature.clone();

                signature.active_parameter = Some(parameter_index);

                Ok(Some(signature))
            }
            _ => {
                return Ok(None);
            }
        }
    }

    async fn inlay_hint(&self, _params: InlayHintParams) -> RpcResult<Option<Vec<InlayHint>>> {
        // TODO: do this

        Ok(None)
    }

    async fn semantic_tokens_full(&self, params: SemanticTokensParams) -> RpcResult<Option<SemanticTokensResult>> {
        let filename = params.text_document.uri.to_string();

        let Some(semantic_tokens) = self.semantic_tokens_map.get(&filename) else {
            return Ok(None);
        };

        Ok(Some(SemanticTokensResult::Tokens(SemanticTokens {
            result_id: None,
            data: semantic_tokens.clone(),
        })))
    }

    async fn document_symbol(&self, params: DocumentSymbolParams) -> RpcResult<Option<DocumentSymbolResponse>> {
        let filename = params.text_document.uri.to_string();

        let Some(symbols) = self.symbols_map.get(&filename) else {
            return Ok(None);
        };

        Ok(Some(DocumentSymbolResponse::Nested(symbols.clone())))
    }

    async fn formatting(&self, params: DocumentFormattingParams) -> RpcResult<Option<Vec<TextEdit>>> {
        let filename = params.text_document.uri.to_string();

        let Some(current_code) = self.code_map.get(&filename) else {
            return Ok(None);
        };
        let Ok(current_code) = std::str::from_utf8(&current_code) else {
            return Ok(None);
        };

        // Parse the ast.
        // I don't know if we need to do this again since it should be updated in the context.
        // But I figure better safe than sorry since this will write back out to the file.
        let module_id = ModuleId::default();
        let Ok(ast) = crate::parsing::parse_str(current_code, module_id).parse_errs_as_err() else {
            return Ok(None);
        };
        // Now recast it.
        let recast = ast.recast_top(
            &crate::parsing::ast::types::FormatOptions {
                tab_size: params.options.tab_size as usize,
                insert_final_newline: params.options.insert_final_newline.unwrap_or(false),
                use_tabs: !params.options.insert_spaces,
            },
            0,
        );
        let source_range = SourceRange::new(0, current_code.len(), module_id);
        let range = source_range.to_lsp_range(current_code);
        Ok(Some(vec![TextEdit {
            new_text: recast,
            range,
        }]))
    }

    async fn rename(&self, params: RenameParams) -> RpcResult<Option<WorkspaceEdit>> {
        let Some((current_code, new_code)) =
            self.inner_prepare_rename(&params.text_document_position, &params.new_name)?
        else {
            return Ok(None);
        };

        let source_range = SourceRange::new(0, current_code.len(), ModuleId::default());
        let range = source_range.to_lsp_range(&current_code);
        Ok(Some(WorkspaceEdit {
            changes: Some(HashMap::from([(
                params.text_document_position.text_document.uri,
                vec![TextEdit {
                    new_text: new_code,
                    range,
                }],
            )])),
            document_changes: None,
            change_annotations: None,
        }))
    }

    async fn prepare_rename(&self, params: TextDocumentPositionParams) -> RpcResult<Option<PrepareRenameResponse>> {
        if self
            .inner_prepare_rename(&params, "someNameNoOneInTheirRightMindWouldEverUseForTesting")?
            .is_none()
        {
            return Ok(None);
        }

        // Return back to the client, that it is safe to use the rename behavior.
        Ok(Some(PrepareRenameResponse::DefaultBehavior { default_behavior: true }))
    }

    async fn folding_range(&self, params: FoldingRangeParams) -> RpcResult<Option<Vec<FoldingRange>>> {
        let filename = params.text_document.uri.to_string();

        // Get the ast.
        let Some(ast) = self.ast_map.get(&filename) else {
            return Ok(None);
        };

        // Get the folding ranges.
        let folding_ranges = ast.ast.get_lsp_folding_ranges();

        if folding_ranges.is_empty() {
            return Ok(None);
        }

        Ok(Some(folding_ranges))
    }

    async fn code_action(&self, params: CodeActionParams) -> RpcResult<Option<CodeActionResponse>> {
        // Get the actual diagnostics from our map to ensure we have the full diagnostic info
        let filename = params.text_document.uri.to_string();
        let stored_diagnostics = self
            .diagnostics_map
            .get(&filename)
            .map(|d| d.clone())
            .unwrap_or_default();

        // Use stored diagnostics if available, otherwise fall back to params.context.diagnostics
        let diagnostics_to_check: Vec<_> = if stored_diagnostics.is_empty() {
            params.context.diagnostics.clone()
        } else {
            // Match params.context.diagnostics with stored diagnostics by range
            params
                .context
                .diagnostics
                .iter()
                .filter_map(|param_diag| {
                    stored_diagnostics
                        .iter()
                        .find(|stored_diag| stored_diag.range == param_diag.range)
                        .cloned()
                })
                .collect()
        };

        let actions = diagnostics_to_check
            .into_iter()
            .filter_map(|diagnostic| {
                // Handle regular suggestions (like camelCase)
                let (suggestion, range) = diagnostic
                    .data
                    .as_ref()
                    .and_then(|data| serde_json::from_value::<LspSuggestion>(data.clone()).ok())?;
                let edit = TextEdit {
                    range,
                    new_text: suggestion.insert,
                };
                let changes = HashMap::from([(params.text_document.uri.clone(), vec![edit])]);

                // If you add more code action kinds, make sure you add it to the server
                // capabilities on initialization!
                Some(CodeActionOrCommand::CodeAction(CodeAction {
                    title: suggestion.title,
                    kind: Some(CodeActionKind::QUICKFIX),
                    diagnostics: Some(vec![diagnostic]),
                    edit: Some(WorkspaceEdit {
                        changes: Some(changes),
                        document_changes: None,
                        change_annotations: None,
                    }),
                    command: None,
                    is_preferred: Some(true),
                    disabled: None,
                    data: None,
                }))
            })
            .collect();

        Ok(Some(actions))
    }

    async fn document_color(&self, params: DocumentColorParams) -> RpcResult<Vec<ColorInformation>> {
        let filename = params.text_document.uri.to_string();

        let Some(current_code) = self.code_map.get(&filename) else {
            return Ok(vec![]);
        };
        let Ok(current_code) = std::str::from_utf8(&current_code) else {
            return Ok(vec![]);
        };

        // Get the ast from our map.
        let Some(ast) = self.ast_map.get(&filename) else {
            return Ok(vec![]);
        };

        // Get the colors from the ast.
        let Ok(colors) = ast.ast.document_color(current_code) else {
            return Ok(vec![]);
        };

        Ok(colors)
    }

    async fn color_presentation(&self, params: ColorPresentationParams) -> RpcResult<Vec<ColorPresentation>> {
        let filename = params.text_document.uri.to_string();

        let Some(current_code) = self.code_map.get(&filename) else {
            return Ok(vec![]);
        };
        let Ok(current_code) = std::str::from_utf8(&current_code) else {
            return Ok(vec![]);
        };

        // Get the ast from our map.
        let Some(ast) = self.ast_map.get(&filename) else {
            return Ok(vec![]);
        };

        let pos_start = position_to_char_index(params.range.start, current_code);
        let pos_end = position_to_char_index(params.range.end, current_code);

        // Get the colors from the ast.
        let Ok(Some(presentation)) = ast.ast.color_presentation(&params.color, pos_start, pos_end) else {
            return Ok(vec![]);
        };

        Ok(vec![presentation])
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum StdlibCompletionContext {
    Default,
    SketchBlock,
}

fn is_sketch2_doc(doc: &crate::docs::kcl_doc::DocData) -> bool {
    doc.qual_name().starts_with("std::solver::")
}

fn strip_sketch2_prefix(value: &str) -> String {
    value.strip_prefix("solver::").unwrap_or(value).to_owned()
}

fn rewrite_completion_for_sketch_block(mut completion: CompletionItem) -> CompletionItem {
    completion.label = strip_sketch2_prefix(&completion.label);
    completion.insert_text = completion.insert_text.map(|text| strip_sketch2_prefix(&text));
    completion
}

fn rewrite_signature_for_sketch_block(mut signature: SignatureHelp) -> SignatureHelp {
    for info in &mut signature.signatures {
        info.label = strip_sketch2_prefix(&info.label);
    }
    signature
}

fn should_skip_stdlib_doc(
    doc: &crate::docs::kcl_doc::DocData,
    has_existing: bool,
    context: StdlibCompletionContext,
) -> bool {
    if !has_existing {
        return false;
    }

    match context {
        StdlibCompletionContext::Default => doc.is_experimental() || is_sketch2_doc(doc),
        StdlibCompletionContext::SketchBlock => doc.is_experimental() && !is_sketch2_doc(doc),
    }
}

/// Get completions from our stdlib.
pub fn get_completions_from_stdlib(kcl_std: &ModData) -> Result<HashMap<String, CompletionItem>> {
    get_completions_from_stdlib_in_context(kcl_std, StdlibCompletionContext::Default)
}

pub fn get_completions_from_stdlib_for_sketch_block(kcl_std: &ModData) -> Result<HashMap<String, CompletionItem>> {
    get_completions_from_stdlib_in_context(kcl_std, StdlibCompletionContext::SketchBlock)
}

fn get_completions_from_stdlib_in_context(
    kcl_std: &ModData,
    context: StdlibCompletionContext,
) -> Result<HashMap<String, CompletionItem>> {
    let mut completions = HashMap::new();

    for d in kcl_std.all_docs() {
        if let Some(mut ci) = d.to_completion_item() {
            let name = d.name();
            if should_skip_stdlib_doc(d, completions.contains_key(name), context) {
                continue;
            }
            if context == StdlibCompletionContext::SketchBlock && is_sketch2_doc(d) {
                ci = rewrite_completion_for_sketch_block(ci);
            }
            completions.insert(name.to_owned(), ci);
        }
    }

    let variable_kinds = VariableKind::to_completion_items();
    for variable_kind in variable_kinds {
        completions.insert(variable_kind.label.clone(), variable_kind);
    }

    Ok(completions)
}

/// Get signatures from our stdlib.
pub fn get_signatures_from_stdlib(kcl_std: &ModData) -> HashMap<String, SignatureHelp> {
    get_signatures_from_stdlib_in_context(kcl_std, StdlibCompletionContext::Default)
}

pub fn get_signatures_from_stdlib_for_sketch_block(kcl_std: &ModData) -> HashMap<String, SignatureHelp> {
    get_signatures_from_stdlib_in_context(kcl_std, StdlibCompletionContext::SketchBlock)
}

fn get_signatures_from_stdlib_in_context(
    kcl_std: &ModData,
    context: StdlibCompletionContext,
) -> HashMap<String, SignatureHelp> {
    let mut signatures = HashMap::new();

    for d in kcl_std.all_docs() {
        if let Some(mut sig) = d.to_signature_help() {
            let name = d.name();
            if should_skip_stdlib_doc(d, signatures.contains_key(name), context) {
                continue;
            }
            if context == StdlibCompletionContext::SketchBlock && is_sketch2_doc(d) {
                sig = rewrite_signature_for_sketch_block(sig);
            }
            signatures.insert(name.to_owned(), sig);
        }
    }

    signatures
}

/// Get KCL keywords
pub fn get_keywords() -> HashMap<String, CompletionItem> {
    RESERVED_WORDS
        .keys()
        .map(|k| (k.to_string(), keyword_to_completion(k.to_string())))
        .collect()
}

fn keyword_to_completion(kw: String) -> CompletionItem {
    CompletionItem {
        label: kw,
        label_details: None,
        kind: Some(CompletionItemKind::KEYWORD),
        detail: None,
        documentation: None,
        deprecated: Some(false),
        preselect: None,
        sort_text: None,
        filter_text: None,
        insert_text: None,
        insert_text_format: None,
        insert_text_mode: None,
        text_edit: None,
        additional_text_edits: None,
        command: None,
        commit_characters: None,
        data: None,
        tags: None,
    }
}

#[derive(Clone, Debug)]
pub struct LspArgData {
    pub tip: String,
    pub props: ArgData,
}

/// Get signatures from our stdlib.
pub fn get_arg_maps_from_stdlib(kcl_std: &ModData) -> HashMap<String, HashMap<String, LspArgData>> {
    get_arg_maps_from_stdlib_in_context(kcl_std, StdlibCompletionContext::Default)
}

pub fn get_arg_maps_from_stdlib_for_sketch_block(kcl_std: &ModData) -> HashMap<String, HashMap<String, LspArgData>> {
    get_arg_maps_from_stdlib_in_context(kcl_std, StdlibCompletionContext::SketchBlock)
}

fn get_arg_maps_from_stdlib_in_context(
    kcl_std: &ModData,
    context: StdlibCompletionContext,
) -> HashMap<String, HashMap<String, LspArgData>> {
    let mut result = HashMap::new();

    for d in kcl_std.all_docs() {
        let crate::docs::kcl_doc::DocData::Fn(f) = d else {
            continue;
        };
        let arg_map: HashMap<String, _> = f
            .args
            .iter()
            .map(|data| {
                let mut tip = "```\n".to_owned();
                tip.push_str(&data.to_string());
                tip.push_str("\n```");
                if let Some(docs) = &data.docs {
                    tip.push_str("\n\n");
                    tip.push_str(docs);
                }
                let arg_data = LspArgData {
                    tip,
                    props: data.clone(),
                };
                (data.name.clone(), arg_data)
            })
            .collect();
        if !arg_map.is_empty() {
            if should_skip_stdlib_doc(d, result.contains_key(&f.name), context) {
                continue;
            }
            result.insert(f.name.clone(), arg_map);
        }
    }

    result
}

/// Convert a position to a character index from the start of the file.
fn position_to_char_index(position: Position, code: &str) -> usize {
    // Get the character position from the start of the file.
    let mut char_position = 0;
    for (index, line) in code.lines().enumerate() {
        if index == position.line as usize {
            char_position += position.character as usize;
            break;
        } else {
            char_position += line.len() + 1;
        }
    }

    let end_of_file = if code.is_empty() { 0 } else { code.len() - 1 };
    std::cmp::min(char_position, end_of_file)
}

async fn with_cached_var<T>(name: &str, f: impl Fn(&KclValue) -> T) -> Option<T> {
    let mem = cache::read_old_memory().await?;
    let value = mem.stack.get(name, SourceRange::default()).ok()?;

    Some(f(value))
}

#[cfg(test)]
mod tests {
    use pretty_assertions::assert_eq;

    use super::*;

    #[test]
    fn test_position_to_char_index_first_line() {
        let code = r#"def foo():
return 42"#;
        let position = Position::new(0, 3);
        let index = position_to_char_index(position, code);
        assert_eq!(index, 3);
    }

    #[test]
    fn test_position_to_char_index() {
        let code = r#"def foo():
return 42"#;
        let position = Position::new(1, 4);
        let index = position_to_char_index(position, code);
        assert_eq!(index, 15);
    }

    #[test]
    fn test_position_to_char_index_with_newline() {
        let code = r#"def foo():

return 42"#;
        let position = Position::new(2, 0);
        let index = position_to_char_index(position, code);
        assert_eq!(index, 12);
    }

    #[test]
    fn test_position_to_char_at_end() {
        let code = r#"def foo():
return 42"#;

        let position = Position::new(1, 8);
        let index = position_to_char_index(position, code);
        assert_eq!(index, 19);
    }

    #[test]
    fn test_position_to_char_empty() {
        let code = r#""#;
        let position = Position::new(0, 0);
        let index = position_to_char_index(position, code);
        assert_eq!(index, 0);
    }
}