-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
handlers.rs
1900 lines (1679 loc) · 68.7 KB
/
handlers.rs
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
//! This module is responsible for implementing handlers for Language Server
//! Protocol. The majority of requests are fulfilled by calling into the
//! `ide` crate.
use std::{
io::Write as _,
process::{self, Stdio},
};
use anyhow::Context;
use ide::{
AnnotationConfig, AssistKind, AssistResolveStrategy, Cancellable, FileId, FilePosition,
FileRange, HoverAction, HoverGotoTypeData, Query, RangeInfo, ReferenceCategory, Runnable,
RunnableKind, SingleResolve, SourceChange, TextEdit,
};
use ide_db::SymbolKind;
use lsp_server::ErrorCode;
use lsp_types::{
CallHierarchyIncomingCall, CallHierarchyIncomingCallsParams, CallHierarchyItem,
CallHierarchyOutgoingCall, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams,
CodeLens, CompletionItem, Diagnostic, DiagnosticTag, DocumentFormattingParams, FoldingRange,
FoldingRangeParams, HoverContents, InlayHint, InlayHintParams, Location, LocationLink,
NumberOrString, Position, PrepareRenameResponse, Range, RenameParams,
SemanticTokensDeltaParams, SemanticTokensFullDeltaResult, SemanticTokensParams,
SemanticTokensRangeParams, SemanticTokensRangeResult, SemanticTokensResult, SymbolInformation,
SymbolTag, TextDocumentIdentifier, Url, WorkspaceEdit,
};
use project_model::{ManifestPath, ProjectWorkspace, TargetKind};
use serde_json::json;
use stdx::{format_to, never};
use syntax::{algo, ast, AstNode, TextRange, TextSize};
use vfs::AbsPathBuf;
use crate::{
cargo_target_spec::CargoTargetSpec,
config::{RustfmtConfig, WorkspaceSymbolConfig},
diff::diff,
from_proto,
global_state::{GlobalState, GlobalStateSnapshot},
line_index::LineEndings,
lsp_ext::{self, PositionOrRange, ViewCrateGraphParams, WorkspaceSymbolParams},
lsp_utils::{all_edits_are_disjoint, invalid_params_error},
to_proto, LspError, Result,
};
pub(crate) fn handle_workspace_reload(state: &mut GlobalState, _: ()) -> Result<()> {
state.proc_macro_clients.clear();
state.proc_macro_changed = false;
state.fetch_workspaces_queue.request_op("reload workspace request".to_string());
state.fetch_build_data_queue.request_op("reload workspace request".to_string());
Ok(())
}
pub(crate) fn handle_cancel_flycheck(state: &mut GlobalState, _: ()) -> Result<()> {
let _p = profile::span("handle_stop_flycheck");
state.flycheck.iter().for_each(|flycheck| flycheck.cancel());
Ok(())
}
pub(crate) fn handle_analyzer_status(
snap: GlobalStateSnapshot,
params: lsp_ext::AnalyzerStatusParams,
) -> Result<String> {
let _p = profile::span("handle_analyzer_status");
let mut buf = String::new();
let mut file_id = None;
if let Some(tdi) = params.text_document {
match from_proto::file_id(&snap, &tdi.uri) {
Ok(it) => file_id = Some(it),
Err(_) => format_to!(buf, "file {} not found in vfs", tdi.uri),
}
}
if snap.workspaces.is_empty() {
buf.push_str("No workspaces\n")
} else {
buf.push_str("Workspaces:\n");
format_to!(
buf,
"Loaded {:?} packages across {} workspace{}.\n",
snap.workspaces.iter().map(|w| w.n_packages()).sum::<usize>(),
snap.workspaces.len(),
if snap.workspaces.len() == 1 { "" } else { "s" }
);
}
buf.push_str("\nAnalysis:\n");
buf.push_str(
&snap
.analysis
.status(file_id)
.unwrap_or_else(|_| "Analysis retrieval was cancelled".to_owned()),
);
Ok(buf)
}
pub(crate) fn handle_memory_usage(state: &mut GlobalState, _: ()) -> Result<String> {
let _p = profile::span("handle_memory_usage");
let mut mem = state.analysis_host.per_query_memory_usage();
mem.push(("Remaining".into(), profile::memory_usage().allocated));
let mut out = String::new();
for (name, bytes) in mem {
format_to!(out, "{:>8} {}\n", bytes, name);
}
Ok(out)
}
pub(crate) fn handle_shuffle_crate_graph(state: &mut GlobalState, _: ()) -> Result<()> {
state.analysis_host.shuffle_crate_graph();
Ok(())
}
pub(crate) fn handle_syntax_tree(
snap: GlobalStateSnapshot,
params: lsp_ext::SyntaxTreeParams,
) -> Result<String> {
let _p = profile::span("handle_syntax_tree");
let id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
let line_index = snap.file_line_index(id)?;
let text_range = params.range.and_then(|r| from_proto::text_range(&line_index, r).ok());
let res = snap.analysis.syntax_tree(id, text_range)?;
Ok(res)
}
pub(crate) fn handle_view_hir(
snap: GlobalStateSnapshot,
params: lsp_types::TextDocumentPositionParams,
) -> Result<String> {
let _p = profile::span("handle_view_hir");
let position = from_proto::file_position(&snap, params)?;
let res = snap.analysis.view_hir(position)?;
Ok(res)
}
pub(crate) fn handle_view_mir(
snap: GlobalStateSnapshot,
params: lsp_types::TextDocumentPositionParams,
) -> Result<String> {
let _p = profile::span("handle_view_mir");
let position = from_proto::file_position(&snap, params)?;
let res = snap.analysis.view_mir(position)?;
Ok(res)
}
pub(crate) fn handle_view_file_text(
snap: GlobalStateSnapshot,
params: lsp_types::TextDocumentIdentifier,
) -> Result<String> {
let file_id = from_proto::file_id(&snap, ¶ms.uri)?;
Ok(snap.analysis.file_text(file_id)?.to_string())
}
pub(crate) fn handle_view_item_tree(
snap: GlobalStateSnapshot,
params: lsp_ext::ViewItemTreeParams,
) -> Result<String> {
let _p = profile::span("handle_view_item_tree");
let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
let res = snap.analysis.view_item_tree(file_id)?;
Ok(res)
}
pub(crate) fn handle_view_crate_graph(
snap: GlobalStateSnapshot,
params: ViewCrateGraphParams,
) -> Result<String> {
let _p = profile::span("handle_view_crate_graph");
let dot = snap.analysis.view_crate_graph(params.full)??;
Ok(dot)
}
pub(crate) fn handle_expand_macro(
snap: GlobalStateSnapshot,
params: lsp_ext::ExpandMacroParams,
) -> Result<Option<lsp_ext::ExpandedMacro>> {
let _p = profile::span("handle_expand_macro");
let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
let line_index = snap.file_line_index(file_id)?;
let offset = from_proto::offset(&line_index, params.position)?;
let res = snap.analysis.expand_macro(FilePosition { file_id, offset })?;
Ok(res.map(|it| lsp_ext::ExpandedMacro { name: it.name, expansion: it.expansion }))
}
pub(crate) fn handle_selection_range(
snap: GlobalStateSnapshot,
params: lsp_types::SelectionRangeParams,
) -> Result<Option<Vec<lsp_types::SelectionRange>>> {
let _p = profile::span("handle_selection_range");
let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
let line_index = snap.file_line_index(file_id)?;
let res: Result<Vec<lsp_types::SelectionRange>> = params
.positions
.into_iter()
.map(|position| {
let offset = from_proto::offset(&line_index, position)?;
let mut ranges = Vec::new();
{
let mut range = TextRange::new(offset, offset);
loop {
ranges.push(range);
let frange = FileRange { file_id, range };
let next = snap.analysis.extend_selection(frange)?;
if next == range {
break;
} else {
range = next
}
}
}
let mut range = lsp_types::SelectionRange {
range: to_proto::range(&line_index, *ranges.last().unwrap()),
parent: None,
};
for &r in ranges.iter().rev().skip(1) {
range = lsp_types::SelectionRange {
range: to_proto::range(&line_index, r),
parent: Some(Box::new(range)),
}
}
Ok(range)
})
.collect();
Ok(Some(res?))
}
pub(crate) fn handle_matching_brace(
snap: GlobalStateSnapshot,
params: lsp_ext::MatchingBraceParams,
) -> Result<Vec<Position>> {
let _p = profile::span("handle_matching_brace");
let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
let line_index = snap.file_line_index(file_id)?;
params
.positions
.into_iter()
.map(|position| {
let offset = from_proto::offset(&line_index, position);
offset.map(|offset| {
let offset = match snap.analysis.matching_brace(FilePosition { file_id, offset }) {
Ok(Some(matching_brace_offset)) => matching_brace_offset,
Err(_) | Ok(None) => offset,
};
to_proto::position(&line_index, offset)
})
})
.collect()
}
pub(crate) fn handle_join_lines(
snap: GlobalStateSnapshot,
params: lsp_ext::JoinLinesParams,
) -> Result<Vec<lsp_types::TextEdit>> {
let _p = profile::span("handle_join_lines");
let config = snap.config.join_lines();
let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
let line_index = snap.file_line_index(file_id)?;
let mut res = TextEdit::default();
for range in params.ranges {
let range = from_proto::text_range(&line_index, range)?;
let edit = snap.analysis.join_lines(&config, FileRange { file_id, range })?;
match res.union(edit) {
Ok(()) => (),
Err(_edit) => {
// just ignore overlapping edits
}
}
}
Ok(to_proto::text_edit_vec(&line_index, res))
}
pub(crate) fn handle_on_enter(
snap: GlobalStateSnapshot,
params: lsp_types::TextDocumentPositionParams,
) -> Result<Option<Vec<lsp_ext::SnippetTextEdit>>> {
let _p = profile::span("handle_on_enter");
let position = from_proto::file_position(&snap, params)?;
let edit = match snap.analysis.on_enter(position)? {
None => return Ok(None),
Some(it) => it,
};
let line_index = snap.file_line_index(position.file_id)?;
let edit = to_proto::snippet_text_edit_vec(&line_index, true, edit);
Ok(Some(edit))
}
pub(crate) fn handle_on_type_formatting(
snap: GlobalStateSnapshot,
params: lsp_types::DocumentOnTypeFormattingParams,
) -> Result<Option<Vec<lsp_ext::SnippetTextEdit>>> {
let _p = profile::span("handle_on_type_formatting");
let mut position = from_proto::file_position(&snap, params.text_document_position)?;
let line_index = snap.file_line_index(position.file_id)?;
// in `ide`, the `on_type` invariant is that
// `text.char_at(position) == typed_char`.
position.offset -= TextSize::of('.');
let char_typed = params.ch.chars().next().unwrap_or('\0');
let text = snap.analysis.file_text(position.file_id)?;
if stdx::never!(!text[usize::from(position.offset)..].starts_with(char_typed)) {
return Ok(None);
}
// We have an assist that inserts ` ` after typing `->` in `fn foo() ->{`,
// but it requires precise cursor positioning to work, and one can't
// position the cursor with on_type formatting. So, let's just toggle this
// feature off here, hoping that we'll enable it one day, 😿.
if char_typed == '>' {
return Ok(None);
}
let edit =
snap.analysis.on_char_typed(position, char_typed, snap.config.typing_autoclose_angle())?;
let edit = match edit {
Some(it) => it,
None => return Ok(None),
};
// This should be a single-file edit
let (_, text_edit) = edit.source_file_edits.into_iter().next().unwrap();
let change = to_proto::snippet_text_edit_vec(&line_index, edit.is_snippet, text_edit);
Ok(Some(change))
}
pub(crate) fn handle_document_symbol(
snap: GlobalStateSnapshot,
params: lsp_types::DocumentSymbolParams,
) -> Result<Option<lsp_types::DocumentSymbolResponse>> {
let _p = profile::span("handle_document_symbol");
let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
let line_index = snap.file_line_index(file_id)?;
let mut parents: Vec<(lsp_types::DocumentSymbol, Option<usize>)> = Vec::new();
for symbol in snap.analysis.file_structure(file_id)? {
let mut tags = Vec::new();
if symbol.deprecated {
tags.push(SymbolTag::DEPRECATED)
};
#[allow(deprecated)]
let doc_symbol = lsp_types::DocumentSymbol {
name: symbol.label,
detail: symbol.detail,
kind: to_proto::structure_node_kind(symbol.kind),
tags: Some(tags),
deprecated: Some(symbol.deprecated),
range: to_proto::range(&line_index, symbol.node_range),
selection_range: to_proto::range(&line_index, symbol.navigation_range),
children: None,
};
parents.push((doc_symbol, symbol.parent));
}
// Builds hierarchy from a flat list, in reverse order (so that indices
// makes sense)
let document_symbols = {
let mut acc = Vec::new();
while let Some((mut node, parent_idx)) = parents.pop() {
if let Some(children) = &mut node.children {
children.reverse();
}
let parent = match parent_idx {
None => &mut acc,
Some(i) => parents[i].0.children.get_or_insert_with(Vec::new),
};
parent.push(node);
}
acc.reverse();
acc
};
let res = if snap.config.hierarchical_symbols() {
document_symbols.into()
} else {
let url = to_proto::url(&snap, file_id);
let mut symbol_information = Vec::<SymbolInformation>::new();
for symbol in document_symbols {
flatten_document_symbol(&symbol, None, &url, &mut symbol_information);
}
symbol_information.into()
};
return Ok(Some(res));
fn flatten_document_symbol(
symbol: &lsp_types::DocumentSymbol,
container_name: Option<String>,
url: &Url,
res: &mut Vec<SymbolInformation>,
) {
let mut tags = Vec::new();
#[allow(deprecated)]
if let Some(true) = symbol.deprecated {
tags.push(SymbolTag::DEPRECATED)
}
#[allow(deprecated)]
res.push(SymbolInformation {
name: symbol.name.clone(),
kind: symbol.kind,
tags: Some(tags),
deprecated: symbol.deprecated,
location: Location::new(url.clone(), symbol.range),
container_name,
});
for child in symbol.children.iter().flatten() {
flatten_document_symbol(child, Some(symbol.name.clone()), url, res);
}
}
}
pub(crate) fn handle_workspace_symbol(
snap: GlobalStateSnapshot,
params: WorkspaceSymbolParams,
) -> Result<Option<Vec<SymbolInformation>>> {
let _p = profile::span("handle_workspace_symbol");
let config = snap.config.workspace_symbol();
let (all_symbols, libs) = decide_search_scope_and_kind(¶ms, &config);
let limit = config.search_limit;
let query = {
let query: String = params.query.chars().filter(|&c| c != '#' && c != '*').collect();
let mut q = Query::new(query);
if !all_symbols {
q.only_types();
}
if libs {
q.libs();
}
q.limit(limit);
q
};
let mut res = exec_query(&snap, query)?;
if res.is_empty() && !all_symbols {
let mut query = Query::new(params.query);
query.limit(limit);
res = exec_query(&snap, query)?;
}
return Ok(Some(res));
fn decide_search_scope_and_kind(
params: &WorkspaceSymbolParams,
config: &WorkspaceSymbolConfig,
) -> (bool, bool) {
// Support old-style parsing of markers in the query.
let mut all_symbols = params.query.contains('#');
let mut libs = params.query.contains('*');
// If no explicit marker was set, check request params. If that's also empty
// use global config.
if !all_symbols {
let search_kind = match params.search_kind {
Some(ref search_kind) => search_kind,
None => &config.search_kind,
};
all_symbols = match search_kind {
lsp_ext::WorkspaceSymbolSearchKind::OnlyTypes => false,
lsp_ext::WorkspaceSymbolSearchKind::AllSymbols => true,
}
}
if !libs {
let search_scope = match params.search_scope {
Some(ref search_scope) => search_scope,
None => &config.search_scope,
};
libs = match search_scope {
lsp_ext::WorkspaceSymbolSearchScope::Workspace => false,
lsp_ext::WorkspaceSymbolSearchScope::WorkspaceAndDependencies => true,
}
}
(all_symbols, libs)
}
fn exec_query(snap: &GlobalStateSnapshot, query: Query) -> Result<Vec<SymbolInformation>> {
let mut res = Vec::new();
for nav in snap.analysis.symbol_search(query)? {
let container_name = nav.container_name.as_ref().map(|v| v.to_string());
#[allow(deprecated)]
let info = SymbolInformation {
name: nav.name.to_string(),
kind: nav
.kind
.map(to_proto::symbol_kind)
.unwrap_or(lsp_types::SymbolKind::VARIABLE),
tags: None,
location: to_proto::location_from_nav(snap, nav)?,
container_name,
deprecated: None,
};
res.push(info);
}
Ok(res)
}
}
pub(crate) fn handle_will_rename_files(
snap: GlobalStateSnapshot,
params: lsp_types::RenameFilesParams,
) -> Result<Option<lsp_types::WorkspaceEdit>> {
let _p = profile::span("handle_will_rename_files");
let source_changes: Vec<SourceChange> = params
.files
.into_iter()
.filter_map(|file_rename| {
let from = Url::parse(&file_rename.old_uri).ok()?;
let to = Url::parse(&file_rename.new_uri).ok()?;
let from_path = from.to_file_path().ok()?;
let to_path = to.to_file_path().ok()?;
// Limit to single-level moves for now.
match (from_path.parent(), to_path.parent()) {
(Some(p1), Some(p2)) if p1 == p2 => {
if from_path.is_dir() {
// add '/' to end of url -- from `file://path/to/folder` to `file://path/to/folder/`
let mut old_folder_name = from_path.file_stem()?.to_str()?.to_string();
old_folder_name.push('/');
let from_with_trailing_slash = from.join(&old_folder_name).ok()?;
let imitate_from_url = from_with_trailing_slash.join("mod.rs").ok()?;
let new_file_name = to_path.file_name()?.to_str()?;
Some((
snap.url_to_file_id(&imitate_from_url).ok()?,
new_file_name.to_string(),
))
} else {
let old_name = from_path.file_stem()?.to_str()?;
let new_name = to_path.file_stem()?.to_str()?;
match (old_name, new_name) {
("mod", _) => None,
(_, "mod") => None,
_ => Some((snap.url_to_file_id(&from).ok()?, new_name.to_string())),
}
}
}
_ => None,
}
})
.filter_map(|(file_id, new_name)| {
snap.analysis.will_rename_file(file_id, &new_name).ok()?
})
.collect();
// Drop file system edits since we're just renaming things on the same level
let mut source_changes = source_changes.into_iter();
let mut source_change = source_changes.next().unwrap_or_default();
source_change.file_system_edits.clear();
// no collect here because we want to merge text edits on same file ids
source_change.extend(source_changes.flat_map(|it| it.source_file_edits));
if source_change.source_file_edits.is_empty() {
Ok(None)
} else {
Ok(Some(to_proto::workspace_edit(&snap, source_change)?))
}
}
pub(crate) fn handle_goto_definition(
snap: GlobalStateSnapshot,
params: lsp_types::GotoDefinitionParams,
) -> Result<Option<lsp_types::GotoDefinitionResponse>> {
let _p = profile::span("handle_goto_definition");
let position = from_proto::file_position(&snap, params.text_document_position_params)?;
let nav_info = match snap.analysis.goto_definition(position)? {
None => return Ok(None),
Some(it) => it,
};
let src = FileRange { file_id: position.file_id, range: nav_info.range };
let res = to_proto::goto_definition_response(&snap, Some(src), nav_info.info)?;
Ok(Some(res))
}
pub(crate) fn handle_goto_declaration(
snap: GlobalStateSnapshot,
params: lsp_types::request::GotoDeclarationParams,
) -> Result<Option<lsp_types::request::GotoDeclarationResponse>> {
let _p = profile::span("handle_goto_declaration");
let position = from_proto::file_position(&snap, params.text_document_position_params.clone())?;
let nav_info = match snap.analysis.goto_declaration(position)? {
None => return handle_goto_definition(snap, params),
Some(it) => it,
};
let src = FileRange { file_id: position.file_id, range: nav_info.range };
let res = to_proto::goto_definition_response(&snap, Some(src), nav_info.info)?;
Ok(Some(res))
}
pub(crate) fn handle_goto_implementation(
snap: GlobalStateSnapshot,
params: lsp_types::request::GotoImplementationParams,
) -> Result<Option<lsp_types::request::GotoImplementationResponse>> {
let _p = profile::span("handle_goto_implementation");
let position = from_proto::file_position(&snap, params.text_document_position_params)?;
let nav_info = match snap.analysis.goto_implementation(position)? {
None => return Ok(None),
Some(it) => it,
};
let src = FileRange { file_id: position.file_id, range: nav_info.range };
let res = to_proto::goto_definition_response(&snap, Some(src), nav_info.info)?;
Ok(Some(res))
}
pub(crate) fn handle_goto_type_definition(
snap: GlobalStateSnapshot,
params: lsp_types::request::GotoTypeDefinitionParams,
) -> Result<Option<lsp_types::request::GotoTypeDefinitionResponse>> {
let _p = profile::span("handle_goto_type_definition");
let position = from_proto::file_position(&snap, params.text_document_position_params)?;
let nav_info = match snap.analysis.goto_type_definition(position)? {
None => return Ok(None),
Some(it) => it,
};
let src = FileRange { file_id: position.file_id, range: nav_info.range };
let res = to_proto::goto_definition_response(&snap, Some(src), nav_info.info)?;
Ok(Some(res))
}
pub(crate) fn handle_parent_module(
snap: GlobalStateSnapshot,
params: lsp_types::TextDocumentPositionParams,
) -> Result<Option<lsp_types::GotoDefinitionResponse>> {
let _p = profile::span("handle_parent_module");
if let Ok(file_path) = ¶ms.text_document.uri.to_file_path() {
if file_path.file_name().unwrap_or_default() == "Cargo.toml" {
// search workspaces for parent packages or fallback to workspace root
let abs_path_buf = match AbsPathBuf::try_from(file_path.to_path_buf()).ok() {
Some(abs_path_buf) => abs_path_buf,
None => return Ok(None),
};
let manifest_path = match ManifestPath::try_from(abs_path_buf).ok() {
Some(manifest_path) => manifest_path,
None => return Ok(None),
};
let links: Vec<LocationLink> = snap
.workspaces
.iter()
.filter_map(|ws| match ws {
ProjectWorkspace::Cargo { cargo, .. } => cargo.parent_manifests(&manifest_path),
_ => None,
})
.flatten()
.map(|parent_manifest_path| LocationLink {
origin_selection_range: None,
target_uri: to_proto::url_from_abs_path(&parent_manifest_path),
target_range: Range::default(),
target_selection_range: Range::default(),
})
.collect::<_>();
return Ok(Some(links.into()));
}
// check if invoked at the crate root
let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
let crate_id = match snap.analysis.crates_for(file_id)?.first() {
Some(&crate_id) => crate_id,
None => return Ok(None),
};
let cargo_spec = match CargoTargetSpec::for_file(&snap, file_id)? {
Some(it) => it,
None => return Ok(None),
};
if snap.analysis.crate_root(crate_id)? == file_id {
let cargo_toml_url = to_proto::url_from_abs_path(&cargo_spec.cargo_toml);
let res = vec![LocationLink {
origin_selection_range: None,
target_uri: cargo_toml_url,
target_range: Range::default(),
target_selection_range: Range::default(),
}]
.into();
return Ok(Some(res));
}
}
// locate parent module by semantics
let position = from_proto::file_position(&snap, params)?;
let navs = snap.analysis.parent_module(position)?;
let res = to_proto::goto_definition_response(&snap, None, navs)?;
Ok(Some(res))
}
pub(crate) fn handle_runnables(
snap: GlobalStateSnapshot,
params: lsp_ext::RunnablesParams,
) -> Result<Vec<lsp_ext::Runnable>> {
let _p = profile::span("handle_runnables");
let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
let line_index = snap.file_line_index(file_id)?;
let offset = params.position.and_then(|it| from_proto::offset(&line_index, it).ok());
let cargo_spec = CargoTargetSpec::for_file(&snap, file_id)?;
let expect_test = match offset {
Some(offset) => {
let source_file = snap.analysis.parse(file_id)?;
algo::find_node_at_offset::<ast::MacroCall>(source_file.syntax(), offset)
.and_then(|it| it.path()?.segment()?.name_ref())
.map_or(false, |it| it.text() == "expect" || it.text() == "expect_file")
}
None => false,
};
let mut res = Vec::new();
for runnable in snap.analysis.runnables(file_id)? {
if should_skip_for_offset(&runnable, offset) {
continue;
}
if should_skip_target(&runnable, cargo_spec.as_ref()) {
continue;
}
let mut runnable = to_proto::runnable(&snap, runnable)?;
if expect_test {
runnable.label = format!("{} + expect", runnable.label);
runnable.args.expect_test = Some(true);
}
res.push(runnable);
}
// Add `cargo check` and `cargo test` for all targets of the whole package
let config = snap.config.runnables();
match cargo_spec {
Some(spec) => {
for cmd in ["check", "test"] {
res.push(lsp_ext::Runnable {
label: format!("cargo {cmd} -p {} --all-targets", spec.package),
location: None,
kind: lsp_ext::RunnableKind::Cargo,
args: lsp_ext::CargoRunnable {
workspace_root: Some(spec.workspace_root.clone().into()),
override_cargo: config.override_cargo.clone(),
cargo_args: vec![
cmd.to_string(),
"--package".to_string(),
spec.package.clone(),
"--all-targets".to_string(),
],
cargo_extra_args: config.cargo_extra_args.clone(),
executable_args: Vec::new(),
expect_test: None,
},
})
}
}
None => {
if !snap.config.linked_projects().is_empty()
|| !snap
.config
.discovered_projects
.as_ref()
.map(|projects| projects.is_empty())
.unwrap_or(true)
{
res.push(lsp_ext::Runnable {
label: "cargo check --workspace".to_string(),
location: None,
kind: lsp_ext::RunnableKind::Cargo,
args: lsp_ext::CargoRunnable {
workspace_root: None,
override_cargo: config.override_cargo,
cargo_args: vec!["check".to_string(), "--workspace".to_string()],
cargo_extra_args: config.cargo_extra_args,
executable_args: Vec::new(),
expect_test: None,
},
});
}
}
}
Ok(res)
}
fn should_skip_for_offset(runnable: &Runnable, offset: Option<TextSize>) -> bool {
match offset {
None => false,
_ if matches!(&runnable.kind, RunnableKind::TestMod { .. }) => false,
Some(offset) => !runnable.nav.full_range.contains_inclusive(offset),
}
}
pub(crate) fn handle_related_tests(
snap: GlobalStateSnapshot,
params: lsp_types::TextDocumentPositionParams,
) -> Result<Vec<lsp_ext::TestInfo>> {
let _p = profile::span("handle_related_tests");
let position = from_proto::file_position(&snap, params)?;
let tests = snap.analysis.related_tests(position, None)?;
let mut res = Vec::new();
for it in tests {
if let Ok(runnable) = to_proto::runnable(&snap, it) {
res.push(lsp_ext::TestInfo { runnable })
}
}
Ok(res)
}
pub(crate) fn handle_completion(
snap: GlobalStateSnapshot,
params: lsp_types::CompletionParams,
) -> Result<Option<lsp_types::CompletionResponse>> {
let _p = profile::span("handle_completion");
let text_document_position = params.text_document_position.clone();
let position = from_proto::file_position(&snap, params.text_document_position)?;
let completion_trigger_character =
params.context.and_then(|ctx| ctx.trigger_character).and_then(|s| s.chars().next());
let completion_config = &snap.config.completion();
let items = match snap.analysis.completions(
completion_config,
position,
completion_trigger_character,
)? {
None => return Ok(None),
Some(items) => items,
};
let line_index = snap.file_line_index(position.file_id)?;
let items =
to_proto::completion_items(&snap.config, &line_index, text_document_position, items);
let completion_list = lsp_types::CompletionList { is_incomplete: true, items };
Ok(Some(completion_list.into()))
}
pub(crate) fn handle_completion_resolve(
snap: GlobalStateSnapshot,
mut original_completion: CompletionItem,
) -> Result<CompletionItem> {
let _p = profile::span("handle_completion_resolve");
if !all_edits_are_disjoint(&original_completion, &[]) {
return Err(invalid_params_error(
"Received a completion with overlapping edits, this is not LSP-compliant".to_string(),
)
.into());
}
let data = match original_completion.data.take() {
Some(it) => it,
None => return Ok(original_completion),
};
let resolve_data: lsp_ext::CompletionResolveData = serde_json::from_value(data)?;
let file_id = from_proto::file_id(&snap, &resolve_data.position.text_document.uri)?;
let line_index = snap.file_line_index(file_id)?;
let offset = from_proto::offset(&line_index, resolve_data.position.position)?;
let additional_edits = snap
.analysis
.resolve_completion_edits(
&snap.config.completion(),
FilePosition { file_id, offset },
resolve_data
.imports
.into_iter()
.map(|import| (import.full_import_path, import.imported_name)),
)?
.into_iter()
.flat_map(|edit| edit.into_iter().map(|indel| to_proto::text_edit(&line_index, indel)))
.collect::<Vec<_>>();
if !all_edits_are_disjoint(&original_completion, &additional_edits) {
return Err(LspError::new(
ErrorCode::InternalError as i32,
"Import edit overlaps with the original completion edits, this is not LSP-compliant"
.into(),
)
.into());
}
if let Some(original_additional_edits) = original_completion.additional_text_edits.as_mut() {
original_additional_edits.extend(additional_edits.into_iter())
} else {
original_completion.additional_text_edits = Some(additional_edits);
}
Ok(original_completion)
}
pub(crate) fn handle_folding_range(
snap: GlobalStateSnapshot,
params: FoldingRangeParams,
) -> Result<Option<Vec<FoldingRange>>> {
let _p = profile::span("handle_folding_range");
let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
let folds = snap.analysis.folding_ranges(file_id)?;
let text = snap.analysis.file_text(file_id)?;
let line_index = snap.file_line_index(file_id)?;
let line_folding_only = snap.config.line_folding_only();
let res = folds
.into_iter()
.map(|it| to_proto::folding_range(&text, &line_index, line_folding_only, it))
.collect();
Ok(Some(res))
}
pub(crate) fn handle_signature_help(
snap: GlobalStateSnapshot,
params: lsp_types::SignatureHelpParams,
) -> Result<Option<lsp_types::SignatureHelp>> {
let _p = profile::span("handle_signature_help");
let position = from_proto::file_position(&snap, params.text_document_position_params)?;
let help = match snap.analysis.signature_help(position)? {
Some(it) => it,
None => return Ok(None),
};
let config = snap.config.call_info();
let res = to_proto::signature_help(help, config, snap.config.signature_help_label_offsets());
Ok(Some(res))
}
pub(crate) fn handle_hover(
snap: GlobalStateSnapshot,
params: lsp_ext::HoverParams,
) -> Result<Option<lsp_ext::Hover>> {
let _p = profile::span("handle_hover");
let range = match params.position {
PositionOrRange::Position(position) => Range::new(position, position),
PositionOrRange::Range(range) => range,
};
let file_range = from_proto::file_range(&snap, params.text_document, range)?;
let info = match snap.analysis.hover(&snap.config.hover(), file_range)? {
None => return Ok(None),
Some(info) => info,
};
let line_index = snap.file_line_index(file_range.file_id)?;
let range = to_proto::range(&line_index, info.range);
let markup_kind = snap.config.hover().format;
let hover = lsp_ext::Hover {
hover: lsp_types::Hover {
contents: HoverContents::Markup(to_proto::markup_content(
info.info.markup,
markup_kind,
)),
range: Some(range),
},
actions: if snap.config.hover_actions().none() {
Vec::new()
} else {
prepare_hover_actions(&snap, &info.info.actions)
},
};
Ok(Some(hover))
}
pub(crate) fn handle_prepare_rename(
snap: GlobalStateSnapshot,
params: lsp_types::TextDocumentPositionParams,
) -> Result<Option<PrepareRenameResponse>> {
let _p = profile::span("handle_prepare_rename");
let position = from_proto::file_position(&snap, params)?;
let change = snap.analysis.prepare_rename(position)?.map_err(to_proto::rename_error)?;
let line_index = snap.file_line_index(position.file_id)?;
let range = to_proto::range(&line_index, change.range);
Ok(Some(PrepareRenameResponse::Range(range)))
}
pub(crate) fn handle_rename(
snap: GlobalStateSnapshot,
params: RenameParams,
) -> Result<Option<WorkspaceEdit>> {
let _p = profile::span("handle_rename");
let position = from_proto::file_position(&snap, params.text_document_position)?;
let mut change =
snap.analysis.rename(position, ¶ms.new_name)?.map_err(to_proto::rename_error)?;
// this is kind of a hack to prevent double edits from happening when moving files
// When a module gets renamed by renaming the mod declaration this causes the file to move
// which in turn will trigger a WillRenameFiles request to the server for which we reply with a
// a second identical set of renames, the client will then apply both edits causing incorrect edits
// with this we only emit source_file_edits in the WillRenameFiles response which will do the rename instead
// See https://github.com/microsoft/vscode-languageserver-node/issues/752 for more info
if !change.file_system_edits.is_empty() && snap.config.will_rename() {
change.source_file_edits.clear();
}