1 //! Conversion of rust-analyzer specific types to lsp_types equivalents.
4 sync::atomic::{AtomicU32, Ordering},
8 Annotation, AnnotationKind, Assist, AssistKind, CallInfo, CompletionItem, CompletionItemKind,
9 CompletionRelevance, Documentation, FileId, FileRange, FileSystemEdit, Fold, FoldKind,
10 Highlight, HlMod, HlPunct, HlRange, HlTag, Indel, InlayHint, InlayKind, InsertTextFormat,
11 Markup, NavigationTarget, ReferenceAccess, RenameError, Runnable, Severity, SourceChange,
12 TextEdit, TextRange, TextSize,
14 use ide_db::SymbolKind;
15 use itertools::Itertools;
16 use serde_json::to_value;
19 cargo_target_spec::CargoTargetSpec,
20 global_state::GlobalStateSnapshot,
21 line_index::{LineEndings, LineIndex, OffsetEncoding},
22 lsp_ext, semantic_tokens, Result,
25 pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position {
26 let line_col = line_index.index.line_col(offset);
27 match line_index.encoding {
28 OffsetEncoding::Utf8 => lsp_types::Position::new(line_col.line, line_col.col),
29 OffsetEncoding::Utf16 => {
30 let line_col = line_index.index.to_utf16(line_col);
31 lsp_types::Position::new(line_col.line, line_col.col)
36 pub(crate) fn range(line_index: &LineIndex, range: TextRange) -> lsp_types::Range {
37 let start = position(line_index, range.start());
38 let end = position(line_index, range.end());
39 lsp_types::Range::new(start, end)
42 pub(crate) fn symbol_kind(symbol_kind: SymbolKind) -> lsp_types::SymbolKind {
44 SymbolKind::Function => lsp_types::SymbolKind::Function,
45 SymbolKind::Struct => lsp_types::SymbolKind::Struct,
46 SymbolKind::Enum => lsp_types::SymbolKind::Enum,
47 SymbolKind::Variant => lsp_types::SymbolKind::EnumMember,
48 SymbolKind::Trait => lsp_types::SymbolKind::Interface,
49 SymbolKind::Macro => lsp_types::SymbolKind::Function,
50 SymbolKind::Module => lsp_types::SymbolKind::Module,
51 SymbolKind::TypeAlias | SymbolKind::TypeParam => lsp_types::SymbolKind::TypeParameter,
52 SymbolKind::Field => lsp_types::SymbolKind::Field,
53 SymbolKind::Static => lsp_types::SymbolKind::Constant,
54 SymbolKind::Const => lsp_types::SymbolKind::Constant,
55 SymbolKind::ConstParam => lsp_types::SymbolKind::Constant,
56 SymbolKind::Impl => lsp_types::SymbolKind::Object,
58 | SymbolKind::SelfParam
59 | SymbolKind::LifetimeParam
60 | SymbolKind::ValueParam
61 | SymbolKind::Label => lsp_types::SymbolKind::Variable,
62 SymbolKind::Union => lsp_types::SymbolKind::Struct,
66 pub(crate) fn document_highlight_kind(
67 reference_access: ReferenceAccess,
68 ) -> lsp_types::DocumentHighlightKind {
69 match reference_access {
70 ReferenceAccess::Read => lsp_types::DocumentHighlightKind::Read,
71 ReferenceAccess::Write => lsp_types::DocumentHighlightKind::Write,
75 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
77 Severity::Error => lsp_types::DiagnosticSeverity::Error,
78 Severity::WeakWarning => lsp_types::DiagnosticSeverity::Hint,
82 pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
83 let value = crate::markdown::format_docs(documentation.as_str());
84 let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
85 lsp_types::Documentation::MarkupContent(markup_content)
88 pub(crate) fn insert_text_format(
89 insert_text_format: InsertTextFormat,
90 ) -> lsp_types::InsertTextFormat {
91 match insert_text_format {
92 InsertTextFormat::Snippet => lsp_types::InsertTextFormat::Snippet,
93 InsertTextFormat::PlainText => lsp_types::InsertTextFormat::PlainText,
97 pub(crate) fn completion_item_kind(
98 completion_item_kind: CompletionItemKind,
99 ) -> lsp_types::CompletionItemKind {
100 match completion_item_kind {
101 CompletionItemKind::Attribute => lsp_types::CompletionItemKind::EnumMember,
102 CompletionItemKind::Binding => lsp_types::CompletionItemKind::Variable,
103 CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::Struct,
104 CompletionItemKind::Keyword => lsp_types::CompletionItemKind::Keyword,
105 CompletionItemKind::Method => lsp_types::CompletionItemKind::Method,
106 CompletionItemKind::Snippet => lsp_types::CompletionItemKind::Snippet,
107 CompletionItemKind::UnresolvedReference => lsp_types::CompletionItemKind::Reference,
108 CompletionItemKind::SymbolKind(symbol) => match symbol {
109 SymbolKind::Const => lsp_types::CompletionItemKind::Constant,
110 SymbolKind::ConstParam => lsp_types::CompletionItemKind::TypeParameter,
111 SymbolKind::Enum => lsp_types::CompletionItemKind::Enum,
112 SymbolKind::Field => lsp_types::CompletionItemKind::Field,
113 SymbolKind::Function => lsp_types::CompletionItemKind::Function,
114 SymbolKind::Impl => lsp_types::CompletionItemKind::Text,
115 SymbolKind::Label => lsp_types::CompletionItemKind::Variable,
116 SymbolKind::LifetimeParam => lsp_types::CompletionItemKind::TypeParameter,
117 SymbolKind::Local => lsp_types::CompletionItemKind::Variable,
118 SymbolKind::Macro => lsp_types::CompletionItemKind::Method,
119 SymbolKind::Module => lsp_types::CompletionItemKind::Module,
120 SymbolKind::SelfParam => lsp_types::CompletionItemKind::Value,
121 SymbolKind::Static => lsp_types::CompletionItemKind::Value,
122 SymbolKind::Struct => lsp_types::CompletionItemKind::Struct,
123 SymbolKind::Trait => lsp_types::CompletionItemKind::Interface,
124 SymbolKind::TypeAlias => lsp_types::CompletionItemKind::Struct,
125 SymbolKind::TypeParam => lsp_types::CompletionItemKind::TypeParameter,
126 SymbolKind::Union => lsp_types::CompletionItemKind::Struct,
127 SymbolKind::ValueParam => lsp_types::CompletionItemKind::Value,
128 SymbolKind::Variant => lsp_types::CompletionItemKind::EnumMember,
133 pub(crate) fn text_edit(line_index: &LineIndex, indel: Indel) -> lsp_types::TextEdit {
134 let range = range(line_index, indel.delete);
135 let new_text = match line_index.endings {
136 LineEndings::Unix => indel.insert,
137 LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
139 lsp_types::TextEdit { range, new_text }
142 pub(crate) fn snippet_text_edit(
143 line_index: &LineIndex,
146 ) -> lsp_ext::SnippetTextEdit {
147 let text_edit = text_edit(line_index, indel);
148 let insert_text_format =
149 if is_snippet { Some(lsp_types::InsertTextFormat::Snippet) } else { None };
150 lsp_ext::SnippetTextEdit {
151 range: text_edit.range,
152 new_text: text_edit.new_text,
157 pub(crate) fn text_edit_vec(
158 line_index: &LineIndex,
160 ) -> Vec<lsp_types::TextEdit> {
161 text_edit.into_iter().map(|indel| self::text_edit(line_index, indel)).collect()
164 pub(crate) fn snippet_text_edit_vec(
165 line_index: &LineIndex,
168 ) -> Vec<lsp_ext::SnippetTextEdit> {
171 .map(|indel| self::snippet_text_edit(line_index, is_snippet, indel))
175 pub(crate) fn completion_item(
176 line_index: &LineIndex,
177 item: CompletionItem,
178 ) -> Vec<lsp_types::CompletionItem> {
179 let mut additional_text_edits = Vec::new();
180 let mut text_edit = None;
181 // LSP does not allow arbitrary edits in completion, so we have to do a
182 // non-trivial mapping here.
183 let source_range = item.source_range();
184 for indel in item.text_edit().iter() {
185 if indel.delete.contains_range(source_range) {
186 text_edit = Some(if indel.delete == source_range {
187 self::text_edit(line_index, indel.clone())
189 assert!(source_range.end() == indel.delete.end());
190 let range1 = TextRange::new(indel.delete.start(), source_range.start());
191 let range2 = source_range;
192 let indel1 = Indel::replace(range1, String::new());
193 let indel2 = Indel::replace(range2, indel.insert.clone());
194 additional_text_edits.push(self::text_edit(line_index, indel1));
195 self::text_edit(line_index, indel2)
198 assert!(source_range.intersect(indel.delete).is_none());
199 let text_edit = self::text_edit(line_index, indel.clone());
200 additional_text_edits.push(text_edit);
203 let text_edit = text_edit.unwrap();
205 let mut lsp_item = lsp_types::CompletionItem {
206 label: item.label().to_string(),
207 detail: item.detail().map(|it| it.to_string()),
208 filter_text: Some(item.lookup().to_string()),
209 kind: item.kind().map(completion_item_kind),
210 text_edit: Some(text_edit.into()),
211 additional_text_edits: Some(additional_text_edits),
212 documentation: item.documentation().map(documentation),
213 deprecated: Some(item.deprecated()),
217 fn set_score(res: &mut lsp_types::CompletionItem, relevance: CompletionRelevance) {
218 if relevance.is_relevant() {
219 res.preselect = Some(true);
221 // The relevance needs to be inverted to come up with a sort score
222 // because the client will sort ascending.
223 let sort_score = relevance.score() ^ 0xFF_FF_FF_FF;
224 // Zero pad the string to ensure values can be properly sorted
225 // by the client. Hex format is used because it is easier to
226 // visually compare very large values, which the sort text
227 // tends to be since it is the opposite of the score.
228 res.sort_text = Some(format!("{:08x}", sort_score));
231 set_score(&mut lsp_item, item.relevance());
233 if item.deprecated() {
234 lsp_item.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
237 if item.trigger_call_info() {
238 lsp_item.command = Some(command::trigger_parameter_hints());
241 let mut res = match item.ref_match() {
242 Some((mutability, relevance)) => {
243 let mut lsp_item_with_ref = lsp_item.clone();
244 set_score(&mut lsp_item_with_ref, relevance);
245 lsp_item_with_ref.label =
246 format!("&{}{}", mutability.as_keyword_for_ref(), lsp_item_with_ref.label);
247 if let Some(lsp_types::CompletionTextEdit::Edit(it)) = &mut lsp_item_with_ref.text_edit
249 it.new_text = format!("&{}{}", mutability.as_keyword_for_ref(), it.new_text);
251 vec![lsp_item_with_ref, lsp_item]
253 None => vec![lsp_item],
256 for lsp_item in res.iter_mut() {
257 lsp_item.insert_text_format = Some(insert_text_format(item.insert_text_format()));
262 pub(crate) fn signature_help(
266 ) -> lsp_types::SignatureHelp {
267 let (label, parameters) = match (concise, label_offsets) {
269 let params = call_info
271 .map(|label| lsp_types::ParameterInformation {
272 label: lsp_types::ParameterLabel::Simple(label.to_string()),
275 .collect::<Vec<_>>();
277 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
281 let params = call_info
284 .map(|it| [u32::from(it.start()).into(), u32::from(it.end()).into()])
285 .map(|label_offsets| lsp_types::ParameterInformation {
286 label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
289 .collect::<Vec<_>>();
290 (call_info.signature, params)
293 let mut params = Vec::new();
294 let mut label = String::new();
295 let mut first = true;
296 for param in call_info.parameter_labels() {
298 label.push_str(", ");
301 let start = label.len() as u32;
302 label.push_str(param);
303 let end = label.len() as u32;
304 params.push(lsp_types::ParameterInformation {
305 label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
314 let documentation = if concise {
317 call_info.doc.map(|doc| {
318 lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
319 kind: lsp_types::MarkupKind::Markdown,
325 let active_parameter = call_info.active_parameter.map(|it| it as u32);
327 let signature = lsp_types::SignatureInformation {
330 parameters: Some(parameters),
333 lsp_types::SignatureHelp {
334 signatures: vec![signature],
335 active_signature: None,
340 pub(crate) fn inlay_hint(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
342 label: inlay_hint.label.to_string(),
343 range: range(line_index, inlay_hint.range),
344 kind: match inlay_hint.kind {
345 InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
346 InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
347 InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
352 static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
354 pub(crate) fn semantic_tokens(
356 line_index: &LineIndex,
357 highlights: Vec<HlRange>,
358 ) -> lsp_types::SemanticTokens {
359 let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
360 let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
362 for highlight_range in highlights {
363 if highlight_range.highlight.is_empty() {
366 let (type_, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
367 let token_index = semantic_tokens::type_index(type_);
368 let modifier_bitset = mods.0;
370 for mut text_range in line_index.index.lines(highlight_range.range) {
371 if text[text_range].ends_with('\n') {
373 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
375 let range = range(&line_index, text_range);
376 builder.push(range, token_index, modifier_bitset);
383 pub(crate) fn semantic_token_delta(
384 previous: &lsp_types::SemanticTokens,
385 current: &lsp_types::SemanticTokens,
386 ) -> lsp_types::SemanticTokensDelta {
387 let result_id = current.result_id.clone();
388 let edits = semantic_tokens::diff_tokens(&previous.data, ¤t.data);
389 lsp_types::SemanticTokensDelta { result_id, edits }
392 fn semantic_token_type_and_modifiers(
393 highlight: Highlight,
394 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
395 let mut mods = semantic_tokens::ModifierSet::default();
396 let type_ = match highlight.tag {
397 HlTag::Symbol(symbol) => match symbol {
398 SymbolKind::Module => lsp_types::SemanticTokenType::NAMESPACE,
399 SymbolKind::Impl => lsp_types::SemanticTokenType::TYPE,
400 SymbolKind::Field => lsp_types::SemanticTokenType::PROPERTY,
401 SymbolKind::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
402 SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
403 SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
404 SymbolKind::Label => semantic_tokens::LABEL,
405 SymbolKind::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
406 SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
407 SymbolKind::Local => lsp_types::SemanticTokenType::VARIABLE,
408 SymbolKind::Function => {
409 if highlight.mods.contains(HlMod::Associated) {
410 lsp_types::SemanticTokenType::METHOD
412 lsp_types::SemanticTokenType::FUNCTION
415 SymbolKind::Const => {
416 mods |= semantic_tokens::CONSTANT;
417 mods |= lsp_types::SemanticTokenModifier::STATIC;
418 lsp_types::SemanticTokenType::VARIABLE
420 SymbolKind::Static => {
421 mods |= lsp_types::SemanticTokenModifier::STATIC;
422 lsp_types::SemanticTokenType::VARIABLE
424 SymbolKind::Struct => lsp_types::SemanticTokenType::STRUCT,
425 SymbolKind::Enum => lsp_types::SemanticTokenType::ENUM,
426 SymbolKind::Variant => lsp_types::SemanticTokenType::ENUM_MEMBER,
427 SymbolKind::Union => semantic_tokens::UNION,
428 SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
429 SymbolKind::Trait => lsp_types::SemanticTokenType::INTERFACE,
430 SymbolKind::Macro => lsp_types::SemanticTokenType::MACRO,
432 HlTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
433 HlTag::None => semantic_tokens::GENERIC,
434 HlTag::ByteLiteral | HlTag::NumericLiteral => lsp_types::SemanticTokenType::NUMBER,
435 HlTag::BoolLiteral => semantic_tokens::BOOLEAN,
436 HlTag::StringLiteral => lsp_types::SemanticTokenType::STRING,
437 HlTag::CharLiteral => semantic_tokens::CHAR_LITERAL,
438 HlTag::Comment => lsp_types::SemanticTokenType::COMMENT,
439 HlTag::Attribute => semantic_tokens::ATTRIBUTE,
440 HlTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
441 HlTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
442 HlTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
443 HlTag::Operator => lsp_types::SemanticTokenType::OPERATOR,
444 HlTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
445 HlTag::Punctuation(punct) => match punct {
446 HlPunct::Bracket => semantic_tokens::BRACKET,
447 HlPunct::Brace => semantic_tokens::BRACE,
448 HlPunct::Parenthesis => semantic_tokens::PARENTHESIS,
449 HlPunct::Angle => semantic_tokens::ANGLE,
450 HlPunct::Comma => semantic_tokens::COMMA,
451 HlPunct::Dot => semantic_tokens::DOT,
452 HlPunct::Colon => semantic_tokens::COLON,
453 HlPunct::Semi => semantic_tokens::SEMICOLON,
454 HlPunct::Other => semantic_tokens::PUNCTUATION,
458 for modifier in highlight.mods.iter() {
459 let modifier = match modifier {
460 HlMod::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
461 HlMod::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
462 HlMod::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
463 HlMod::Injected => semantic_tokens::INJECTED,
464 HlMod::ControlFlow => semantic_tokens::CONTROL_FLOW,
465 HlMod::Mutable => semantic_tokens::MUTABLE,
466 HlMod::Consuming => semantic_tokens::CONSUMING,
467 HlMod::Unsafe => semantic_tokens::UNSAFE,
468 HlMod::Callable => semantic_tokens::CALLABLE,
469 HlMod::Static => lsp_types::SemanticTokenModifier::STATIC,
470 HlMod::Associated => continue,
478 pub(crate) fn folding_range(
480 line_index: &LineIndex,
481 line_folding_only: bool,
483 ) -> lsp_types::FoldingRange {
484 let kind = match fold.kind {
485 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
486 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
487 FoldKind::Mods | FoldKind::Block | FoldKind::ArgList | FoldKind::Region => None,
490 let range = range(line_index, fold.range);
492 if line_folding_only {
493 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
494 // even if it contains text not in the folding range. To prevent that we exclude
495 // range.end.line from the folding region if there is more text after range.end
497 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
499 .take_while(|it| *it != '\n')
500 .any(|it| !it.is_whitespace());
502 let end_line = if has_more_text_on_end_line {
503 range.end.line.saturating_sub(1)
508 lsp_types::FoldingRange {
509 start_line: range.start.line,
510 start_character: None,
516 lsp_types::FoldingRange {
517 start_line: range.start.line,
518 start_character: Some(range.start.character),
519 end_line: range.end.line,
520 end_character: Some(range.end.character),
526 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
527 snap.file_id_to_url(file_id)
530 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
531 /// This will only happen when processing windows paths.
533 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
534 pub(crate) fn url_from_abs_path(path: &Path) -> lsp_types::Url {
535 assert!(path.is_absolute());
536 let url = lsp_types::Url::from_file_path(path).unwrap();
537 match path.components().next() {
538 Some(path::Component::Prefix(prefix))
539 if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
541 // Need to lowercase driver letter
546 let driver_letter_range = {
547 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
551 let start = scheme.len() + ':'.len_utf8();
552 start..(start + drive_letter.len())
555 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
556 // machinery *also* canonicalizes the drive letter. So, just massage the
558 let mut url = url.into_string();
559 url[driver_letter_range].make_ascii_lowercase();
560 lsp_types::Url::parse(&url).unwrap()
563 pub(crate) fn optional_versioned_text_document_identifier(
564 snap: &GlobalStateSnapshot,
566 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
567 let url = url(snap, file_id);
568 let version = snap.url_file_version(&url);
569 lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
572 pub(crate) fn location(
573 snap: &GlobalStateSnapshot,
575 ) -> Result<lsp_types::Location> {
576 let url = url(snap, frange.file_id);
577 let line_index = snap.file_line_index(frange.file_id)?;
578 let range = range(&line_index, frange.range);
579 let loc = lsp_types::Location::new(url, range);
583 /// Perefer using `location_link`, if the client has the cap.
584 pub(crate) fn location_from_nav(
585 snap: &GlobalStateSnapshot,
586 nav: NavigationTarget,
587 ) -> Result<lsp_types::Location> {
588 let url = url(snap, nav.file_id);
589 let line_index = snap.file_line_index(nav.file_id)?;
590 let range = range(&line_index, nav.full_range);
591 let loc = lsp_types::Location::new(url, range);
595 pub(crate) fn location_link(
596 snap: &GlobalStateSnapshot,
597 src: Option<FileRange>,
598 target: NavigationTarget,
599 ) -> Result<lsp_types::LocationLink> {
600 let origin_selection_range = match src {
602 let line_index = snap.file_line_index(src.file_id)?;
603 let range = range(&line_index, src.range);
608 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
609 let res = lsp_types::LocationLink {
610 origin_selection_range,
613 target_selection_range,
619 snap: &GlobalStateSnapshot,
620 target: NavigationTarget,
621 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
622 let line_index = snap.file_line_index(target.file_id)?;
624 let target_uri = url(snap, target.file_id);
625 let target_range = range(&line_index, target.full_range);
626 let target_selection_range =
627 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
628 Ok((target_uri, target_range, target_selection_range))
631 pub(crate) fn goto_definition_response(
632 snap: &GlobalStateSnapshot,
633 src: Option<FileRange>,
634 targets: Vec<NavigationTarget>,
635 ) -> Result<lsp_types::GotoDefinitionResponse> {
636 if snap.config.location_link() {
639 .map(|nav| location_link(snap, src, nav))
640 .collect::<Result<Vec<_>>>()?;
643 let locations = targets
646 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
648 .collect::<Result<Vec<_>>>()?;
653 pub(crate) fn snippet_text_document_edit(
654 snap: &GlobalStateSnapshot,
658 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
659 let text_document = optional_versioned_text_document_identifier(snap, file_id);
660 let line_index = snap.file_line_index(file_id)?;
661 let edits = edit.into_iter().map(|it| snippet_text_edit(&line_index, is_snippet, it)).collect();
662 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
665 pub(crate) fn snippet_text_document_ops(
666 snap: &GlobalStateSnapshot,
667 file_system_edit: FileSystemEdit,
668 ) -> Vec<lsp_ext::SnippetDocumentChangeOperation> {
669 let mut ops = Vec::new();
670 match file_system_edit {
671 FileSystemEdit::CreateFile { dst, initial_contents } => {
672 let uri = snap.anchored_path(&dst);
673 let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
678 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
679 if !initial_contents.is_empty() {
681 lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
682 let text_edit = lsp_ext::SnippetTextEdit {
683 range: lsp_types::Range::default(),
684 new_text: initial_contents,
685 insert_text_format: Some(lsp_types::InsertTextFormat::PlainText),
688 lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
689 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
692 FileSystemEdit::MoveFile { src, dst } => {
693 let old_uri = snap.file_id_to_url(src);
694 let new_uri = snap.anchored_path(&dst);
695 let rename_file = lsp_types::ResourceOp::Rename(lsp_types::RenameFile {
701 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(rename_file))
707 pub(crate) fn snippet_workspace_edit(
708 snap: &GlobalStateSnapshot,
709 source_change: SourceChange,
710 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
711 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
712 for op in source_change.file_system_edits {
713 let ops = snippet_text_document_ops(snap, op);
714 document_changes.extend_from_slice(&ops);
716 for (file_id, edit) in source_change.source_file_edits {
717 let edit = snippet_text_document_edit(&snap, source_change.is_snippet, file_id, edit)?;
718 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
721 lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
725 pub(crate) fn workspace_edit(
726 snap: &GlobalStateSnapshot,
727 source_change: SourceChange,
728 ) -> Result<lsp_types::WorkspaceEdit> {
729 assert!(!source_change.is_snippet);
730 snippet_workspace_edit(snap, source_change).map(|it| it.into())
733 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
734 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
735 lsp_types::WorkspaceEdit {
737 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
738 lsp_types::DocumentChanges::Operations(
741 .map(|change| match change {
742 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
743 lsp_types::DocumentChangeOperation::Op(op)
745 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
746 lsp_types::DocumentChangeOperation::Edit(
747 lsp_types::TextDocumentEdit {
748 text_document: edit.text_document,
753 lsp_types::OneOf::Left(lsp_types::TextEdit {
755 new_text: edit.new_text,
766 change_annotations: None,
771 pub(crate) fn call_hierarchy_item(
772 snap: &GlobalStateSnapshot,
773 target: NavigationTarget,
774 ) -> Result<lsp_types::CallHierarchyItem> {
775 let name = target.name.to_string();
776 let detail = target.description.clone();
777 let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::Function);
778 let (uri, range, selection_range) = location_info(snap, target)?;
779 Ok(lsp_types::CallHierarchyItem {
791 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
793 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
794 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
795 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
796 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
797 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
798 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
802 pub(crate) fn unresolved_code_action(
803 snap: &GlobalStateSnapshot,
804 code_action_params: lsp_types::CodeActionParams,
807 ) -> Result<lsp_ext::CodeAction> {
808 assert!(assist.source_change.is_none());
809 let res = lsp_ext::CodeAction {
810 title: assist.label.to_string(),
811 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
812 kind: Some(code_action_kind(assist.id.1)),
815 data: Some(lsp_ext::CodeActionData {
816 id: format!("{}:{}", assist.id.0, index.to_string()),
823 pub(crate) fn resolved_code_action(
824 snap: &GlobalStateSnapshot,
826 ) -> Result<lsp_ext::CodeAction> {
827 let change = assist.source_change.unwrap();
828 let res = lsp_ext::CodeAction {
829 edit: Some(snippet_workspace_edit(snap, change)?),
830 title: assist.label.to_string(),
831 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
832 kind: Some(code_action_kind(assist.id.1)),
839 pub(crate) fn runnable(
840 snap: &GlobalStateSnapshot,
843 ) -> Result<lsp_ext::Runnable> {
844 let config = snap.config.runnables();
845 let spec = CargoTargetSpec::for_file(snap, file_id)?;
846 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
847 let target = spec.as_ref().map(|s| s.target.clone());
848 let (cargo_args, executable_args) =
849 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
850 let label = runnable.label(target);
851 let location = location_link(snap, None, runnable.nav)?;
853 Ok(lsp_ext::Runnable {
855 location: Some(location),
856 kind: lsp_ext::RunnableKind::Cargo,
857 args: lsp_ext::CargoRunnable {
858 workspace_root: workspace_root.map(|it| it.into()),
859 override_cargo: config.override_cargo,
861 cargo_extra_args: config.cargo_extra_args,
868 pub(crate) fn code_lens(
869 snap: &GlobalStateSnapshot,
870 annotation: Annotation,
871 ) -> Result<lsp_types::CodeLens> {
872 match annotation.kind {
873 AnnotationKind::Runnable { debug, runnable: run } => {
874 let line_index = snap.file_line_index(run.nav.file_id)?;
875 let annotation_range = range(&line_index, annotation.range);
877 let action = run.action();
878 let r = runnable(&snap, run.nav.file_id, run)?;
880 let command = if debug {
881 command::debug_single(&r)
883 let title = action.run_title.to_string();
884 command::run_single(&r, &title)
887 Ok(lsp_types::CodeLens { range: annotation_range, command: Some(command), data: None })
889 AnnotationKind::HasImpls { position: file_position, data } => {
890 let line_index = snap.file_line_index(file_position.file_id)?;
891 let annotation_range = range(&line_index, annotation.range);
892 let url = url(snap, file_position.file_id);
894 let position = position(&line_index, file_position.offset);
896 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
898 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
900 let goto_params = lsp_types::request::GotoImplementationParams {
901 text_document_position_params: doc_pos,
902 work_done_progress_params: Default::default(),
903 partial_result_params: Default::default(),
906 let command = data.map(|ranges| {
907 let locations: Vec<lsp_types::Location> = ranges
909 .filter_map(|target| {
912 FileRange { file_id: target.file_id, range: target.full_range },
918 command::show_references(
919 implementation_title(locations.len()),
926 Ok(lsp_types::CodeLens {
927 range: annotation_range,
929 data: Some(to_value(lsp_ext::CodeLensResolveData::Impls(goto_params)).unwrap()),
932 AnnotationKind::HasReferences { position: file_position, data } => {
933 let line_index = snap.file_line_index(file_position.file_id)?;
934 let annotation_range = range(&line_index, annotation.range);
935 let url = url(snap, file_position.file_id);
937 let position = position(&line_index, file_position.offset);
939 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
941 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
943 let command = data.map(|ranges| {
944 let locations: Vec<lsp_types::Location> =
945 ranges.into_iter().filter_map(|range| location(snap, range).ok()).collect();
947 command::show_references(
948 reference_title(locations.len()),
955 Ok(lsp_types::CodeLens {
956 range: annotation_range,
958 data: Some(to_value(lsp_ext::CodeLensResolveData::References(doc_pos)).unwrap()),
964 pub(crate) mod command {
965 use ide::{FileRange, NavigationTarget};
966 use serde_json::to_value;
969 global_state::GlobalStateSnapshot,
971 to_proto::{location, location_link},
974 pub(crate) fn show_references(
976 uri: &lsp_types::Url,
977 position: lsp_types::Position,
978 locations: Vec<lsp_types::Location>,
979 ) -> lsp_types::Command {
980 // We cannot use the 'editor.action.showReferences' command directly
981 // because that command requires vscode types which we convert in the handler
982 // on the client side.
986 command: "rust-analyzer.showReferences".into(),
987 arguments: Some(vec![
988 to_value(uri).unwrap(),
989 to_value(position).unwrap(),
990 to_value(locations).unwrap(),
995 pub(crate) fn run_single(runnable: &lsp_ext::Runnable, title: &str) -> lsp_types::Command {
997 title: title.to_string(),
998 command: "rust-analyzer.runSingle".into(),
999 arguments: Some(vec![to_value(runnable).unwrap()]),
1003 pub(crate) fn debug_single(runnable: &lsp_ext::Runnable) -> lsp_types::Command {
1004 lsp_types::Command {
1005 title: "Debug".into(),
1006 command: "rust-analyzer.debugSingle".into(),
1007 arguments: Some(vec![to_value(runnable).unwrap()]),
1011 pub(crate) fn goto_location(
1012 snap: &GlobalStateSnapshot,
1013 nav: &NavigationTarget,
1014 ) -> Option<lsp_types::Command> {
1015 let value = if snap.config.location_link() {
1016 let link = location_link(snap, None, nav.clone()).ok()?;
1017 to_value(link).ok()?
1019 let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1020 let location = location(snap, range).ok()?;
1021 to_value(location).ok()?
1024 Some(lsp_types::Command {
1025 title: nav.name.to_string(),
1026 command: "rust-analyzer.gotoLocation".into(),
1027 arguments: Some(vec![value]),
1031 pub(crate) fn trigger_parameter_hints() -> lsp_types::Command {
1032 lsp_types::Command {
1033 title: "triggerParameterHints".into(),
1034 command: "editor.action.triggerParameterHints".into(),
1040 pub(crate) fn implementation_title(count: usize) -> String {
1042 "1 implementation".into()
1044 format!("{} implementations", count)
1048 pub(crate) fn reference_title(count: usize) -> String {
1050 "1 reference".into()
1052 format!("{} references", count)
1056 pub(crate) fn markup_content(markup: Markup) -> lsp_types::MarkupContent {
1057 let value = crate::markdown::format_docs(markup.as_str());
1058 lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value }
1061 pub(crate) fn rename_error(err: RenameError) -> crate::LspError {
1062 crate::LspError { code: lsp_server::ErrorCode::InvalidParams as i32, message: err.to_string() }
1069 use hir::PrefixKind;
1071 use ide_db::helpers::{insert_use::InsertUseConfig, SnippetCap};
1076 fn test_completion_with_ref() {
1079 fn foo(arg: &Foo) {}
1085 let (offset, text) = test_utils::extract_offset(fixture);
1086 let line_index = LineIndex {
1087 index: Arc::new(ide::LineIndex::new(&text)),
1088 endings: LineEndings::Unix,
1089 encoding: OffsetEncoding::Utf16,
1091 let (analysis, file_id) = Analysis::from_single_file(text);
1092 let completions: Vec<(String, Option<String>)> = analysis
1094 &ide::CompletionConfig {
1095 enable_postfix_completions: true,
1096 enable_imports_on_the_fly: true,
1097 add_call_parenthesis: true,
1098 add_call_argument_snippets: true,
1099 snippet_cap: SnippetCap::new(true),
1100 insert_use: InsertUseConfig {
1102 prefix_kind: PrefixKind::Plain,
1106 ide_db::base_db::FilePosition { file_id, offset },
1111 .filter(|c| c.label().ends_with("arg"))
1112 .map(|c| completion_item(&line_index, c))
1113 .flat_map(|comps| comps.into_iter().map(|c| (c.label, c.sort_text)))
1115 expect_test::expect![[r#"
1131 .assert_debug_eq(&completions);
1135 fn conv_fold_line_folding_only_fixup() {
1136 let text = r#"mod a;
1148 let (analysis, file_id) = Analysis::from_single_file(text.to_string());
1149 let folds = analysis.folding_ranges(file_id).unwrap();
1150 assert_eq!(folds.len(), 4);
1152 let line_index = LineIndex {
1153 index: Arc::new(ide::LineIndex::new(&text)),
1154 endings: LineEndings::Unix,
1155 encoding: OffsetEncoding::Utf16,
1157 let converted: Vec<lsp_types::FoldingRange> =
1158 folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
1160 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
1161 assert_eq!(converted.len(), expected_lines.len());
1162 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
1163 assert_eq!(folding_range.start_line, *start_line);
1164 assert_eq!(folding_range.start_character, None);
1165 assert_eq!(folding_range.end_line, *end_line);
1166 assert_eq!(folding_range.end_character, None);
1170 // `Url` is not able to parse windows paths on unix machines.
1172 #[cfg(target_os = "windows")]
1173 fn test_lowercase_drive_letter_with_drive() {
1174 let url = url_from_abs_path(Path::new("C:\\Test"));
1175 assert_eq!(url.to_string(), "file:///c:/Test");
1179 #[cfg(target_os = "windows")]
1180 fn test_drive_without_colon_passthrough() {
1181 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#));
1182 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");