1 //! Conversion of rust-analyzer specific types to lsp_types equivalents.
2 use std::{
3 iter::once,
4 path,
5 sync::atomic::{AtomicU32, Ordering},
6 };
7
8 use ide::{
9 Annotation, AnnotationKind, Assist, AssistKind, CallInfo, Cancellable, CompletionItem,
10 CompletionItemKind, CompletionRelevance, Documentation, FileId, FileRange, FileSystemEdit,
11 Fold, FoldKind, Highlight, HlMod, HlOperator, HlPunct, HlRange, HlTag, Indel, InlayHint,
12 InlayKind, Markup, NavigationTarget, ReferenceCategory, RenameError, Runnable, Severity,
13 SourceChange, StructureNodeKind, SymbolKind, TextEdit, TextRange, TextSize,
14 };
15 use itertools::Itertools;
16 use serde_json::to_value;
17 use vfs::AbsPath;
18
19 use crate::{
20 cargo_target_spec::CargoTargetSpec,
21 config::Config,
22 global_state::GlobalStateSnapshot,
23 line_index::{LineEndings, LineIndex, OffsetEncoding},
24 lsp_ext,
25 lsp_utils::invalid_params_error,
26 semantic_tokens, Result,
27 };
28
position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position29 pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position {
30 let line_col = line_index.index.line_col(offset);
31 match line_index.encoding {
32 OffsetEncoding::Utf8 => lsp_types::Position::new(line_col.line, line_col.col),
33 OffsetEncoding::Utf16 => {
34 let line_col = line_index.index.to_utf16(line_col);
35 lsp_types::Position::new(line_col.line, line_col.col)
36 }
37 }
38 }
39
range(line_index: &LineIndex, range: TextRange) -> lsp_types::Range40 pub(crate) fn range(line_index: &LineIndex, range: TextRange) -> lsp_types::Range {
41 let start = position(line_index, range.start());
42 let end = position(line_index, range.end());
43 lsp_types::Range::new(start, end)
44 }
45
symbol_kind(symbol_kind: SymbolKind) -> lsp_types::SymbolKind46 pub(crate) fn symbol_kind(symbol_kind: SymbolKind) -> lsp_types::SymbolKind {
47 match symbol_kind {
48 SymbolKind::Function => lsp_types::SymbolKind::FUNCTION,
49 SymbolKind::Struct => lsp_types::SymbolKind::STRUCT,
50 SymbolKind::Enum => lsp_types::SymbolKind::ENUM,
51 SymbolKind::Variant => lsp_types::SymbolKind::ENUM_MEMBER,
52 SymbolKind::Trait => lsp_types::SymbolKind::INTERFACE,
53 SymbolKind::Macro
54 | SymbolKind::BuiltinAttr
55 | SymbolKind::Attribute
56 | SymbolKind::Derive => lsp_types::SymbolKind::FUNCTION,
57 SymbolKind::Module | SymbolKind::ToolModule => lsp_types::SymbolKind::MODULE,
58 SymbolKind::TypeAlias | SymbolKind::TypeParam => lsp_types::SymbolKind::TYPE_PARAMETER,
59 SymbolKind::Field => lsp_types::SymbolKind::FIELD,
60 SymbolKind::Static => lsp_types::SymbolKind::CONSTANT,
61 SymbolKind::Const => lsp_types::SymbolKind::CONSTANT,
62 SymbolKind::ConstParam => lsp_types::SymbolKind::CONSTANT,
63 SymbolKind::Impl => lsp_types::SymbolKind::OBJECT,
64 SymbolKind::Local
65 | SymbolKind::SelfParam
66 | SymbolKind::LifetimeParam
67 | SymbolKind::ValueParam
68 | SymbolKind::Label => lsp_types::SymbolKind::VARIABLE,
69 SymbolKind::Union => lsp_types::SymbolKind::STRUCT,
70 }
71 }
72
structure_node_kind(kind: StructureNodeKind) -> lsp_types::SymbolKind73 pub(crate) fn structure_node_kind(kind: StructureNodeKind) -> lsp_types::SymbolKind {
74 match kind {
75 StructureNodeKind::SymbolKind(symbol) => symbol_kind(symbol),
76 StructureNodeKind::Region => lsp_types::SymbolKind::NAMESPACE,
77 }
78 }
79
document_highlight_kind( category: ReferenceCategory, ) -> lsp_types::DocumentHighlightKind80 pub(crate) fn document_highlight_kind(
81 category: ReferenceCategory,
82 ) -> lsp_types::DocumentHighlightKind {
83 match category {
84 ReferenceCategory::Read => lsp_types::DocumentHighlightKind::READ,
85 ReferenceCategory::Write => lsp_types::DocumentHighlightKind::WRITE,
86 }
87 }
88
diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity89 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
90 match severity {
91 Severity::Error => lsp_types::DiagnosticSeverity::ERROR,
92 Severity::WeakWarning => lsp_types::DiagnosticSeverity::HINT,
93 }
94 }
95
documentation(documentation: Documentation) -> lsp_types::Documentation96 pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
97 let value = crate::markdown::format_docs(documentation.as_str());
98 let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
99 lsp_types::Documentation::MarkupContent(markup_content)
100 }
101
completion_item_kind( completion_item_kind: CompletionItemKind, ) -> lsp_types::CompletionItemKind102 pub(crate) fn completion_item_kind(
103 completion_item_kind: CompletionItemKind,
104 ) -> lsp_types::CompletionItemKind {
105 match completion_item_kind {
106 CompletionItemKind::Binding => lsp_types::CompletionItemKind::VARIABLE,
107 CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::STRUCT,
108 CompletionItemKind::Keyword => lsp_types::CompletionItemKind::KEYWORD,
109 CompletionItemKind::Method => lsp_types::CompletionItemKind::METHOD,
110 CompletionItemKind::Snippet => lsp_types::CompletionItemKind::SNIPPET,
111 CompletionItemKind::UnresolvedReference => lsp_types::CompletionItemKind::REFERENCE,
112 CompletionItemKind::SymbolKind(symbol) => match symbol {
113 SymbolKind::Attribute => lsp_types::CompletionItemKind::FUNCTION,
114 SymbolKind::Const => lsp_types::CompletionItemKind::CONSTANT,
115 SymbolKind::ConstParam => lsp_types::CompletionItemKind::TYPE_PARAMETER,
116 SymbolKind::Derive => lsp_types::CompletionItemKind::FUNCTION,
117 SymbolKind::Enum => lsp_types::CompletionItemKind::ENUM,
118 SymbolKind::Field => lsp_types::CompletionItemKind::FIELD,
119 SymbolKind::Function => lsp_types::CompletionItemKind::FUNCTION,
120 SymbolKind::Impl => lsp_types::CompletionItemKind::TEXT,
121 SymbolKind::Label => lsp_types::CompletionItemKind::VARIABLE,
122 SymbolKind::LifetimeParam => lsp_types::CompletionItemKind::TYPE_PARAMETER,
123 SymbolKind::Local => lsp_types::CompletionItemKind::VARIABLE,
124 SymbolKind::Macro => lsp_types::CompletionItemKind::FUNCTION,
125 SymbolKind::Module => lsp_types::CompletionItemKind::MODULE,
126 SymbolKind::SelfParam => lsp_types::CompletionItemKind::VALUE,
127 SymbolKind::Static => lsp_types::CompletionItemKind::VALUE,
128 SymbolKind::Struct => lsp_types::CompletionItemKind::STRUCT,
129 SymbolKind::Trait => lsp_types::CompletionItemKind::INTERFACE,
130 SymbolKind::TypeAlias => lsp_types::CompletionItemKind::STRUCT,
131 SymbolKind::TypeParam => lsp_types::CompletionItemKind::TYPE_PARAMETER,
132 SymbolKind::Union => lsp_types::CompletionItemKind::STRUCT,
133 SymbolKind::ValueParam => lsp_types::CompletionItemKind::VALUE,
134 SymbolKind::Variant => lsp_types::CompletionItemKind::ENUM_MEMBER,
135 SymbolKind::BuiltinAttr => lsp_types::CompletionItemKind::FUNCTION,
136 SymbolKind::ToolModule => lsp_types::CompletionItemKind::MODULE,
137 },
138 }
139 }
140
text_edit(line_index: &LineIndex, indel: Indel) -> lsp_types::TextEdit141 pub(crate) fn text_edit(line_index: &LineIndex, indel: Indel) -> lsp_types::TextEdit {
142 let range = range(line_index, indel.delete);
143 let new_text = match line_index.endings {
144 LineEndings::Unix => indel.insert,
145 LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
146 };
147 lsp_types::TextEdit { range, new_text }
148 }
149
completion_text_edit( line_index: &LineIndex, insert_replace_support: Option<lsp_types::Position>, indel: Indel, ) -> lsp_types::CompletionTextEdit150 pub(crate) fn completion_text_edit(
151 line_index: &LineIndex,
152 insert_replace_support: Option<lsp_types::Position>,
153 indel: Indel,
154 ) -> lsp_types::CompletionTextEdit {
155 let text_edit = text_edit(line_index, indel);
156 match insert_replace_support {
157 Some(cursor_pos) => lsp_types::InsertReplaceEdit {
158 new_text: text_edit.new_text,
159 insert: lsp_types::Range { start: text_edit.range.start, end: cursor_pos },
160 replace: text_edit.range,
161 }
162 .into(),
163 None => text_edit.into(),
164 }
165 }
166
snippet_text_edit( line_index: &LineIndex, is_snippet: bool, indel: Indel, ) -> lsp_ext::SnippetTextEdit167 pub(crate) fn snippet_text_edit(
168 line_index: &LineIndex,
169 is_snippet: bool,
170 indel: Indel,
171 ) -> lsp_ext::SnippetTextEdit {
172 let text_edit = text_edit(line_index, indel);
173 let insert_text_format =
174 if is_snippet { Some(lsp_types::InsertTextFormat::SNIPPET) } else { None };
175 lsp_ext::SnippetTextEdit {
176 range: text_edit.range,
177 new_text: text_edit.new_text,
178 insert_text_format,
179 annotation_id: None,
180 }
181 }
182
text_edit_vec( line_index: &LineIndex, text_edit: TextEdit, ) -> Vec<lsp_types::TextEdit>183 pub(crate) fn text_edit_vec(
184 line_index: &LineIndex,
185 text_edit: TextEdit,
186 ) -> Vec<lsp_types::TextEdit> {
187 text_edit.into_iter().map(|indel| self::text_edit(line_index, indel)).collect()
188 }
189
snippet_text_edit_vec( line_index: &LineIndex, is_snippet: bool, text_edit: TextEdit, ) -> Vec<lsp_ext::SnippetTextEdit>190 pub(crate) fn snippet_text_edit_vec(
191 line_index: &LineIndex,
192 is_snippet: bool,
193 text_edit: TextEdit,
194 ) -> Vec<lsp_ext::SnippetTextEdit> {
195 text_edit
196 .into_iter()
197 .map(|indel| self::snippet_text_edit(line_index, is_snippet, indel))
198 .collect()
199 }
200
completion_items( config: &Config, line_index: &LineIndex, tdpp: lsp_types::TextDocumentPositionParams, items: Vec<CompletionItem>, ) -> Vec<lsp_types::CompletionItem>201 pub(crate) fn completion_items(
202 config: &Config,
203 line_index: &LineIndex,
204 tdpp: lsp_types::TextDocumentPositionParams,
205 items: Vec<CompletionItem>,
206 ) -> Vec<lsp_types::CompletionItem> {
207 let max_relevance = items.iter().map(|it| it.relevance().score()).max().unwrap_or_default();
208 let mut res = Vec::with_capacity(items.len());
209 for item in items {
210 completion_item(&mut res, config, line_index, &tdpp, max_relevance, item)
211 }
212 res
213 }
214
completion_item( acc: &mut Vec<lsp_types::CompletionItem>, config: &Config, line_index: &LineIndex, tdpp: &lsp_types::TextDocumentPositionParams, max_relevance: u32, item: CompletionItem, )215 fn completion_item(
216 acc: &mut Vec<lsp_types::CompletionItem>,
217 config: &Config,
218 line_index: &LineIndex,
219 tdpp: &lsp_types::TextDocumentPositionParams,
220 max_relevance: u32,
221 item: CompletionItem,
222 ) {
223 let mut additional_text_edits = Vec::new();
224
225 // LSP does not allow arbitrary edits in completion, so we have to do a
226 // non-trivial mapping here.
227 let text_edit = {
228 let mut text_edit = None;
229 let source_range = item.source_range();
230 for indel in item.text_edit().iter() {
231 if indel.delete.contains_range(source_range) {
232 let insert_replace_support = config.insert_replace_support().then(|| tdpp.position);
233 text_edit = Some(if indel.delete == source_range {
234 self::completion_text_edit(line_index, insert_replace_support, indel.clone())
235 } else {
236 assert!(source_range.end() == indel.delete.end());
237 let range1 = TextRange::new(indel.delete.start(), source_range.start());
238 let range2 = source_range;
239 let indel1 = Indel::replace(range1, String::new());
240 let indel2 = Indel::replace(range2, indel.insert.clone());
241 additional_text_edits.push(self::text_edit(line_index, indel1));
242 self::completion_text_edit(line_index, insert_replace_support, indel2)
243 })
244 } else {
245 assert!(source_range.intersect(indel.delete).is_none());
246 let text_edit = self::text_edit(line_index, indel.clone());
247 additional_text_edits.push(text_edit);
248 }
249 }
250 text_edit.unwrap()
251 };
252
253 let mut lsp_item = lsp_types::CompletionItem {
254 label: item.label().to_string(),
255 detail: item.detail().map(|it| it.to_string()),
256 filter_text: Some(item.lookup().to_string()),
257 kind: Some(completion_item_kind(item.kind())),
258 text_edit: Some(text_edit),
259 additional_text_edits: Some(additional_text_edits),
260 documentation: item.documentation().map(documentation),
261 deprecated: Some(item.deprecated()),
262 ..Default::default()
263 };
264
265 set_score(&mut lsp_item, max_relevance, item.relevance());
266
267 if item.deprecated() {
268 lsp_item.tags = Some(vec![lsp_types::CompletionItemTag::DEPRECATED])
269 }
270
271 if item.trigger_call_info() && config.client_commands().trigger_parameter_hints {
272 lsp_item.command = Some(command::trigger_parameter_hints());
273 }
274
275 if item.is_snippet() {
276 lsp_item.insert_text_format = Some(lsp_types::InsertTextFormat::SNIPPET);
277 }
278 if config.completion().enable_imports_on_the_fly {
279 if let imports @ [_, ..] = item.imports_to_add() {
280 let imports: Vec<_> = imports
281 .iter()
282 .filter_map(|import_edit| {
283 let import_path = &import_edit.import.import_path;
284 let import_name = import_path.segments().last()?;
285 Some(lsp_ext::CompletionImport {
286 full_import_path: import_path.to_string(),
287 imported_name: import_name.to_string(),
288 })
289 })
290 .collect();
291 if !imports.is_empty() {
292 let data = lsp_ext::CompletionResolveData { position: tdpp.clone(), imports };
293 lsp_item.data = Some(to_value(data).unwrap());
294 }
295 }
296 }
297
298 if let Some((mutability, relevance)) = item.ref_match() {
299 let mut lsp_item_with_ref = lsp_item.clone();
300 set_score(&mut lsp_item_with_ref, max_relevance, relevance);
301 lsp_item_with_ref.label =
302 format!("&{}{}", mutability.as_keyword_for_ref(), lsp_item_with_ref.label);
303 if let Some(it) = &mut lsp_item_with_ref.text_edit {
304 let new_text = match it {
305 lsp_types::CompletionTextEdit::Edit(it) => &mut it.new_text,
306 lsp_types::CompletionTextEdit::InsertAndReplace(it) => &mut it.new_text,
307 };
308 *new_text = format!("&{}{}", mutability.as_keyword_for_ref(), new_text);
309 }
310
311 acc.push(lsp_item_with_ref);
312 };
313
314 acc.push(lsp_item);
315
316 fn set_score(
317 res: &mut lsp_types::CompletionItem,
318 max_relevance: u32,
319 relevance: CompletionRelevance,
320 ) {
321 if relevance.is_relevant() && relevance.score() == max_relevance {
322 res.preselect = Some(true);
323 }
324 // The relevance needs to be inverted to come up with a sort score
325 // because the client will sort ascending.
326 let sort_score = relevance.score() ^ 0xFF_FF_FF_FF;
327 // Zero pad the string to ensure values can be properly sorted
328 // by the client. Hex format is used because it is easier to
329 // visually compare very large values, which the sort text
330 // tends to be since it is the opposite of the score.
331 res.sort_text = Some(format!("{:08x}", sort_score));
332 }
333 }
334
signature_help( call_info: CallInfo, concise: bool, label_offsets: bool, ) -> lsp_types::SignatureHelp335 pub(crate) fn signature_help(
336 call_info: CallInfo,
337 concise: bool,
338 label_offsets: bool,
339 ) -> lsp_types::SignatureHelp {
340 let (label, parameters) = match (concise, label_offsets) {
341 (_, false) => {
342 let params = call_info
343 .parameter_labels()
344 .map(|label| lsp_types::ParameterInformation {
345 label: lsp_types::ParameterLabel::Simple(label.to_string()),
346 documentation: None,
347 })
348 .collect::<Vec<_>>();
349 let label =
350 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
351 (label, params)
352 }
353 (false, true) => {
354 let params = call_info
355 .parameter_ranges()
356 .iter()
357 .map(|it| [u32::from(it.start()), u32::from(it.end())])
358 .map(|label_offsets| lsp_types::ParameterInformation {
359 label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
360 documentation: None,
361 })
362 .collect::<Vec<_>>();
363 (call_info.signature, params)
364 }
365 (true, true) => {
366 let mut params = Vec::new();
367 let mut label = String::new();
368 let mut first = true;
369 for param in call_info.parameter_labels() {
370 if !first {
371 label.push_str(", ");
372 }
373 first = false;
374 let start = label.len() as u32;
375 label.push_str(param);
376 let end = label.len() as u32;
377 params.push(lsp_types::ParameterInformation {
378 label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
379 documentation: None,
380 });
381 }
382
383 (label, params)
384 }
385 };
386
387 let documentation = if concise {
388 None
389 } else {
390 call_info.doc.map(|doc| {
391 lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
392 kind: lsp_types::MarkupKind::Markdown,
393 value: doc,
394 })
395 })
396 };
397
398 let active_parameter = call_info.active_parameter.map(|it| it as u32);
399
400 let signature = lsp_types::SignatureInformation {
401 label,
402 documentation,
403 parameters: Some(parameters),
404 active_parameter,
405 };
406 lsp_types::SignatureHelp {
407 signatures: vec![signature],
408 active_signature: Some(0),
409 active_parameter,
410 }
411 }
412
inlay_hint(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint413 pub(crate) fn inlay_hint(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
414 lsp_ext::InlayHint {
415 label: inlay_hint.label.to_string(),
416 range: range(line_index, inlay_hint.range),
417 kind: match inlay_hint.kind {
418 InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
419 InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
420 InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
421 },
422 }
423 }
424
425 static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
426
semantic_tokens( text: &str, line_index: &LineIndex, highlights: Vec<HlRange>, highlight_strings: bool, ) -> lsp_types::SemanticTokens427 pub(crate) fn semantic_tokens(
428 text: &str,
429 line_index: &LineIndex,
430 highlights: Vec<HlRange>,
431 highlight_strings: bool,
432 ) -> lsp_types::SemanticTokens {
433 let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
434 let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
435
436 for highlight_range in highlights {
437 if highlight_range.highlight.is_empty() {
438 continue;
439 }
440 let (ty, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
441 if !highlight_strings && ty == lsp_types::SemanticTokenType::STRING {
442 continue;
443 }
444 let token_index = semantic_tokens::type_index(ty);
445 let modifier_bitset = mods.0;
446
447 for mut text_range in line_index.index.lines(highlight_range.range) {
448 if text[text_range].ends_with('\n') {
449 text_range =
450 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
451 }
452 let range = range(line_index, text_range);
453 builder.push(range, token_index, modifier_bitset);
454 }
455 }
456
457 builder.build()
458 }
459
semantic_token_delta( previous: &lsp_types::SemanticTokens, current: &lsp_types::SemanticTokens, ) -> lsp_types::SemanticTokensDelta460 pub(crate) fn semantic_token_delta(
461 previous: &lsp_types::SemanticTokens,
462 current: &lsp_types::SemanticTokens,
463 ) -> lsp_types::SemanticTokensDelta {
464 let result_id = current.result_id.clone();
465 let edits = semantic_tokens::diff_tokens(&previous.data, ¤t.data);
466 lsp_types::SemanticTokensDelta { result_id, edits }
467 }
468
semantic_token_type_and_modifiers( highlight: Highlight, ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet)469 fn semantic_token_type_and_modifiers(
470 highlight: Highlight,
471 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
472 let mut mods = semantic_tokens::ModifierSet::default();
473 let type_ = match highlight.tag {
474 HlTag::Symbol(symbol) => match symbol {
475 SymbolKind::Attribute => semantic_tokens::ATTRIBUTE,
476 SymbolKind::Derive => semantic_tokens::DERIVE,
477 SymbolKind::Module => lsp_types::SemanticTokenType::NAMESPACE,
478 SymbolKind::Impl => semantic_tokens::TYPE_ALIAS,
479 SymbolKind::Field => lsp_types::SemanticTokenType::PROPERTY,
480 SymbolKind::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
481 SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
482 SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
483 SymbolKind::Label => semantic_tokens::LABEL,
484 SymbolKind::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
485 SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
486 SymbolKind::Local => lsp_types::SemanticTokenType::VARIABLE,
487 SymbolKind::Function => {
488 if highlight.mods.contains(HlMod::Associated) {
489 lsp_types::SemanticTokenType::METHOD
490 } else {
491 lsp_types::SemanticTokenType::FUNCTION
492 }
493 }
494 SymbolKind::Const => {
495 mods |= semantic_tokens::CONSTANT;
496 mods |= lsp_types::SemanticTokenModifier::STATIC;
497 lsp_types::SemanticTokenType::VARIABLE
498 }
499 SymbolKind::Static => {
500 mods |= lsp_types::SemanticTokenModifier::STATIC;
501 lsp_types::SemanticTokenType::VARIABLE
502 }
503 SymbolKind::Struct => lsp_types::SemanticTokenType::STRUCT,
504 SymbolKind::Enum => lsp_types::SemanticTokenType::ENUM,
505 SymbolKind::Variant => lsp_types::SemanticTokenType::ENUM_MEMBER,
506 SymbolKind::Union => semantic_tokens::UNION,
507 SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
508 SymbolKind::Trait => lsp_types::SemanticTokenType::INTERFACE,
509 SymbolKind::Macro => lsp_types::SemanticTokenType::MACRO,
510 SymbolKind::BuiltinAttr => semantic_tokens::BUILTIN_ATTRIBUTE,
511 SymbolKind::ToolModule => semantic_tokens::TOOL_MODULE,
512 },
513 HlTag::AttributeBracket => semantic_tokens::ATTRIBUTE_BRACKET,
514 HlTag::BoolLiteral => semantic_tokens::BOOLEAN,
515 HlTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
516 HlTag::ByteLiteral | HlTag::NumericLiteral => lsp_types::SemanticTokenType::NUMBER,
517 HlTag::CharLiteral => semantic_tokens::CHAR,
518 HlTag::Comment => lsp_types::SemanticTokenType::COMMENT,
519 HlTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
520 HlTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
521 HlTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
522 HlTag::None => semantic_tokens::GENERIC,
523 HlTag::Operator(op) => match op {
524 HlOperator::Bitwise => semantic_tokens::BITWISE,
525 HlOperator::Arithmetic => semantic_tokens::ARITHMETIC,
526 HlOperator::Logical => semantic_tokens::LOGICAL,
527 HlOperator::Comparison => semantic_tokens::COMPARISON,
528 HlOperator::Other => semantic_tokens::OPERATOR,
529 },
530 HlTag::StringLiteral => lsp_types::SemanticTokenType::STRING,
531 HlTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
532 HlTag::Punctuation(punct) => match punct {
533 HlPunct::Bracket => semantic_tokens::BRACKET,
534 HlPunct::Brace => semantic_tokens::BRACE,
535 HlPunct::Parenthesis => semantic_tokens::PARENTHESIS,
536 HlPunct::Angle => semantic_tokens::ANGLE,
537 HlPunct::Comma => semantic_tokens::COMMA,
538 HlPunct::Dot => semantic_tokens::DOT,
539 HlPunct::Colon => semantic_tokens::COLON,
540 HlPunct::Semi => semantic_tokens::SEMICOLON,
541 HlPunct::Other => semantic_tokens::PUNCTUATION,
542 },
543 };
544
545 for modifier in highlight.mods.iter() {
546 let modifier = match modifier {
547 HlMod::Associated => continue,
548 HlMod::Async => semantic_tokens::ASYNC,
549 HlMod::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
550 HlMod::Callable => semantic_tokens::CALLABLE,
551 HlMod::Consuming => semantic_tokens::CONSUMING,
552 HlMod::ControlFlow => semantic_tokens::CONTROL_FLOW,
553 HlMod::CrateRoot => semantic_tokens::CRATE_ROOT,
554 HlMod::DefaultLibrary => lsp_types::SemanticTokenModifier::DEFAULT_LIBRARY,
555 HlMod::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
556 HlMod::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
557 HlMod::Injected => semantic_tokens::INJECTED,
558 HlMod::IntraDocLink => semantic_tokens::INTRA_DOC_LINK,
559 HlMod::Library => semantic_tokens::LIBRARY,
560 HlMod::Mutable => semantic_tokens::MUTABLE,
561 HlMod::Public => semantic_tokens::PUBLIC,
562 HlMod::Reference => semantic_tokens::REFERENCE,
563 HlMod::Static => lsp_types::SemanticTokenModifier::STATIC,
564 HlMod::Trait => semantic_tokens::TRAIT_MODIFIER,
565 HlMod::Unsafe => semantic_tokens::UNSAFE,
566 };
567 mods |= modifier;
568 }
569
570 (type_, mods)
571 }
572
folding_range( text: &str, line_index: &LineIndex, line_folding_only: bool, fold: Fold, ) -> lsp_types::FoldingRange573 pub(crate) fn folding_range(
574 text: &str,
575 line_index: &LineIndex,
576 line_folding_only: bool,
577 fold: Fold,
578 ) -> lsp_types::FoldingRange {
579 let kind = match fold.kind {
580 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
581 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
582 FoldKind::Region => Some(lsp_types::FoldingRangeKind::Region),
583 FoldKind::Mods
584 | FoldKind::Block
585 | FoldKind::ArgList
586 | FoldKind::Consts
587 | FoldKind::Statics
588 | FoldKind::WhereClause
589 | FoldKind::ReturnType
590 | FoldKind::Array => None,
591 };
592
593 let range = range(line_index, fold.range);
594
595 if line_folding_only {
596 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
597 // even if it contains text not in the folding range. To prevent that we exclude
598 // range.end.line from the folding region if there is more text after range.end
599 // on the same line.
600 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
601 .chars()
602 .take_while(|it| *it != '\n')
603 .any(|it| !it.is_whitespace());
604
605 let end_line = if has_more_text_on_end_line {
606 range.end.line.saturating_sub(1)
607 } else {
608 range.end.line
609 };
610
611 lsp_types::FoldingRange {
612 start_line: range.start.line,
613 start_character: None,
614 end_line,
615 end_character: None,
616 kind,
617 }
618 } else {
619 lsp_types::FoldingRange {
620 start_line: range.start.line,
621 start_character: Some(range.start.character),
622 end_line: range.end.line,
623 end_character: Some(range.end.character),
624 kind,
625 }
626 }
627 }
628
url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url629 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
630 snap.file_id_to_url(file_id)
631 }
632
633 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
634 /// This will only happen when processing windows paths.
635 ///
636 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
url_from_abs_path(path: &AbsPath) -> lsp_types::Url637 pub(crate) fn url_from_abs_path(path: &AbsPath) -> lsp_types::Url {
638 let url = lsp_types::Url::from_file_path(path).unwrap();
639 match path.as_ref().components().next() {
640 Some(path::Component::Prefix(prefix))
641 if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
642 {
643 // Need to lowercase driver letter
644 }
645 _ => return url,
646 }
647
648 let driver_letter_range = {
649 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
650 Some(it) => it,
651 None => return url,
652 };
653 let start = scheme.len() + ':'.len_utf8();
654 start..(start + drive_letter.len())
655 };
656
657 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
658 // machinery *also* canonicalizes the drive letter. So, just massage the
659 // string in place.
660 let mut url: String = url.into();
661 url[driver_letter_range].make_ascii_lowercase();
662 lsp_types::Url::parse(&url).unwrap()
663 }
664
optional_versioned_text_document_identifier( snap: &GlobalStateSnapshot, file_id: FileId, ) -> lsp_types::OptionalVersionedTextDocumentIdentifier665 pub(crate) fn optional_versioned_text_document_identifier(
666 snap: &GlobalStateSnapshot,
667 file_id: FileId,
668 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
669 let url = url(snap, file_id);
670 let version = snap.url_file_version(&url);
671 lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
672 }
673
location( snap: &GlobalStateSnapshot, frange: FileRange, ) -> Result<lsp_types::Location>674 pub(crate) fn location(
675 snap: &GlobalStateSnapshot,
676 frange: FileRange,
677 ) -> Result<lsp_types::Location> {
678 let url = url(snap, frange.file_id);
679 let line_index = snap.file_line_index(frange.file_id)?;
680 let range = range(&line_index, frange.range);
681 let loc = lsp_types::Location::new(url, range);
682 Ok(loc)
683 }
684
685 /// Prefer using `location_link`, if the client has the cap.
location_from_nav( snap: &GlobalStateSnapshot, nav: NavigationTarget, ) -> Result<lsp_types::Location>686 pub(crate) fn location_from_nav(
687 snap: &GlobalStateSnapshot,
688 nav: NavigationTarget,
689 ) -> Result<lsp_types::Location> {
690 let url = url(snap, nav.file_id);
691 let line_index = snap.file_line_index(nav.file_id)?;
692 let range = range(&line_index, nav.full_range);
693 let loc = lsp_types::Location::new(url, range);
694 Ok(loc)
695 }
696
location_link( snap: &GlobalStateSnapshot, src: Option<FileRange>, target: NavigationTarget, ) -> Result<lsp_types::LocationLink>697 pub(crate) fn location_link(
698 snap: &GlobalStateSnapshot,
699 src: Option<FileRange>,
700 target: NavigationTarget,
701 ) -> Result<lsp_types::LocationLink> {
702 let origin_selection_range = match src {
703 Some(src) => {
704 let line_index = snap.file_line_index(src.file_id)?;
705 let range = range(&line_index, src.range);
706 Some(range)
707 }
708 None => None,
709 };
710 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
711 let res = lsp_types::LocationLink {
712 origin_selection_range,
713 target_uri,
714 target_range,
715 target_selection_range,
716 };
717 Ok(res)
718 }
719
location_info( snap: &GlobalStateSnapshot, target: NavigationTarget, ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)>720 fn location_info(
721 snap: &GlobalStateSnapshot,
722 target: NavigationTarget,
723 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
724 let line_index = snap.file_line_index(target.file_id)?;
725
726 let target_uri = url(snap, target.file_id);
727 let target_range = range(&line_index, target.full_range);
728 let target_selection_range =
729 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
730 Ok((target_uri, target_range, target_selection_range))
731 }
732
goto_definition_response( snap: &GlobalStateSnapshot, src: Option<FileRange>, targets: Vec<NavigationTarget>, ) -> Result<lsp_types::GotoDefinitionResponse>733 pub(crate) fn goto_definition_response(
734 snap: &GlobalStateSnapshot,
735 src: Option<FileRange>,
736 targets: Vec<NavigationTarget>,
737 ) -> Result<lsp_types::GotoDefinitionResponse> {
738 if snap.config.location_link() {
739 let links = targets
740 .into_iter()
741 .map(|nav| location_link(snap, src, nav))
742 .collect::<Result<Vec<_>>>()?;
743 Ok(links.into())
744 } else {
745 let locations = targets
746 .into_iter()
747 .map(|nav| {
748 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
749 })
750 .collect::<Result<Vec<_>>>()?;
751 Ok(locations.into())
752 }
753 }
754
outside_workspace_annotation_id() -> String755 fn outside_workspace_annotation_id() -> String {
756 String::from("OutsideWorkspace")
757 }
758
snippet_text_document_edit( snap: &GlobalStateSnapshot, is_snippet: bool, file_id: FileId, edit: TextEdit, ) -> Result<lsp_ext::SnippetTextDocumentEdit>759 pub(crate) fn snippet_text_document_edit(
760 snap: &GlobalStateSnapshot,
761 is_snippet: bool,
762 file_id: FileId,
763 edit: TextEdit,
764 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
765 let text_document = optional_versioned_text_document_identifier(snap, file_id);
766 let line_index = snap.file_line_index(file_id)?;
767 let mut edits: Vec<_> =
768 edit.into_iter().map(|it| snippet_text_edit(&line_index, is_snippet, it)).collect();
769
770 if snap.analysis.is_library_file(file_id)? && snap.config.change_annotation_support() {
771 for edit in &mut edits {
772 edit.annotation_id = Some(outside_workspace_annotation_id())
773 }
774 }
775 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
776 }
777
snippet_text_document_ops( snap: &GlobalStateSnapshot, file_system_edit: FileSystemEdit, ) -> Cancellable<Vec<lsp_ext::SnippetDocumentChangeOperation>>778 pub(crate) fn snippet_text_document_ops(
779 snap: &GlobalStateSnapshot,
780 file_system_edit: FileSystemEdit,
781 ) -> Cancellable<Vec<lsp_ext::SnippetDocumentChangeOperation>> {
782 let mut ops = Vec::new();
783 match file_system_edit {
784 FileSystemEdit::CreateFile { dst, initial_contents } => {
785 let uri = snap.anchored_path(&dst);
786 let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
787 uri: uri.clone(),
788 options: None,
789 annotation_id: None,
790 });
791 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
792 if !initial_contents.is_empty() {
793 let text_document =
794 lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
795 let text_edit = lsp_ext::SnippetTextEdit {
796 range: lsp_types::Range::default(),
797 new_text: initial_contents,
798 insert_text_format: Some(lsp_types::InsertTextFormat::PLAIN_TEXT),
799 annotation_id: None,
800 };
801 let edit_file =
802 lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
803 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
804 }
805 }
806 FileSystemEdit::MoveFile { src, dst } => {
807 let old_uri = snap.file_id_to_url(src);
808 let new_uri = snap.anchored_path(&dst);
809 let mut rename_file =
810 lsp_types::RenameFile { old_uri, new_uri, options: None, annotation_id: None };
811 if snap.analysis.is_library_file(src).ok() == Some(true)
812 && snap.config.change_annotation_support()
813 {
814 rename_file.annotation_id = Some(outside_workspace_annotation_id())
815 }
816 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(lsp_types::ResourceOp::Rename(
817 rename_file,
818 )))
819 }
820 }
821 Ok(ops)
822 }
823
snippet_workspace_edit( snap: &GlobalStateSnapshot, source_change: SourceChange, ) -> Result<lsp_ext::SnippetWorkspaceEdit>824 pub(crate) fn snippet_workspace_edit(
825 snap: &GlobalStateSnapshot,
826 source_change: SourceChange,
827 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
828 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
829
830 for op in source_change.file_system_edits {
831 let ops = snippet_text_document_ops(snap, op)?;
832 document_changes.extend_from_slice(&ops);
833 }
834 for (file_id, edit) in source_change.source_file_edits {
835 let edit = snippet_text_document_edit(snap, source_change.is_snippet, file_id, edit)?;
836 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
837 }
838 let mut workspace_edit = lsp_ext::SnippetWorkspaceEdit {
839 changes: None,
840 document_changes: Some(document_changes),
841 change_annotations: None,
842 };
843 if snap.config.change_annotation_support() {
844 workspace_edit.change_annotations = Some(
845 once((
846 outside_workspace_annotation_id(),
847 lsp_types::ChangeAnnotation {
848 label: String::from("Edit outside of the workspace"),
849 needs_confirmation: Some(true),
850 description: Some(String::from(
851 "This edit lies outside of the workspace and may affect dependencies",
852 )),
853 },
854 ))
855 .collect(),
856 )
857 }
858 Ok(workspace_edit)
859 }
860
workspace_edit( snap: &GlobalStateSnapshot, source_change: SourceChange, ) -> Result<lsp_types::WorkspaceEdit>861 pub(crate) fn workspace_edit(
862 snap: &GlobalStateSnapshot,
863 source_change: SourceChange,
864 ) -> Result<lsp_types::WorkspaceEdit> {
865 assert!(!source_change.is_snippet);
866 snippet_workspace_edit(snap, source_change).map(|it| it.into())
867 }
868
869 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit870 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
871 lsp_types::WorkspaceEdit {
872 changes: None,
873 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
874 lsp_types::DocumentChanges::Operations(
875 changes
876 .into_iter()
877 .map(|change| match change {
878 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
879 lsp_types::DocumentChangeOperation::Op(op)
880 }
881 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
882 lsp_types::DocumentChangeOperation::Edit(
883 lsp_types::TextDocumentEdit {
884 text_document: edit.text_document,
885 edits: edit.edits.into_iter().map(From::from).collect(),
886 },
887 )
888 }
889 })
890 .collect(),
891 )
892 }),
893 change_annotations: snippet_workspace_edit.change_annotations,
894 }
895 }
896 }
897
898 impl From<lsp_ext::SnippetTextEdit>
899 for lsp_types::OneOf<lsp_types::TextEdit, lsp_types::AnnotatedTextEdit>
900 {
901 fn from(
902 lsp_ext::SnippetTextEdit { annotation_id, insert_text_format:_, new_text, range }: lsp_ext::SnippetTextEdit,
903 ) -> Self {
904 match annotation_id {
905 Some(annotation_id) => lsp_types::OneOf::Right(lsp_types::AnnotatedTextEdit {
906 text_edit: lsp_types::TextEdit { range, new_text },
907 annotation_id,
908 }),
909 None => lsp_types::OneOf::Left(lsp_types::TextEdit { range, new_text }),
910 }
911 }
912 }
913
call_hierarchy_item( snap: &GlobalStateSnapshot, target: NavigationTarget, ) -> Result<lsp_types::CallHierarchyItem>914 pub(crate) fn call_hierarchy_item(
915 snap: &GlobalStateSnapshot,
916 target: NavigationTarget,
917 ) -> Result<lsp_types::CallHierarchyItem> {
918 let name = target.name.to_string();
919 let detail = target.description.clone();
920 let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::FUNCTION);
921 let (uri, range, selection_range) = location_info(snap, target)?;
922 Ok(lsp_types::CallHierarchyItem {
923 name,
924 kind,
925 tags: None,
926 detail,
927 uri,
928 range,
929 selection_range,
930 data: None,
931 })
932 }
933
code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind934 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
935 match kind {
936 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
937 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
938 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
939 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
940 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
941 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
942 }
943 }
944
code_action( snap: &GlobalStateSnapshot, assist: Assist, resolve_data: Option<(usize, lsp_types::CodeActionParams)>, ) -> Result<lsp_ext::CodeAction>945 pub(crate) fn code_action(
946 snap: &GlobalStateSnapshot,
947 assist: Assist,
948 resolve_data: Option<(usize, lsp_types::CodeActionParams)>,
949 ) -> Result<lsp_ext::CodeAction> {
950 let mut res = lsp_ext::CodeAction {
951 title: assist.label.to_string(),
952 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
953 kind: Some(code_action_kind(assist.id.1)),
954 edit: None,
955 is_preferred: None,
956 data: None,
957 };
958 match (assist.source_change, resolve_data) {
959 (Some(it), _) => res.edit = Some(snippet_workspace_edit(snap, it)?),
960 (None, Some((index, code_action_params))) => {
961 res.data = Some(lsp_ext::CodeActionData {
962 id: format!("{}:{}:{}", assist.id.0, assist.id.1.name(), index),
963 code_action_params,
964 });
965 }
966 (None, None) => {
967 stdx::never!("assist should always be resolved if client can't do lazy resolving")
968 }
969 };
970 Ok(res)
971 }
972
runnable( snap: &GlobalStateSnapshot, runnable: Runnable, ) -> Result<lsp_ext::Runnable>973 pub(crate) fn runnable(
974 snap: &GlobalStateSnapshot,
975 runnable: Runnable,
976 ) -> Result<lsp_ext::Runnable> {
977 let config = snap.config.runnables();
978 let spec = CargoTargetSpec::for_file(snap, runnable.nav.file_id)?;
979 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
980 let target = spec.as_ref().map(|s| s.target.clone());
981 let (cargo_args, executable_args) =
982 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
983 let label = runnable.label(target);
984 let location = location_link(snap, None, runnable.nav)?;
985
986 Ok(lsp_ext::Runnable {
987 label,
988 location: Some(location),
989 kind: lsp_ext::RunnableKind::Cargo,
990 args: lsp_ext::CargoRunnable {
991 workspace_root: workspace_root.map(|it| it.into()),
992 override_cargo: config.override_cargo,
993 cargo_args,
994 cargo_extra_args: config.cargo_extra_args,
995 executable_args,
996 expect_test: None,
997 },
998 })
999 }
1000
code_lens( acc: &mut Vec<lsp_types::CodeLens>, snap: &GlobalStateSnapshot, annotation: Annotation, ) -> Result<()>1001 pub(crate) fn code_lens(
1002 acc: &mut Vec<lsp_types::CodeLens>,
1003 snap: &GlobalStateSnapshot,
1004 annotation: Annotation,
1005 ) -> Result<()> {
1006 let client_commands_config = snap.config.client_commands();
1007 match annotation.kind {
1008 AnnotationKind::Runnable(run) => {
1009 let line_index = snap.file_line_index(run.nav.file_id)?;
1010 let annotation_range = range(&line_index, annotation.range);
1011
1012 let title = run.title();
1013 let can_debug = match run.kind {
1014 ide::RunnableKind::DocTest { .. } => false,
1015 ide::RunnableKind::TestMod { .. }
1016 | ide::RunnableKind::Test { .. }
1017 | ide::RunnableKind::Bench { .. }
1018 | ide::RunnableKind::Bin => true,
1019 };
1020 let r = runnable(snap, run)?;
1021
1022 let lens_config = snap.config.lens();
1023 if lens_config.run && client_commands_config.run_single {
1024 let command = command::run_single(&r, &title);
1025 acc.push(lsp_types::CodeLens {
1026 range: annotation_range,
1027 command: Some(command),
1028 data: None,
1029 })
1030 }
1031 if lens_config.debug && can_debug && client_commands_config.debug_single {
1032 let command = command::debug_single(&r);
1033 acc.push(lsp_types::CodeLens {
1034 range: annotation_range,
1035 command: Some(command),
1036 data: None,
1037 })
1038 }
1039 }
1040 AnnotationKind::HasImpls { position: file_position, data } => {
1041 if !client_commands_config.show_reference {
1042 return Ok(());
1043 }
1044 let line_index = snap.file_line_index(file_position.file_id)?;
1045 let annotation_range = range(&line_index, annotation.range);
1046 let url = url(snap, file_position.file_id);
1047
1048 let position = position(&line_index, file_position.offset);
1049
1050 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1051
1052 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
1053
1054 let goto_params = lsp_types::request::GotoImplementationParams {
1055 text_document_position_params: doc_pos,
1056 work_done_progress_params: Default::default(),
1057 partial_result_params: Default::default(),
1058 };
1059
1060 let command = data.map(|ranges| {
1061 let locations: Vec<lsp_types::Location> = ranges
1062 .into_iter()
1063 .filter_map(|target| {
1064 location(
1065 snap,
1066 FileRange { file_id: target.file_id, range: target.full_range },
1067 )
1068 .ok()
1069 })
1070 .collect();
1071
1072 command::show_references(
1073 implementation_title(locations.len()),
1074 &url,
1075 position,
1076 locations,
1077 )
1078 });
1079
1080 acc.push(lsp_types::CodeLens {
1081 range: annotation_range,
1082 command,
1083 data: Some(to_value(lsp_ext::CodeLensResolveData::Impls(goto_params)).unwrap()),
1084 })
1085 }
1086 AnnotationKind::HasReferences { position: file_position, data } => {
1087 if !client_commands_config.show_reference {
1088 return Ok(());
1089 }
1090 let line_index = snap.file_line_index(file_position.file_id)?;
1091 let annotation_range = range(&line_index, annotation.range);
1092 let url = url(snap, file_position.file_id);
1093
1094 let position = position(&line_index, file_position.offset);
1095
1096 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1097
1098 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
1099
1100 let command = data.map(|ranges| {
1101 let locations: Vec<lsp_types::Location> =
1102 ranges.into_iter().filter_map(|range| location(snap, range).ok()).collect();
1103
1104 command::show_references(
1105 reference_title(locations.len()),
1106 &url,
1107 position,
1108 locations,
1109 )
1110 });
1111
1112 acc.push(lsp_types::CodeLens {
1113 range: annotation_range,
1114 command,
1115 data: Some(to_value(lsp_ext::CodeLensResolveData::References(doc_pos)).unwrap()),
1116 })
1117 }
1118 }
1119 Ok(())
1120 }
1121
1122 pub(crate) mod command {
1123 use ide::{FileRange, NavigationTarget};
1124 use serde_json::to_value;
1125
1126 use crate::{
1127 global_state::GlobalStateSnapshot,
1128 lsp_ext,
1129 to_proto::{location, location_link},
1130 };
1131
show_references( title: String, uri: &lsp_types::Url, position: lsp_types::Position, locations: Vec<lsp_types::Location>, ) -> lsp_types::Command1132 pub(crate) fn show_references(
1133 title: String,
1134 uri: &lsp_types::Url,
1135 position: lsp_types::Position,
1136 locations: Vec<lsp_types::Location>,
1137 ) -> lsp_types::Command {
1138 // We cannot use the 'editor.action.showReferences' command directly
1139 // because that command requires vscode types which we convert in the handler
1140 // on the client side.
1141
1142 lsp_types::Command {
1143 title,
1144 command: "rust-analyzer.showReferences".into(),
1145 arguments: Some(vec![
1146 to_value(uri).unwrap(),
1147 to_value(position).unwrap(),
1148 to_value(locations).unwrap(),
1149 ]),
1150 }
1151 }
1152
run_single(runnable: &lsp_ext::Runnable, title: &str) -> lsp_types::Command1153 pub(crate) fn run_single(runnable: &lsp_ext::Runnable, title: &str) -> lsp_types::Command {
1154 lsp_types::Command {
1155 title: title.to_string(),
1156 command: "rust-analyzer.runSingle".into(),
1157 arguments: Some(vec![to_value(runnable).unwrap()]),
1158 }
1159 }
1160
debug_single(runnable: &lsp_ext::Runnable) -> lsp_types::Command1161 pub(crate) fn debug_single(runnable: &lsp_ext::Runnable) -> lsp_types::Command {
1162 lsp_types::Command {
1163 title: "Debug".into(),
1164 command: "rust-analyzer.debugSingle".into(),
1165 arguments: Some(vec![to_value(runnable).unwrap()]),
1166 }
1167 }
1168
goto_location( snap: &GlobalStateSnapshot, nav: &NavigationTarget, ) -> Option<lsp_types::Command>1169 pub(crate) fn goto_location(
1170 snap: &GlobalStateSnapshot,
1171 nav: &NavigationTarget,
1172 ) -> Option<lsp_types::Command> {
1173 let value = if snap.config.location_link() {
1174 let link = location_link(snap, None, nav.clone()).ok()?;
1175 to_value(link).ok()?
1176 } else {
1177 let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1178 let location = location(snap, range).ok()?;
1179 to_value(location).ok()?
1180 };
1181
1182 Some(lsp_types::Command {
1183 title: nav.name.to_string(),
1184 command: "rust-analyzer.gotoLocation".into(),
1185 arguments: Some(vec![value]),
1186 })
1187 }
1188
trigger_parameter_hints() -> lsp_types::Command1189 pub(crate) fn trigger_parameter_hints() -> lsp_types::Command {
1190 lsp_types::Command {
1191 title: "triggerParameterHints".into(),
1192 command: "editor.action.triggerParameterHints".into(),
1193 arguments: None,
1194 }
1195 }
1196 }
1197
implementation_title(count: usize) -> String1198 pub(crate) fn implementation_title(count: usize) -> String {
1199 if count == 1 {
1200 "1 implementation".into()
1201 } else {
1202 format!("{} implementations", count)
1203 }
1204 }
1205
reference_title(count: usize) -> String1206 pub(crate) fn reference_title(count: usize) -> String {
1207 if count == 1 {
1208 "1 reference".into()
1209 } else {
1210 format!("{} references", count)
1211 }
1212 }
1213
markup_content( markup: Markup, kind: ide::HoverDocFormat, ) -> lsp_types::MarkupContent1214 pub(crate) fn markup_content(
1215 markup: Markup,
1216 kind: ide::HoverDocFormat,
1217 ) -> lsp_types::MarkupContent {
1218 let kind = match kind {
1219 ide::HoverDocFormat::Markdown => lsp_types::MarkupKind::Markdown,
1220 ide::HoverDocFormat::PlainText => lsp_types::MarkupKind::PlainText,
1221 };
1222 let value = crate::markdown::format_docs(markup.as_str());
1223 lsp_types::MarkupContent { kind, value }
1224 }
1225
rename_error(err: RenameError) -> crate::LspError1226 pub(crate) fn rename_error(err: RenameError) -> crate::LspError {
1227 // This is wrong, but we don't have a better alternative I suppose?
1228 // https://github.com/microsoft/language-server-protocol/issues/1341
1229 invalid_params_error(err.to_string())
1230 }
1231
1232 #[cfg(test)]
1233 mod tests {
1234 use std::sync::Arc;
1235
1236 use ide::Analysis;
1237
1238 use super::*;
1239
1240 #[test]
conv_fold_line_folding_only_fixup()1241 fn conv_fold_line_folding_only_fixup() {
1242 let text = r#"mod a;
1243 mod b;
1244 mod c;
1245
1246 fn main() {
1247 if cond {
1248 a::do_a();
1249 } else {
1250 b::do_b();
1251 }
1252 }"#;
1253
1254 let (analysis, file_id) = Analysis::from_single_file(text.to_string());
1255 let folds = analysis.folding_ranges(file_id).unwrap();
1256 assert_eq!(folds.len(), 4);
1257
1258 let line_index = LineIndex {
1259 index: Arc::new(ide::LineIndex::new(text)),
1260 endings: LineEndings::Unix,
1261 encoding: OffsetEncoding::Utf16,
1262 };
1263 let converted: Vec<lsp_types::FoldingRange> =
1264 folds.into_iter().map(|it| folding_range(text, &line_index, true, it)).collect();
1265
1266 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
1267 assert_eq!(converted.len(), expected_lines.len());
1268 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
1269 assert_eq!(folding_range.start_line, *start_line);
1270 assert_eq!(folding_range.start_character, None);
1271 assert_eq!(folding_range.end_line, *end_line);
1272 assert_eq!(folding_range.end_character, None);
1273 }
1274 }
1275
1276 // `Url` is not able to parse windows paths on unix machines.
1277 #[test]
1278 #[cfg(target_os = "windows")]
test_lowercase_drive_letter()1279 fn test_lowercase_drive_letter() {
1280 use std::{convert::TryInto, path::Path};
1281
1282 let url = url_from_abs_path(Path::new("C:\\Test").try_into().unwrap());
1283 assert_eq!(url.to_string(), "file:///c:/Test");
1284
1285 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#).try_into().unwrap());
1286 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");
1287 }
1288 }
1289