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
|
//! This module is responsible for implementing handlers for Lanuage Server Protocol.
//! The majority of requests are fulfilled by calling into the `ra_ide` crate.
use std::{
collections::hash_map::Entry,
fmt::Write as _,
io::Write as _,
process::{self, Stdio},
};
use lsp_server::ErrorCode;
use lsp_types::{
CallHierarchyIncomingCall, CallHierarchyIncomingCallsParams, CallHierarchyItem,
CallHierarchyOutgoingCall, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams,
CodeAction, CodeActionOrCommand, CodeActionResponse, CodeLens, Command, CompletionItem,
Diagnostic, DocumentFormattingParams, DocumentHighlight, DocumentSymbol, FoldingRange,
FoldingRangeParams, Hover, HoverContents, Location, MarkupContent, MarkupKind, Position,
PrepareRenameResponse, Range, RenameParams, SymbolInformation, TextDocumentIdentifier,
TextEdit, WorkspaceEdit,
};
use ra_ide::{
AssistId, FileId, FilePosition, FileRange, Query, RangeInfo, Runnable, RunnableKind,
SearchScope,
};
use ra_prof::profile;
use ra_syntax::{AstNode, SyntaxKind, TextRange, TextUnit};
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use serde_json::to_value;
use crate::{
cargo_target_spec::{runnable_args, CargoTargetSpec},
conv::{
to_call_hierarchy_item, to_location, Conv, ConvWith, FoldConvCtx, MapConvWith, TryConvWith,
TryConvWithToVec,
},
diagnostics::DiagnosticTask,
from_json,
req::{self, Decoration, InlayHint, InlayHintsParams, InlayKind},
world::WorldSnapshot,
LspError, Result,
};
pub fn handle_analyzer_status(world: WorldSnapshot, _: ()) -> Result<String> {
let _p = profile("handle_analyzer_status");
let mut buf = world.status();
writeln!(buf, "\n\nrequests:").unwrap();
let requests = world.latest_requests.read();
for (is_last, r) in requests.iter() {
let mark = if is_last { "*" } else { " " };
writeln!(buf, "{}{:4} {:<36}{}ms", mark, r.id, r.method, r.duration.as_millis()).unwrap();
}
Ok(buf)
}
pub fn handle_syntax_tree(world: WorldSnapshot, params: req::SyntaxTreeParams) -> Result<String> {
let _p = profile("handle_syntax_tree");
let id = params.text_document.try_conv_with(&world)?;
let line_index = world.analysis().file_line_index(id)?;
let text_range = params.range.map(|p| p.conv_with(&line_index));
let res = world.analysis().syntax_tree(id, text_range)?;
Ok(res)
}
pub fn handle_expand_macro(
world: WorldSnapshot,
params: req::ExpandMacroParams,
) -> Result<Option<req::ExpandedMacro>> {
let _p = profile("handle_expand_macro");
let file_id = params.text_document.try_conv_with(&world)?;
let line_index = world.analysis().file_line_index(file_id)?;
let offset = params.position.map(|p| p.conv_with(&line_index));
match offset {
None => Ok(None),
Some(offset) => {
let res = world.analysis().expand_macro(FilePosition { file_id, offset })?;
Ok(res.map(|it| req::ExpandedMacro { name: it.name, expansion: it.expansion }))
}
}
}
pub fn handle_selection_range(
world: WorldSnapshot,
params: req::SelectionRangeParams,
) -> Result<Vec<req::SelectionRange>> {
let _p = profile("handle_selection_range");
let file_id = params.text_document.try_conv_with(&world)?;
let line_index = world.analysis().file_line_index(file_id)?;
params
.positions
.into_iter()
.map_conv_with(&line_index)
.map(|position| {
let mut ranges = Vec::new();
{
let mut range = TextRange::from_to(position, position);
loop {
ranges.push(range);
let frange = FileRange { file_id, range };
let next = world.analysis().extend_selection(frange)?;
if next == range {
break;
} else {
range = next
}
}
}
let mut range = req::SelectionRange {
range: ranges.last().unwrap().conv_with(&line_index),
parent: None,
};
for r in ranges.iter().rev().skip(1) {
range = req::SelectionRange {
range: r.conv_with(&line_index),
parent: Some(Box::new(range)),
}
}
Ok(range)
})
.collect()
}
pub fn handle_find_matching_brace(
world: WorldSnapshot,
params: req::FindMatchingBraceParams,
) -> Result<Vec<Position>> {
let _p = profile("handle_find_matching_brace");
let file_id = params.text_document.try_conv_with(&world)?;
let line_index = world.analysis().file_line_index(file_id)?;
let res = params
.offsets
.into_iter()
.map_conv_with(&line_index)
.map(|offset| {
if let Ok(Some(matching_brace_offset)) =
world.analysis().matching_brace(FilePosition { file_id, offset })
{
matching_brace_offset
} else {
offset
}
})
.map_conv_with(&line_index)
.collect();
Ok(res)
}
pub fn handle_join_lines(
world: WorldSnapshot,
params: req::JoinLinesParams,
) -> Result<req::SourceChange> {
let _p = profile("handle_join_lines");
let frange = (¶ms.text_document, params.range).try_conv_with(&world)?;
world.analysis().join_lines(frange)?.try_conv_with(&world)
}
pub fn handle_on_enter(
world: WorldSnapshot,
params: req::TextDocumentPositionParams,
) -> Result<Option<req::SourceChange>> {
let _p = profile("handle_on_enter");
let position = params.try_conv_with(&world)?;
match world.analysis().on_enter(position)? {
None => Ok(None),
Some(edit) => Ok(Some(edit.try_conv_with(&world)?)),
}
}
// Don't forget to add new trigger characters to `ServerCapabilities` in `caps.rs`.
pub fn handle_on_type_formatting(
world: WorldSnapshot,
params: req::DocumentOnTypeFormattingParams,
) -> Result<Option<Vec<TextEdit>>> {
let _p = profile("handle_on_type_formatting");
let mut position = params.text_document_position.try_conv_with(&world)?;
let line_index = world.analysis().file_line_index(position.file_id)?;
let line_endings = world.file_line_endings(position.file_id);
// in `ra_ide`, the `on_type` invariant is that
// `text.char_at(position) == typed_char`.
position.offset -= TextUnit::of_char('.');
let char_typed = params.ch.chars().next().unwrap_or('\0');
// 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 = world.analysis().on_char_typed(position, char_typed)?;
let mut edit = match edit {
Some(it) => it,
None => return Ok(None),
};
// This should be a single-file edit
let edit = edit.source_file_edits.pop().unwrap();
let change: Vec<TextEdit> = edit.edit.conv_with((&line_index, line_endings));
Ok(Some(change))
}
pub fn handle_document_symbol(
world: WorldSnapshot,
params: req::DocumentSymbolParams,
) -> Result<Option<req::DocumentSymbolResponse>> {
let _p = profile("handle_document_symbol");
let file_id = params.text_document.try_conv_with(&world)?;
let line_index = world.analysis().file_line_index(file_id)?;
let mut parents: Vec<(DocumentSymbol, Option<usize>)> = Vec::new();
for symbol in world.analysis().file_structure(file_id)? {
let doc_symbol = DocumentSymbol {
name: symbol.label,
detail: symbol.detail,
kind: symbol.kind.conv(),
deprecated: Some(symbol.deprecated),
range: symbol.node_range.conv_with(&line_index),
selection_range: symbol.navigation_range.conv_with(&line_index),
children: None,
};
parents.push((doc_symbol, symbol.parent));
}
let mut res = Vec::new();
while let Some((node, parent)) = parents.pop() {
match parent {
None => res.push(node),
Some(i) => {
let children = &mut parents[i].0.children;
if children.is_none() {
*children = Some(Vec::new());
}
children.as_mut().unwrap().push(node);
}
}
}
Ok(Some(res.into()))
}
pub fn handle_workspace_symbol(
world: WorldSnapshot,
params: req::WorkspaceSymbolParams,
) -> Result<Option<Vec<SymbolInformation>>> {
let _p = profile("handle_workspace_symbol");
let all_symbols = params.query.contains('#');
let libs = params.query.contains('*');
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(128);
q
};
let mut res = exec_query(&world, query)?;
if res.is_empty() && !all_symbols {
let mut query = Query::new(params.query);
query.limit(128);
res = exec_query(&world, query)?;
}
return Ok(Some(res));
fn exec_query(world: &WorldSnapshot, query: Query) -> Result<Vec<SymbolInformation>> {
let mut res = Vec::new();
for nav in world.analysis().symbol_search(query)? {
let info = SymbolInformation {
name: nav.name().to_string(),
kind: nav.kind().conv(),
location: nav.try_conv_with(world)?,
container_name: nav.container_name().map(|v| v.to_string()),
deprecated: None,
};
res.push(info);
}
Ok(res)
}
}
pub fn handle_goto_definition(
world: WorldSnapshot,
params: req::TextDocumentPositionParams,
) -> Result<Option<req::GotoDefinitionResponse>> {
let _p = profile("handle_goto_definition");
let position = params.try_conv_with(&world)?;
let nav_info = match world.analysis().goto_definition(position)? {
None => return Ok(None),
Some(it) => it,
};
let res = (position.file_id, nav_info).try_conv_with(&world)?;
Ok(Some(res))
}
pub fn handle_goto_implementation(
world: WorldSnapshot,
params: req::TextDocumentPositionParams,
) -> Result<Option<req::GotoImplementationResponse>> {
let _p = profile("handle_goto_implementation");
let position = params.try_conv_with(&world)?;
let nav_info = match world.analysis().goto_implementation(position)? {
None => return Ok(None),
Some(it) => it,
};
let res = (position.file_id, nav_info).try_conv_with(&world)?;
Ok(Some(res))
}
pub fn handle_goto_type_definition(
world: WorldSnapshot,
params: req::TextDocumentPositionParams,
) -> Result<Option<req::GotoTypeDefinitionResponse>> {
let _p = profile("handle_goto_type_definition");
let position = params.try_conv_with(&world)?;
let nav_info = match world.analysis().goto_type_definition(position)? {
None => return Ok(None),
Some(it) => it,
};
let res = (position.file_id, nav_info).try_conv_with(&world)?;
Ok(Some(res))
}
pub fn handle_parent_module(
world: WorldSnapshot,
params: req::TextDocumentPositionParams,
) -> Result<Vec<Location>> {
let _p = profile("handle_parent_module");
let position = params.try_conv_with(&world)?;
world.analysis().parent_module(position)?.iter().try_conv_with_to_vec(&world)
}
pub fn handle_runnables(
world: WorldSnapshot,
params: req::RunnablesParams,
) -> Result<Vec<req::Runnable>> {
let _p = profile("handle_runnables");
let file_id = params.text_document.try_conv_with(&world)?;
let line_index = world.analysis().file_line_index(file_id)?;
let offset = params.position.map(|it| it.conv_with(&line_index));
let mut res = Vec::new();
let workspace_root = world.workspace_root_for(file_id);
for runnable in world.analysis().runnables(file_id)? {
if let Some(offset) = offset {
if !runnable.range.contains_inclusive(offset) {
continue;
}
}
res.push(to_lsp_runnable(&world, file_id, runnable)?);
}
let mut check_args = vec!["check".to_string()];
let label;
match CargoTargetSpec::for_file(&world, file_id)? {
Some(spec) => {
label = format!("cargo check -p {}", spec.package);
spec.push_to(&mut check_args);
}
None => {
label = "cargo check --all".to_string();
check_args.push("--all".to_string())
}
}
// Always add `cargo check`.
res.push(req::Runnable {
range: Default::default(),
label,
bin: "cargo".to_string(),
args: check_args,
env: FxHashMap::default(),
cwd: workspace_root.map(|root| root.to_string_lossy().to_string()),
});
Ok(res)
}
pub fn handle_decorations(
world: WorldSnapshot,
params: TextDocumentIdentifier,
) -> Result<Vec<Decoration>> {
let _p = profile("handle_decorations");
let file_id = params.try_conv_with(&world)?;
highlight(&world, file_id)
}
pub fn handle_completion(
world: WorldSnapshot,
params: req::CompletionParams,
) -> Result<Option<req::CompletionResponse>> {
let _p = profile("handle_completion");
let position = params.text_document_position.try_conv_with(&world)?;
let completion_triggered_after_single_colon = {
let mut res = false;
if let Some(ctx) = params.context {
if ctx.trigger_character.unwrap_or_default() == ":" {
let source_file = world.analysis().parse(position.file_id)?;
let syntax = source_file.syntax();
let text = syntax.text();
if let Some(next_char) = text.char_at(position.offset) {
let diff = TextUnit::of_char(next_char) + TextUnit::of_char(':');
let prev_char = position.offset - diff;
if text.char_at(prev_char) != Some(':') {
res = true;
}
}
}
}
res
};
if completion_triggered_after_single_colon {
return Ok(None);
}
let items = match world.analysis().completions(position)? {
None => return Ok(None),
Some(items) => items,
};
let line_index = world.analysis().file_line_index(position.file_id)?;
let line_endings = world.file_line_endings(position.file_id);
let items: Vec<CompletionItem> =
items.into_iter().map(|item| item.conv_with((&line_index, line_endings))).collect();
Ok(Some(items.into()))
}
pub fn handle_folding_range(
world: WorldSnapshot,
params: FoldingRangeParams,
) -> Result<Option<Vec<FoldingRange>>> {
let _p = profile("handle_folding_range");
let file_id = params.text_document.try_conv_with(&world)?;
let folds = world.analysis().folding_ranges(file_id)?;
let text = world.analysis().file_text(file_id)?;
let line_index = world.analysis().file_line_index(file_id)?;
let ctx = FoldConvCtx {
text: &text,
line_index: &line_index,
line_folding_only: world.options.line_folding_only,
};
let res = Some(folds.into_iter().map_conv_with(&ctx).collect());
Ok(res)
}
pub fn handle_signature_help(
world: WorldSnapshot,
params: req::TextDocumentPositionParams,
) -> Result<Option<req::SignatureHelp>> {
let _p = profile("handle_signature_help");
let position = params.try_conv_with(&world)?;
if let Some(call_info) = world.analysis().call_info(position)? {
let active_parameter = call_info.active_parameter.map(|it| it as i64);
let sig_info = call_info.signature.conv();
Ok(Some(req::SignatureHelp {
signatures: vec![sig_info],
active_signature: Some(0),
active_parameter,
}))
} else {
Ok(None)
}
}
pub fn handle_hover(
world: WorldSnapshot,
params: req::TextDocumentPositionParams,
) -> Result<Option<Hover>> {
let _p = profile("handle_hover");
let position = params.try_conv_with(&world)?;
let info = match world.analysis().hover(position)? {
None => return Ok(None),
Some(info) => info,
};
let line_index = world.analysis.file_line_index(position.file_id)?;
let range = info.range.conv_with(&line_index);
let res = Hover {
contents: HoverContents::Markup(MarkupContent {
kind: MarkupKind::Markdown,
value: crate::markdown::format_docs(&info.info.to_markup()),
}),
range: Some(range),
};
Ok(Some(res))
}
pub fn handle_prepare_rename(
world: WorldSnapshot,
params: req::TextDocumentPositionParams,
) -> Result<Option<PrepareRenameResponse>> {
let _p = profile("handle_prepare_rename");
let position = params.try_conv_with(&world)?;
let optional_change = world.analysis().rename(position, "dummy")?;
let range = match optional_change {
None => return Ok(None),
Some(it) => it.range,
};
let file_id = params.text_document.try_conv_with(&world)?;
let line_index = world.analysis().file_line_index(file_id)?;
let range = range.conv_with(&line_index);
Ok(Some(PrepareRenameResponse::Range(range)))
}
pub fn handle_rename(world: WorldSnapshot, params: RenameParams) -> Result<Option<WorkspaceEdit>> {
let _p = profile("handle_rename");
let position = params.text_document_position.try_conv_with(&world)?;
if params.new_name.is_empty() {
return Err(LspError::new(
ErrorCode::InvalidParams as i32,
"New Name cannot be empty".into(),
)
.into());
}
let optional_change = world.analysis().rename(position, &*params.new_name)?;
let change = match optional_change {
None => return Ok(None),
Some(it) => it.info,
};
let source_change_req = change.try_conv_with(&world)?;
Ok(Some(source_change_req.workspace_edit))
}
pub fn handle_references(
world: WorldSnapshot,
params: req::ReferenceParams,
) -> Result<Option<Vec<Location>>> {
let _p = profile("handle_references");
let position = params.text_document_position.try_conv_with(&world)?;
let refs = match world.analysis().find_all_refs(position, None)? {
None => return Ok(None),
Some(refs) => refs,
};
let locations = if params.context.include_declaration {
refs.into_iter()
.filter_map(|reference| {
let line_index =
world.analysis().file_line_index(reference.file_range.file_id).ok()?;
to_location(
reference.file_range.file_id,
reference.file_range.range,
&world,
&line_index,
)
.ok()
})
.collect()
} else {
// Only iterate over the references if include_declaration was false
refs.references()
.iter()
.filter_map(|reference| {
let line_index =
world.analysis().file_line_index(reference.file_range.file_id).ok()?;
to_location(
reference.file_range.file_id,
reference.file_range.range,
&world,
&line_index,
)
.ok()
})
.collect()
};
Ok(Some(locations))
}
pub fn handle_formatting(
world: WorldSnapshot,
params: DocumentFormattingParams,
) -> Result<Option<Vec<TextEdit>>> {
let _p = profile("handle_formatting");
let file_id = params.text_document.try_conv_with(&world)?;
let file = world.analysis().file_text(file_id)?;
let crate_ids = world.analysis().crate_for(file_id)?;
let file_line_index = world.analysis().file_line_index(file_id)?;
let end_position = TextUnit::of_str(&file).conv_with(&file_line_index);
let mut rustfmt = process::Command::new("rustfmt");
rustfmt.args(&world.options.rustfmt_args);
if let Some(&crate_id) = crate_ids.first() {
// Assume all crates are in the same edition
let edition = world.analysis().crate_edition(crate_id)?;
rustfmt.args(&["--edition", &edition.to_string()]);
}
if let Ok(path) = params.text_document.uri.to_file_path() {
if let Some(parent) = path.parent() {
rustfmt.current_dir(parent);
}
}
let mut rustfmt = rustfmt.stdin(Stdio::piped()).stdout(Stdio::piped()).spawn()?;
rustfmt.stdin.as_mut().unwrap().write_all(file.as_bytes())?;
let output = rustfmt.wait_with_output()?;
let captured_stdout = String::from_utf8(output.stdout)?;
if !output.status.success() {
match output.status.code() {
Some(1) => {
// While `rustfmt` doesn't have a specific exit code for parse errors this is the
// likely cause exiting with 1. Most Language Servers swallow parse errors on
// formatting because otherwise an error is surfaced to the user on top of the
// syntax error diagnostics they're already receiving. This is especially jarring
// if they have format on save enabled.
log::info!("rustfmt exited with status 1, assuming parse error and ignoring");
return Ok(None);
}
_ => {
// Something else happened - e.g. `rustfmt` is missing or caught a signal
return Err(LspError::new(
-32900,
format!(
r#"rustfmt exited with:
Status: {}
stdout: {}"#,
output.status, captured_stdout,
),
)
.into());
}
}
}
Ok(Some(vec![TextEdit {
range: Range::new(Position::new(0, 0), end_position),
new_text: captured_stdout,
}]))
}
pub fn handle_code_action(
world: WorldSnapshot,
params: req::CodeActionParams,
) -> Result<Option<CodeActionResponse>> {
let _p = profile("handle_code_action");
let file_id = params.text_document.try_conv_with(&world)?;
let line_index = world.analysis().file_line_index(file_id)?;
let range = params.range.conv_with(&line_index);
let diagnostics = world.analysis().diagnostics(file_id)?;
let mut res = CodeActionResponse::default();
let fixes_from_diagnostics = diagnostics
.into_iter()
.filter_map(|d| Some((d.range, d.fix?)))
.filter(|(diag_range, _fix)| diag_range.intersection(&range).is_some())
.map(|(_range, fix)| fix);
for source_edit in fixes_from_diagnostics {
let title = source_edit.label.clone();
let edit = source_edit.try_conv_with(&world)?;
let command = Command {
title,
command: "rust-analyzer.applySourceChange".to_string(),
arguments: Some(vec![to_value(edit).unwrap()]),
};
let action = CodeAction {
title: command.title.clone(),
kind: None,
diagnostics: None,
edit: None,
command: Some(command),
is_preferred: None,
};
res.push(action.into());
}
for fix in world.check_fixes.get(&file_id).into_iter().flatten() {
let fix_range = fix.range.conv_with(&line_index);
if fix_range.intersection(&range).is_none() {
continue;
}
res.push(fix.action.clone());
}
let mut groups = FxHashMap::default();
for assist in world.analysis().assists(FileRange { file_id, range })?.into_iter() {
let arg = to_value(assist.source_change.try_conv_with(&world)?)?;
let (command, title, arg) = match assist.group_label {
None => ("rust-analyzer.applySourceChange", assist.label.clone(), arg),
// Group all assists with the same `group_label` into a single CodeAction.
Some(group_label) => {
match groups.entry(group_label.clone()) {
Entry::Occupied(entry) => {
let idx: usize = *entry.get();
match &mut res[idx] {
CodeActionOrCommand::CodeAction(CodeAction {
command: Some(Command { arguments: Some(arguments), .. }),
..
}) => match arguments.as_mut_slice() {
[serde_json::Value::Array(arguments)] => arguments.push(arg),
_ => panic!("invalid group"),
},
_ => panic!("invalid group"),
}
continue;
}
Entry::Vacant(entry) => {
entry.insert(res.len());
}
}
("rust-analyzer.selectAndApplySourceChange", group_label, to_value(vec![arg])?)
}
};
let command = Command {
title: assist.label.clone(),
command: command.to_string(),
arguments: Some(vec![arg]),
};
let kind = match assist.id {
AssistId("introduce_variable") => Some("refactor.extract.variable".to_string()),
AssistId("add_custom_impl") => Some("refactor.rewrite.add_custom_impl".to_string()),
_ => None,
};
let action = CodeAction {
title,
kind,
diagnostics: None,
edit: None,
command: Some(command),
is_preferred: None,
};
res.push(action.into());
}
Ok(Some(res))
}
pub fn handle_code_lens(
world: WorldSnapshot,
params: req::CodeLensParams,
) -> Result<Option<Vec<CodeLens>>> {
let _p = profile("handle_code_lens");
let file_id = params.text_document.try_conv_with(&world)?;
let line_index = world.analysis().file_line_index(file_id)?;
let mut lenses: Vec<CodeLens> = Default::default();
// Gather runnables
for runnable in world.analysis().runnables(file_id)? {
let title = match &runnable.kind {
RunnableKind::Test { .. } | RunnableKind::TestMod { .. } => "▶️\u{fe0e}Run Test",
RunnableKind::Bench { .. } => "Run Bench",
RunnableKind::Bin => "Run",
}
.to_string();
let r = to_lsp_runnable(&world, file_id, runnable)?;
let lens = CodeLens {
range: r.range,
command: Some(Command {
title,
command: "rust-analyzer.runSingle".into(),
arguments: Some(vec![to_value(r).unwrap()]),
}),
data: None,
};
lenses.push(lens);
}
// Handle impls
lenses.extend(
world
.analysis()
.file_structure(file_id)?
.into_iter()
.filter(|it| match it.kind {
SyntaxKind::TRAIT_DEF | SyntaxKind::STRUCT_DEF | SyntaxKind::ENUM_DEF => true,
_ => false,
})
.map(|it| {
let range = it.node_range.conv_with(&line_index);
let pos = range.start;
let lens_params =
req::TextDocumentPositionParams::new(params.text_document.clone(), pos);
CodeLens {
range,
command: None,
data: Some(to_value(CodeLensResolveData::Impls(lens_params)).unwrap()),
}
}),
);
Ok(Some(lenses))
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
enum CodeLensResolveData {
Impls(req::TextDocumentPositionParams),
}
pub fn handle_code_lens_resolve(world: WorldSnapshot, code_lens: CodeLens) -> Result<CodeLens> {
let _p = profile("handle_code_lens_resolve");
let data = code_lens.data.unwrap();
let resolve = from_json::<Option<CodeLensResolveData>>("CodeLensResolveData", data)?;
match resolve {
Some(CodeLensResolveData::Impls(lens_params)) => {
let locations: Vec<Location> =
match handle_goto_implementation(world, lens_params.clone())? {
Some(req::GotoDefinitionResponse::Scalar(loc)) => vec![loc],
Some(req::GotoDefinitionResponse::Array(locs)) => locs,
Some(req::GotoDefinitionResponse::Link(links)) => links
.into_iter()
.map(|link| Location::new(link.target_uri, link.target_selection_range))
.collect(),
_ => vec![],
};
let title = if locations.len() == 1 {
"1 implementation".into()
} else {
format!("{} implementations", locations.len())
};
// We cannot use the 'editor.action.showReferences' command directly
// because that command requires vscode types which we convert in the handler
// on the client side.
let cmd = Command {
title,
command: "rust-analyzer.showReferences".into(),
arguments: Some(vec![
to_value(&lens_params.text_document.uri).unwrap(),
to_value(code_lens.range.start).unwrap(),
to_value(locations).unwrap(),
]),
};
Ok(CodeLens { range: code_lens.range, command: Some(cmd), data: None })
}
None => Ok(CodeLens {
range: code_lens.range,
command: Some(Command { title: "Error".into(), ..Default::default() }),
data: None,
}),
}
}
pub fn handle_document_highlight(
world: WorldSnapshot,
params: req::TextDocumentPositionParams,
) -> Result<Option<Vec<DocumentHighlight>>> {
let _p = profile("handle_document_highlight");
let file_id = params.text_document.try_conv_with(&world)?;
let line_index = world.analysis().file_line_index(file_id)?;
let refs = match world
.analysis()
.find_all_refs(params.try_conv_with(&world)?, Some(SearchScope::single_file(file_id)))?
{
None => return Ok(None),
Some(refs) => refs,
};
Ok(Some(
refs.into_iter()
.filter(|reference| reference.file_range.file_id == file_id)
.map(|reference| DocumentHighlight {
range: reference.file_range.range.conv_with(&line_index),
kind: reference.access.map(|it| it.conv()),
})
.collect(),
))
}
pub fn handle_ssr(world: WorldSnapshot, params: req::SsrParams) -> Result<req::SourceChange> {
let _p = profile("handle_ssr");
world.analysis().structural_search_replace(¶ms.arg)??.try_conv_with(&world)
}
pub fn publish_diagnostics(world: &WorldSnapshot, file_id: FileId) -> Result<DiagnosticTask> {
let _p = profile("publish_diagnostics");
let line_index = world.analysis().file_line_index(file_id)?;
let diagnostics: Vec<Diagnostic> = world
.analysis()
.diagnostics(file_id)?
.into_iter()
.map(|d| Diagnostic {
range: d.range.conv_with(&line_index),
severity: Some(d.severity.conv()),
code: None,
source: Some("rust-analyzer".to_string()),
message: d.message,
related_information: None,
tags: None,
})
.collect();
Ok(DiagnosticTask::SetNative(file_id, diagnostics))
}
pub fn publish_decorations(
world: &WorldSnapshot,
file_id: FileId,
) -> Result<req::PublishDecorationsParams> {
let _p = profile("publish_decorations");
let uri = world.file_id_to_uri(file_id)?;
Ok(req::PublishDecorationsParams { uri, decorations: highlight(&world, file_id)? })
}
fn to_lsp_runnable(
world: &WorldSnapshot,
file_id: FileId,
runnable: Runnable,
) -> Result<req::Runnable> {
let args = runnable_args(world, file_id, &runnable.kind)?;
let line_index = world.analysis().file_line_index(file_id)?;
let label = match &runnable.kind {
RunnableKind::Test { test_id } => format!("test {}", test_id),
RunnableKind::TestMod { path } => format!("test-mod {}", path),
RunnableKind::Bench { test_id } => format!("bench {}", test_id),
RunnableKind::Bin => "run binary".to_string(),
};
Ok(req::Runnable {
range: runnable.range.conv_with(&line_index),
label,
bin: "cargo".to_string(),
args,
env: {
let mut m = FxHashMap::default();
m.insert("RUST_BACKTRACE".to_string(), "short".to_string());
m
},
cwd: world.workspace_root_for(file_id).map(|root| root.to_string_lossy().to_string()),
})
}
fn highlight(world: &WorldSnapshot, file_id: FileId) -> Result<Vec<Decoration>> {
let line_index = world.analysis().file_line_index(file_id)?;
let res = world
.analysis()
.highlight(file_id)?
.into_iter()
.map(|h| Decoration {
range: h.range.conv_with(&line_index),
tag: h.tag,
binding_hash: h.binding_hash.map(|x| x.to_string()),
})
.collect();
Ok(res)
}
pub fn handle_inlay_hints(
world: WorldSnapshot,
params: InlayHintsParams,
) -> Result<Vec<InlayHint>> {
let _p = profile("handle_inlay_hints");
let file_id = params.text_document.try_conv_with(&world)?;
let analysis = world.analysis();
let line_index = analysis.file_line_index(file_id)?;
Ok(analysis
.inlay_hints(file_id, world.options.max_inlay_hint_length)?
.into_iter()
.map(|api_type| InlayHint {
label: api_type.label.to_string(),
range: api_type.range.conv_with(&line_index),
kind: match api_type.kind {
ra_ide::InlayKind::TypeHint => InlayKind::TypeHint,
ra_ide::InlayKind::ParameterHint => InlayKind::ParameterHint,
},
})
.collect())
}
pub fn handle_call_hierarchy_prepare(
world: WorldSnapshot,
params: CallHierarchyPrepareParams,
) -> Result<Option<Vec<CallHierarchyItem>>> {
let _p = profile("handle_call_hierarchy_prepare");
let position = params.text_document_position_params.try_conv_with(&world)?;
let file_id = position.file_id;
let nav_info = match world.analysis().call_hierarchy(position)? {
None => return Ok(None),
Some(it) => it,
};
let line_index = world.analysis().file_line_index(file_id)?;
let RangeInfo { range, info: navs } = nav_info;
let res = navs
.into_iter()
.filter(|it| it.kind() == SyntaxKind::FN_DEF)
.filter_map(|it| to_call_hierarchy_item(file_id, range, &world, &line_index, it).ok())
.collect();
Ok(Some(res))
}
pub fn handle_call_hierarchy_incoming(
world: WorldSnapshot,
params: CallHierarchyIncomingCallsParams,
) -> Result<Option<Vec<CallHierarchyIncomingCall>>> {
let _p = profile("handle_call_hierarchy_incoming");
let item = params.item;
let doc = TextDocumentIdentifier::new(item.uri);
let frange: FileRange = (&doc, item.range).try_conv_with(&world)?;
let fpos = FilePosition { file_id: frange.file_id, offset: frange.range.start() };
let call_items = match world.analysis().incoming_calls(fpos)? {
None => return Ok(None),
Some(it) => it,
};
let mut res = vec![];
for call_item in call_items.into_iter() {
let file_id = call_item.target.file_id();
let line_index = world.analysis().file_line_index(file_id)?;
let range = call_item.target.range();
let item = to_call_hierarchy_item(file_id, range, &world, &line_index, call_item.target)?;
res.push(CallHierarchyIncomingCall {
from: item,
from_ranges: call_item.ranges.iter().map(|it| it.conv_with(&line_index)).collect(),
});
}
Ok(Some(res))
}
pub fn handle_call_hierarchy_outgoing(
world: WorldSnapshot,
params: CallHierarchyOutgoingCallsParams,
) -> Result<Option<Vec<CallHierarchyOutgoingCall>>> {
let _p = profile("handle_call_hierarchy_outgoing");
let item = params.item;
let doc = TextDocumentIdentifier::new(item.uri);
let frange: FileRange = (&doc, item.range).try_conv_with(&world)?;
let fpos = FilePosition { file_id: frange.file_id, offset: frange.range.start() };
let call_items = match world.analysis().outgoing_calls(fpos)? {
None => return Ok(None),
Some(it) => it,
};
let mut res = vec![];
for call_item in call_items.into_iter() {
let file_id = call_item.target.file_id();
let line_index = world.analysis().file_line_index(file_id)?;
let range = call_item.target.range();
let item = to_call_hierarchy_item(file_id, range, &world, &line_index, call_item.target)?;
res.push(CallHierarchyOutgoingCall {
to: item,
from_ranges: call_item.ranges.iter().map(|it| it.conv_with(&line_index)).collect(),
});
}
Ok(Some(res))
}
|