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 StructureNodeKind, SymbolKind, TextEdit, TextRange, TextSize,
14 use itertools::Itertools;
15 use serde_json::to_value;
18 cargo_target_spec::CargoTargetSpec,
19 global_state::GlobalStateSnapshot,
20 line_index::{LineEndings, LineIndex, OffsetEncoding},
21 lsp_ext, semantic_tokens, Result,
24 pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position {
25 let line_col = line_index.index.line_col(offset);
26 match line_index.encoding {
27 OffsetEncoding::Utf8 => lsp_types::Position::new(line_col.line, line_col.col),
28 OffsetEncoding::Utf16 => {
29 let line_col = line_index.index.to_utf16(line_col);
30 lsp_types::Position::new(line_col.line, line_col.col)
35 pub(crate) fn range(line_index: &LineIndex, range: TextRange) -> lsp_types::Range {
36 let start = position(line_index, range.start());
37 let end = position(line_index, range.end());
38 lsp_types::Range::new(start, end)
41 pub(crate) fn symbol_kind(symbol_kind: SymbolKind) -> lsp_types::SymbolKind {
43 SymbolKind::Function => lsp_types::SymbolKind::Function,
44 SymbolKind::Struct => lsp_types::SymbolKind::Struct,
45 SymbolKind::Enum => lsp_types::SymbolKind::Enum,
46 SymbolKind::Variant => lsp_types::SymbolKind::EnumMember,
47 SymbolKind::Trait => lsp_types::SymbolKind::Interface,
48 SymbolKind::Macro => lsp_types::SymbolKind::Function,
49 SymbolKind::Module => lsp_types::SymbolKind::Module,
50 SymbolKind::TypeAlias | SymbolKind::TypeParam => lsp_types::SymbolKind::TypeParameter,
51 SymbolKind::Field => lsp_types::SymbolKind::Field,
52 SymbolKind::Static => lsp_types::SymbolKind::Constant,
53 SymbolKind::Const => lsp_types::SymbolKind::Constant,
54 SymbolKind::ConstParam => lsp_types::SymbolKind::Constant,
55 SymbolKind::Impl => lsp_types::SymbolKind::Object,
57 | SymbolKind::SelfParam
58 | SymbolKind::LifetimeParam
59 | SymbolKind::ValueParam
60 | SymbolKind::Label => lsp_types::SymbolKind::Variable,
61 SymbolKind::Union => lsp_types::SymbolKind::Struct,
65 pub(crate) fn structure_node_kind(kind: StructureNodeKind) -> lsp_types::SymbolKind {
67 StructureNodeKind::SymbolKind(symbol) => symbol_kind(symbol),
68 StructureNodeKind::Region => lsp_types::SymbolKind::Namespace,
72 pub(crate) fn document_highlight_kind(
73 reference_access: ReferenceAccess,
74 ) -> lsp_types::DocumentHighlightKind {
75 match reference_access {
76 ReferenceAccess::Read => lsp_types::DocumentHighlightKind::Read,
77 ReferenceAccess::Write => lsp_types::DocumentHighlightKind::Write,
81 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
83 Severity::Error => lsp_types::DiagnosticSeverity::Error,
84 Severity::WeakWarning => lsp_types::DiagnosticSeverity::Hint,
88 pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
89 let value = crate::markdown::format_docs(documentation.as_str());
90 let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
91 lsp_types::Documentation::MarkupContent(markup_content)
94 pub(crate) fn insert_text_format(
95 insert_text_format: InsertTextFormat,
96 ) -> lsp_types::InsertTextFormat {
97 match insert_text_format {
98 InsertTextFormat::Snippet => lsp_types::InsertTextFormat::Snippet,
99 InsertTextFormat::PlainText => lsp_types::InsertTextFormat::PlainText,
103 pub(crate) fn completion_item_kind(
104 completion_item_kind: CompletionItemKind,
105 ) -> lsp_types::CompletionItemKind {
106 match completion_item_kind {
107 CompletionItemKind::Attribute => lsp_types::CompletionItemKind::EnumMember,
108 CompletionItemKind::Binding => lsp_types::CompletionItemKind::Variable,
109 CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::Struct,
110 CompletionItemKind::Keyword => lsp_types::CompletionItemKind::Keyword,
111 CompletionItemKind::Method => lsp_types::CompletionItemKind::Method,
112 CompletionItemKind::Snippet => lsp_types::CompletionItemKind::Snippet,
113 CompletionItemKind::UnresolvedReference => lsp_types::CompletionItemKind::Reference,
114 CompletionItemKind::SymbolKind(symbol) => match symbol {
115 SymbolKind::Const => lsp_types::CompletionItemKind::Constant,
116 SymbolKind::ConstParam => lsp_types::CompletionItemKind::TypeParameter,
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::TypeParameter,
123 SymbolKind::Local => lsp_types::CompletionItemKind::Variable,
124 SymbolKind::Macro => lsp_types::CompletionItemKind::Method,
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::TypeParameter,
132 SymbolKind::Union => lsp_types::CompletionItemKind::Struct,
133 SymbolKind::ValueParam => lsp_types::CompletionItemKind::Value,
134 SymbolKind::Variant => lsp_types::CompletionItemKind::EnumMember,
139 pub(crate) fn text_edit(line_index: &LineIndex, indel: Indel) -> lsp_types::TextEdit {
140 let range = range(line_index, indel.delete);
141 let new_text = match line_index.endings {
142 LineEndings::Unix => indel.insert,
143 LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
145 lsp_types::TextEdit { range, new_text }
148 pub(crate) fn completion_text_edit(
149 line_index: &LineIndex,
150 insert_replace_support: Option<lsp_types::Position>,
152 ) -> lsp_types::CompletionTextEdit {
153 let text_edit = text_edit(line_index, indel);
154 match insert_replace_support {
155 Some(cursor_pos) => lsp_types::InsertReplaceEdit {
156 new_text: text_edit.new_text,
157 insert: lsp_types::Range { start: text_edit.range.start, end: cursor_pos },
158 replace: text_edit.range,
161 None => text_edit.into(),
165 pub(crate) fn snippet_text_edit(
166 line_index: &LineIndex,
169 ) -> lsp_ext::SnippetTextEdit {
170 let text_edit = text_edit(line_index, indel);
171 let insert_text_format =
172 if is_snippet { Some(lsp_types::InsertTextFormat::Snippet) } else { None };
173 lsp_ext::SnippetTextEdit {
174 range: text_edit.range,
175 new_text: text_edit.new_text,
180 pub(crate) fn text_edit_vec(
181 line_index: &LineIndex,
183 ) -> Vec<lsp_types::TextEdit> {
184 text_edit.into_iter().map(|indel| self::text_edit(line_index, indel)).collect()
187 pub(crate) fn snippet_text_edit_vec(
188 line_index: &LineIndex,
191 ) -> Vec<lsp_ext::SnippetTextEdit> {
194 .map(|indel| self::snippet_text_edit(line_index, is_snippet, indel))
198 pub(crate) fn completion_item(
199 insert_replace_support: Option<lsp_types::Position>,
200 line_index: &LineIndex,
201 item: CompletionItem,
202 ) -> Vec<lsp_types::CompletionItem> {
203 let mut additional_text_edits = Vec::new();
204 let mut text_edit = None;
205 // LSP does not allow arbitrary edits in completion, so we have to do a
206 // non-trivial mapping here.
207 let source_range = item.source_range();
208 for indel in item.text_edit().iter() {
209 if indel.delete.contains_range(source_range) {
210 text_edit = Some(if indel.delete == source_range {
211 self::completion_text_edit(line_index, insert_replace_support, indel.clone())
213 assert!(source_range.end() == indel.delete.end());
214 let range1 = TextRange::new(indel.delete.start(), source_range.start());
215 let range2 = source_range;
216 let indel1 = Indel::replace(range1, String::new());
217 let indel2 = Indel::replace(range2, indel.insert.clone());
218 additional_text_edits.push(self::text_edit(line_index, indel1));
219 self::completion_text_edit(line_index, insert_replace_support, indel2)
222 assert!(source_range.intersect(indel.delete).is_none());
223 let text_edit = self::text_edit(line_index, indel.clone());
224 additional_text_edits.push(text_edit);
227 let text_edit = text_edit.unwrap();
229 let mut lsp_item = lsp_types::CompletionItem {
230 label: item.label().to_string(),
231 detail: item.detail().map(|it| it.to_string()),
232 filter_text: Some(item.lookup().to_string()),
233 kind: item.kind().map(completion_item_kind),
234 text_edit: Some(text_edit),
235 additional_text_edits: Some(additional_text_edits),
236 documentation: item.documentation().map(documentation),
237 deprecated: Some(item.deprecated()),
241 fn set_score(res: &mut lsp_types::CompletionItem, relevance: CompletionRelevance) {
242 if relevance.is_relevant() {
243 res.preselect = Some(true);
245 // The relevance needs to be inverted to come up with a sort score
246 // because the client will sort ascending.
247 let sort_score = relevance.score() ^ 0xFF_FF_FF_FF;
248 // Zero pad the string to ensure values can be properly sorted
249 // by the client. Hex format is used because it is easier to
250 // visually compare very large values, which the sort text
251 // tends to be since it is the opposite of the score.
252 res.sort_text = Some(format!("{:08x}", sort_score));
255 set_score(&mut lsp_item, item.relevance());
257 if item.deprecated() {
258 lsp_item.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
261 if item.trigger_call_info() {
262 lsp_item.command = Some(command::trigger_parameter_hints());
265 let mut res = match item.ref_match() {
266 Some((mutability, relevance)) => {
267 let mut lsp_item_with_ref = lsp_item.clone();
268 set_score(&mut lsp_item_with_ref, relevance);
269 lsp_item_with_ref.label =
270 format!("&{}{}", mutability.as_keyword_for_ref(), lsp_item_with_ref.label);
271 if let Some(lsp_types::CompletionTextEdit::Edit(it)) = &mut lsp_item_with_ref.text_edit
273 it.new_text = format!("&{}{}", mutability.as_keyword_for_ref(), it.new_text);
275 vec![lsp_item_with_ref, lsp_item]
277 None => vec![lsp_item],
280 for lsp_item in res.iter_mut() {
281 lsp_item.insert_text_format = Some(insert_text_format(item.insert_text_format()));
286 pub(crate) fn signature_help(
290 ) -> lsp_types::SignatureHelp {
291 let (label, parameters) = match (concise, label_offsets) {
293 let params = call_info
295 .map(|label| lsp_types::ParameterInformation {
296 label: lsp_types::ParameterLabel::Simple(label.to_string()),
299 .collect::<Vec<_>>();
301 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
305 let params = call_info
308 .map(|it| [u32::from(it.start()), u32::from(it.end())])
309 .map(|label_offsets| lsp_types::ParameterInformation {
310 label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
313 .collect::<Vec<_>>();
314 (call_info.signature, params)
317 let mut params = Vec::new();
318 let mut label = String::new();
319 let mut first = true;
320 for param in call_info.parameter_labels() {
322 label.push_str(", ");
325 let start = label.len() as u32;
326 label.push_str(param);
327 let end = label.len() as u32;
328 params.push(lsp_types::ParameterInformation {
329 label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
338 let documentation = if concise {
341 call_info.doc.map(|doc| {
342 lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
343 kind: lsp_types::MarkupKind::Markdown,
349 let active_parameter = call_info.active_parameter.map(|it| it as u32);
351 let signature = lsp_types::SignatureInformation {
354 parameters: Some(parameters),
357 lsp_types::SignatureHelp {
358 signatures: vec![signature],
359 active_signature: None,
364 pub(crate) fn inlay_hint(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
366 label: inlay_hint.label.to_string(),
367 range: range(line_index, inlay_hint.range),
368 kind: match inlay_hint.kind {
369 InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
370 InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
371 InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
376 static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
378 pub(crate) fn semantic_tokens(
380 line_index: &LineIndex,
381 highlights: Vec<HlRange>,
382 ) -> lsp_types::SemanticTokens {
383 let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
384 let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
386 for highlight_range in highlights {
387 if highlight_range.highlight.is_empty() {
390 let (type_, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
391 let token_index = semantic_tokens::type_index(type_);
392 let modifier_bitset = mods.0;
394 for mut text_range in line_index.index.lines(highlight_range.range) {
395 if text[text_range].ends_with('\n') {
397 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
399 let range = range(&line_index, text_range);
400 builder.push(range, token_index, modifier_bitset);
407 pub(crate) fn semantic_token_delta(
408 previous: &lsp_types::SemanticTokens,
409 current: &lsp_types::SemanticTokens,
410 ) -> lsp_types::SemanticTokensDelta {
411 let result_id = current.result_id.clone();
412 let edits = semantic_tokens::diff_tokens(&previous.data, ¤t.data);
413 lsp_types::SemanticTokensDelta { result_id, edits }
416 fn semantic_token_type_and_modifiers(
417 highlight: Highlight,
418 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
419 let mut mods = semantic_tokens::ModifierSet::default();
420 let type_ = match highlight.tag {
421 HlTag::Symbol(symbol) => match symbol {
422 SymbolKind::Module => lsp_types::SemanticTokenType::NAMESPACE,
423 SymbolKind::Impl => lsp_types::SemanticTokenType::TYPE,
424 SymbolKind::Field => lsp_types::SemanticTokenType::PROPERTY,
425 SymbolKind::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
426 SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
427 SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
428 SymbolKind::Label => semantic_tokens::LABEL,
429 SymbolKind::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
430 SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
431 SymbolKind::Local => lsp_types::SemanticTokenType::VARIABLE,
432 SymbolKind::Function => {
433 if highlight.mods.contains(HlMod::Associated) {
434 lsp_types::SemanticTokenType::METHOD
436 lsp_types::SemanticTokenType::FUNCTION
439 SymbolKind::Const => {
440 mods |= semantic_tokens::CONSTANT;
441 mods |= lsp_types::SemanticTokenModifier::STATIC;
442 lsp_types::SemanticTokenType::VARIABLE
444 SymbolKind::Static => {
445 mods |= lsp_types::SemanticTokenModifier::STATIC;
446 lsp_types::SemanticTokenType::VARIABLE
448 SymbolKind::Struct => lsp_types::SemanticTokenType::STRUCT,
449 SymbolKind::Enum => lsp_types::SemanticTokenType::ENUM,
450 SymbolKind::Variant => lsp_types::SemanticTokenType::ENUM_MEMBER,
451 SymbolKind::Union => semantic_tokens::UNION,
452 SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
453 SymbolKind::Trait => lsp_types::SemanticTokenType::INTERFACE,
454 SymbolKind::Macro => lsp_types::SemanticTokenType::MACRO,
456 HlTag::Attribute => semantic_tokens::ATTRIBUTE,
457 HlTag::BoolLiteral => semantic_tokens::BOOLEAN,
458 HlTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
459 HlTag::ByteLiteral | HlTag::NumericLiteral => lsp_types::SemanticTokenType::NUMBER,
460 HlTag::CharLiteral => semantic_tokens::CHAR_LITERAL,
461 HlTag::Comment => lsp_types::SemanticTokenType::COMMENT,
462 HlTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
463 HlTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
464 HlTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
465 HlTag::None => semantic_tokens::GENERIC,
466 HlTag::Operator => lsp_types::SemanticTokenType::OPERATOR,
467 HlTag::StringLiteral => lsp_types::SemanticTokenType::STRING,
468 HlTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
469 HlTag::Punctuation(punct) => match punct {
470 HlPunct::Bracket => semantic_tokens::BRACKET,
471 HlPunct::Brace => semantic_tokens::BRACE,
472 HlPunct::Parenthesis => semantic_tokens::PARENTHESIS,
473 HlPunct::Angle => semantic_tokens::ANGLE,
474 HlPunct::Comma => semantic_tokens::COMMA,
475 HlPunct::Dot => semantic_tokens::DOT,
476 HlPunct::Colon => semantic_tokens::COLON,
477 HlPunct::Semi => semantic_tokens::SEMICOLON,
478 HlPunct::Other => semantic_tokens::PUNCTUATION,
482 for modifier in highlight.mods.iter() {
483 let modifier = match modifier {
484 HlMod::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
485 HlMod::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
486 HlMod::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
487 HlMod::Injected => semantic_tokens::INJECTED,
488 HlMod::ControlFlow => semantic_tokens::CONTROL_FLOW,
489 HlMod::Mutable => semantic_tokens::MUTABLE,
490 HlMod::Consuming => semantic_tokens::CONSUMING,
491 HlMod::Unsafe => semantic_tokens::UNSAFE,
492 HlMod::Callable => semantic_tokens::CALLABLE,
493 HlMod::Static => lsp_types::SemanticTokenModifier::STATIC,
494 HlMod::IntraDocLink => semantic_tokens::INTRA_DOC_LINK,
495 HlMod::Trait => semantic_tokens::TRAIT_MODIFIER,
496 HlMod::Associated => continue,
504 pub(crate) fn folding_range(
506 line_index: &LineIndex,
507 line_folding_only: bool,
509 ) -> lsp_types::FoldingRange {
510 let kind = match fold.kind {
511 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
512 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
513 FoldKind::Region => Some(lsp_types::FoldingRangeKind::Region),
519 | FoldKind::Array => None,
522 let range = range(line_index, fold.range);
524 if line_folding_only {
525 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
526 // even if it contains text not in the folding range. To prevent that we exclude
527 // range.end.line from the folding region if there is more text after range.end
529 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
531 .take_while(|it| *it != '\n')
532 .any(|it| !it.is_whitespace());
534 let end_line = if has_more_text_on_end_line {
535 range.end.line.saturating_sub(1)
540 lsp_types::FoldingRange {
541 start_line: range.start.line,
542 start_character: None,
548 lsp_types::FoldingRange {
549 start_line: range.start.line,
550 start_character: Some(range.start.character),
551 end_line: range.end.line,
552 end_character: Some(range.end.character),
558 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
559 snap.file_id_to_url(file_id)
562 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
563 /// This will only happen when processing windows paths.
565 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
566 pub(crate) fn url_from_abs_path(path: &Path) -> lsp_types::Url {
567 assert!(path.is_absolute());
568 let url = lsp_types::Url::from_file_path(path).unwrap();
569 match path.components().next() {
570 Some(path::Component::Prefix(prefix))
571 if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
573 // Need to lowercase driver letter
578 let driver_letter_range = {
579 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
583 let start = scheme.len() + ':'.len_utf8();
584 start..(start + drive_letter.len())
587 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
588 // machinery *also* canonicalizes the drive letter. So, just massage the
590 let mut url = url.into_string();
591 url[driver_letter_range].make_ascii_lowercase();
592 lsp_types::Url::parse(&url).unwrap()
595 pub(crate) fn optional_versioned_text_document_identifier(
596 snap: &GlobalStateSnapshot,
598 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
599 let url = url(snap, file_id);
600 let version = snap.url_file_version(&url);
601 lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
604 pub(crate) fn location(
605 snap: &GlobalStateSnapshot,
607 ) -> Result<lsp_types::Location> {
608 let url = url(snap, frange.file_id);
609 let line_index = snap.file_line_index(frange.file_id)?;
610 let range = range(&line_index, frange.range);
611 let loc = lsp_types::Location::new(url, range);
615 /// Perefer using `location_link`, if the client has the cap.
616 pub(crate) fn location_from_nav(
617 snap: &GlobalStateSnapshot,
618 nav: NavigationTarget,
619 ) -> Result<lsp_types::Location> {
620 let url = url(snap, nav.file_id);
621 let line_index = snap.file_line_index(nav.file_id)?;
622 let range = range(&line_index, nav.full_range);
623 let loc = lsp_types::Location::new(url, range);
627 pub(crate) fn location_link(
628 snap: &GlobalStateSnapshot,
629 src: Option<FileRange>,
630 target: NavigationTarget,
631 ) -> Result<lsp_types::LocationLink> {
632 let origin_selection_range = match src {
634 let line_index = snap.file_line_index(src.file_id)?;
635 let range = range(&line_index, src.range);
640 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
641 let res = lsp_types::LocationLink {
642 origin_selection_range,
645 target_selection_range,
651 snap: &GlobalStateSnapshot,
652 target: NavigationTarget,
653 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
654 let line_index = snap.file_line_index(target.file_id)?;
656 let target_uri = url(snap, target.file_id);
657 let target_range = range(&line_index, target.full_range);
658 let target_selection_range =
659 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
660 Ok((target_uri, target_range, target_selection_range))
663 pub(crate) fn goto_definition_response(
664 snap: &GlobalStateSnapshot,
665 src: Option<FileRange>,
666 targets: Vec<NavigationTarget>,
667 ) -> Result<lsp_types::GotoDefinitionResponse> {
668 if snap.config.location_link() {
671 .map(|nav| location_link(snap, src, nav))
672 .collect::<Result<Vec<_>>>()?;
675 let locations = targets
678 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
680 .collect::<Result<Vec<_>>>()?;
685 pub(crate) fn text_document_edit(
686 snap: &GlobalStateSnapshot,
689 ) -> Result<lsp_types::TextDocumentEdit> {
690 let text_document = optional_versioned_text_document_identifier(snap, file_id);
691 let line_index = snap.file_line_index(file_id)?;
693 edit.into_iter().map(|it| lsp_types::OneOf::Left(text_edit(&line_index, it))).collect();
694 Ok(lsp_types::TextDocumentEdit { text_document, edits })
697 pub(crate) fn snippet_text_document_edit(
698 snap: &GlobalStateSnapshot,
702 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
703 let text_document = optional_versioned_text_document_identifier(snap, file_id);
704 let line_index = snap.file_line_index(file_id)?;
705 let edits = edit.into_iter().map(|it| snippet_text_edit(&line_index, is_snippet, it)).collect();
706 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
709 pub(crate) fn snippet_text_document_ops(
710 snap: &GlobalStateSnapshot,
711 file_system_edit: FileSystemEdit,
712 ) -> Vec<lsp_ext::SnippetDocumentChangeOperation> {
713 let mut ops = Vec::new();
714 match file_system_edit {
715 FileSystemEdit::CreateFile { dst, initial_contents } => {
716 let uri = snap.anchored_path(&dst);
717 let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
722 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
723 if !initial_contents.is_empty() {
725 lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
726 let text_edit = lsp_ext::SnippetTextEdit {
727 range: lsp_types::Range::default(),
728 new_text: initial_contents,
729 insert_text_format: Some(lsp_types::InsertTextFormat::PlainText),
732 lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
733 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
736 FileSystemEdit::MoveFile { src, dst } => {
737 let old_uri = snap.file_id_to_url(src);
738 let new_uri = snap.anchored_path(&dst);
739 let rename_file = lsp_types::ResourceOp::Rename(lsp_types::RenameFile {
745 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(rename_file))
751 pub(crate) fn snippet_workspace_edit(
752 snap: &GlobalStateSnapshot,
753 source_change: SourceChange,
754 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
755 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
756 for op in source_change.file_system_edits {
757 let ops = snippet_text_document_ops(snap, op);
758 document_changes.extend_from_slice(&ops);
760 for (file_id, edit) in source_change.source_file_edits {
761 let edit = snippet_text_document_edit(&snap, source_change.is_snippet, file_id, edit)?;
762 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
765 lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
769 pub(crate) fn workspace_edit(
770 snap: &GlobalStateSnapshot,
771 source_change: SourceChange,
772 ) -> Result<lsp_types::WorkspaceEdit> {
773 assert!(!source_change.is_snippet);
774 snippet_workspace_edit(snap, source_change).map(|it| it.into())
777 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
778 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
779 lsp_types::WorkspaceEdit {
781 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
782 lsp_types::DocumentChanges::Operations(
785 .map(|change| match change {
786 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
787 lsp_types::DocumentChangeOperation::Op(op)
789 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
790 lsp_types::DocumentChangeOperation::Edit(
791 lsp_types::TextDocumentEdit {
792 text_document: edit.text_document,
797 lsp_types::OneOf::Left(lsp_types::TextEdit {
799 new_text: edit.new_text,
810 change_annotations: None,
815 pub(crate) fn call_hierarchy_item(
816 snap: &GlobalStateSnapshot,
817 target: NavigationTarget,
818 ) -> Result<lsp_types::CallHierarchyItem> {
819 let name = target.name.to_string();
820 let detail = target.description.clone();
821 let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::Function);
822 let (uri, range, selection_range) = location_info(snap, target)?;
823 Ok(lsp_types::CallHierarchyItem {
835 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
837 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
838 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
839 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
840 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
841 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
842 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
846 pub(crate) fn code_action(
847 snap: &GlobalStateSnapshot,
849 resolve_data: Option<(usize, lsp_types::CodeActionParams)>,
850 ) -> Result<lsp_ext::CodeAction> {
851 let mut res = lsp_ext::CodeAction {
852 title: assist.label.to_string(),
853 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
854 kind: Some(code_action_kind(assist.id.1)),
859 match (assist.source_change, resolve_data) {
860 (Some(it), _) => res.edit = Some(snippet_workspace_edit(snap, it)?),
861 (None, Some((index, code_action_params))) => {
862 res.data = Some(lsp_ext::CodeActionData {
863 id: format!("{}:{}", assist.id.0, index.to_string()),
868 stdx::never!("assist should always be resolved if client can't do lazy resolving")
874 pub(crate) fn runnable(
875 snap: &GlobalStateSnapshot,
877 ) -> Result<lsp_ext::Runnable> {
878 let config = snap.config.runnables();
879 let spec = CargoTargetSpec::for_file(snap, runnable.nav.file_id)?;
880 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
881 let target = spec.as_ref().map(|s| s.target.clone());
882 let (cargo_args, executable_args) =
883 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
884 let label = runnable.label(target);
885 let location = location_link(snap, None, runnable.nav)?;
887 Ok(lsp_ext::Runnable {
889 location: Some(location),
890 kind: lsp_ext::RunnableKind::Cargo,
891 args: lsp_ext::CargoRunnable {
892 workspace_root: workspace_root.map(|it| it.into()),
893 override_cargo: config.override_cargo,
895 cargo_extra_args: config.cargo_extra_args,
902 pub(crate) fn code_lens(
903 snap: &GlobalStateSnapshot,
904 annotation: Annotation,
905 ) -> Result<lsp_types::CodeLens> {
906 match annotation.kind {
907 AnnotationKind::Runnable { debug, runnable: run } => {
908 let line_index = snap.file_line_index(run.nav.file_id)?;
909 let annotation_range = range(&line_index, annotation.range);
911 let action = run.action();
912 let r = runnable(&snap, run)?;
914 let command = if debug {
915 command::debug_single(&r)
917 let title = action.run_title.to_string();
918 command::run_single(&r, &title)
921 Ok(lsp_types::CodeLens { range: annotation_range, command: Some(command), data: None })
923 AnnotationKind::HasImpls { position: file_position, data } => {
924 let line_index = snap.file_line_index(file_position.file_id)?;
925 let annotation_range = range(&line_index, annotation.range);
926 let url = url(snap, file_position.file_id);
928 let position = position(&line_index, file_position.offset);
930 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
932 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
934 let goto_params = lsp_types::request::GotoImplementationParams {
935 text_document_position_params: doc_pos,
936 work_done_progress_params: Default::default(),
937 partial_result_params: Default::default(),
940 let command = data.map(|ranges| {
941 let locations: Vec<lsp_types::Location> = ranges
943 .filter_map(|target| {
946 FileRange { file_id: target.file_id, range: target.full_range },
952 command::show_references(
953 implementation_title(locations.len()),
960 Ok(lsp_types::CodeLens {
961 range: annotation_range,
963 data: Some(to_value(lsp_ext::CodeLensResolveData::Impls(goto_params)).unwrap()),
966 AnnotationKind::HasReferences { position: file_position, data } => {
967 let line_index = snap.file_line_index(file_position.file_id)?;
968 let annotation_range = range(&line_index, annotation.range);
969 let url = url(snap, file_position.file_id);
971 let position = position(&line_index, file_position.offset);
973 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
975 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
977 let command = data.map(|ranges| {
978 let locations: Vec<lsp_types::Location> =
979 ranges.into_iter().filter_map(|range| location(snap, range).ok()).collect();
981 command::show_references(
982 reference_title(locations.len()),
989 Ok(lsp_types::CodeLens {
990 range: annotation_range,
992 data: Some(to_value(lsp_ext::CodeLensResolveData::References(doc_pos)).unwrap()),
998 pub(crate) mod command {
999 use ide::{FileRange, NavigationTarget};
1000 use serde_json::to_value;
1003 global_state::GlobalStateSnapshot,
1005 to_proto::{location, location_link},
1008 pub(crate) fn show_references(
1010 uri: &lsp_types::Url,
1011 position: lsp_types::Position,
1012 locations: Vec<lsp_types::Location>,
1013 ) -> lsp_types::Command {
1014 // We cannot use the 'editor.action.showReferences' command directly
1015 // because that command requires vscode types which we convert in the handler
1016 // on the client side.
1018 lsp_types::Command {
1020 command: "rust-analyzer.showReferences".into(),
1021 arguments: Some(vec![
1022 to_value(uri).unwrap(),
1023 to_value(position).unwrap(),
1024 to_value(locations).unwrap(),
1029 pub(crate) fn run_single(runnable: &lsp_ext::Runnable, title: &str) -> lsp_types::Command {
1030 lsp_types::Command {
1031 title: title.to_string(),
1032 command: "rust-analyzer.runSingle".into(),
1033 arguments: Some(vec![to_value(runnable).unwrap()]),
1037 pub(crate) fn debug_single(runnable: &lsp_ext::Runnable) -> lsp_types::Command {
1038 lsp_types::Command {
1039 title: "Debug".into(),
1040 command: "rust-analyzer.debugSingle".into(),
1041 arguments: Some(vec![to_value(runnable).unwrap()]),
1045 pub(crate) fn goto_location(
1046 snap: &GlobalStateSnapshot,
1047 nav: &NavigationTarget,
1048 ) -> Option<lsp_types::Command> {
1049 let value = if snap.config.location_link() {
1050 let link = location_link(snap, None, nav.clone()).ok()?;
1051 to_value(link).ok()?
1053 let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1054 let location = location(snap, range).ok()?;
1055 to_value(location).ok()?
1058 Some(lsp_types::Command {
1059 title: nav.name.to_string(),
1060 command: "rust-analyzer.gotoLocation".into(),
1061 arguments: Some(vec![value]),
1065 pub(crate) fn trigger_parameter_hints() -> lsp_types::Command {
1066 lsp_types::Command {
1067 title: "triggerParameterHints".into(),
1068 command: "editor.action.triggerParameterHints".into(),
1074 pub(crate) fn implementation_title(count: usize) -> String {
1076 "1 implementation".into()
1078 format!("{} implementations", count)
1082 pub(crate) fn reference_title(count: usize) -> String {
1084 "1 reference".into()
1086 format!("{} references", count)
1090 pub(crate) fn markup_content(markup: Markup) -> lsp_types::MarkupContent {
1091 let value = crate::markdown::format_docs(markup.as_str());
1092 lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value }
1095 pub(crate) fn rename_error(err: RenameError) -> crate::LspError {
1096 crate::LspError { code: lsp_server::ErrorCode::InvalidParams as i32, message: err.to_string() }
1104 use ide_db::helpers::{
1105 insert_use::{InsertUseConfig, PrefixKind},
1112 fn test_completion_with_ref() {
1115 fn foo(arg: &Foo) {}
1121 let (offset, text) = test_utils::extract_offset(fixture);
1122 let line_index = LineIndex {
1123 index: Arc::new(ide::LineIndex::new(&text)),
1124 endings: LineEndings::Unix,
1125 encoding: OffsetEncoding::Utf16,
1127 let (analysis, file_id) = Analysis::from_single_file(text);
1128 let completions: Vec<(String, Option<String>)> = analysis
1130 &ide::CompletionConfig {
1131 enable_postfix_completions: true,
1132 enable_imports_on_the_fly: true,
1133 add_call_parenthesis: true,
1134 add_call_argument_snippets: true,
1135 snippet_cap: SnippetCap::new(true),
1136 insert_use: InsertUseConfig {
1138 prefix_kind: PrefixKind::Plain,
1142 ide_db::base_db::FilePosition { file_id, offset },
1147 .filter(|c| c.label().ends_with("arg"))
1148 .map(|c| completion_item(None, &line_index, c))
1149 .flat_map(|comps| comps.into_iter().map(|c| (c.label, c.sort_text)))
1151 expect_test::expect![[r#"
1167 .assert_debug_eq(&completions);
1171 fn conv_fold_line_folding_only_fixup() {
1172 let text = r#"mod a;
1184 let (analysis, file_id) = Analysis::from_single_file(text.to_string());
1185 let folds = analysis.folding_ranges(file_id).unwrap();
1186 assert_eq!(folds.len(), 4);
1188 let line_index = LineIndex {
1189 index: Arc::new(ide::LineIndex::new(&text)),
1190 endings: LineEndings::Unix,
1191 encoding: OffsetEncoding::Utf16,
1193 let converted: Vec<lsp_types::FoldingRange> =
1194 folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
1196 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
1197 assert_eq!(converted.len(), expected_lines.len());
1198 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
1199 assert_eq!(folding_range.start_line, *start_line);
1200 assert_eq!(folding_range.start_character, None);
1201 assert_eq!(folding_range.end_line, *end_line);
1202 assert_eq!(folding_range.end_character, None);
1206 // `Url` is not able to parse windows paths on unix machines.
1208 #[cfg(target_os = "windows")]
1209 fn test_lowercase_drive_letter_with_drive() {
1210 let url = url_from_abs_path(Path::new("C:\\Test"));
1211 assert_eq!(url.to_string(), "file:///c:/Test");
1215 #[cfg(target_os = "windows")]
1216 fn test_drive_without_colon_passthrough() {
1217 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#));
1218 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");