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 Documentation, FileId, FileRange, FileSystemEdit, Fold, FoldKind, Highlight, HlMod, HlPunct,
10 HlRange, HlTag, Indel, InlayHint, InlayKind, InsertTextFormat, Markup, NavigationTarget,
11 ReferenceAccess, RenameError, Runnable, Severity, SourceChange, TextEdit, TextRange, TextSize,
13 use ide_db::SymbolKind;
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 document_highlight_kind(
66 reference_access: ReferenceAccess,
67 ) -> lsp_types::DocumentHighlightKind {
68 match reference_access {
69 ReferenceAccess::Read => lsp_types::DocumentHighlightKind::Read,
70 ReferenceAccess::Write => lsp_types::DocumentHighlightKind::Write,
74 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
76 Severity::Error => lsp_types::DiagnosticSeverity::Error,
77 Severity::WeakWarning => lsp_types::DiagnosticSeverity::Hint,
81 pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
82 let value = crate::markdown::format_docs(documentation.as_str());
83 let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
84 lsp_types::Documentation::MarkupContent(markup_content)
87 pub(crate) fn insert_text_format(
88 insert_text_format: InsertTextFormat,
89 ) -> lsp_types::InsertTextFormat {
90 match insert_text_format {
91 InsertTextFormat::Snippet => lsp_types::InsertTextFormat::Snippet,
92 InsertTextFormat::PlainText => lsp_types::InsertTextFormat::PlainText,
96 pub(crate) fn completion_item_kind(
97 completion_item_kind: CompletionItemKind,
98 ) -> lsp_types::CompletionItemKind {
99 match completion_item_kind {
100 CompletionItemKind::Attribute => lsp_types::CompletionItemKind::EnumMember,
101 CompletionItemKind::Binding => lsp_types::CompletionItemKind::Variable,
102 CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::Struct,
103 CompletionItemKind::Keyword => lsp_types::CompletionItemKind::Keyword,
104 CompletionItemKind::Method => lsp_types::CompletionItemKind::Method,
105 CompletionItemKind::Snippet => lsp_types::CompletionItemKind::Snippet,
106 CompletionItemKind::UnresolvedReference => lsp_types::CompletionItemKind::Reference,
107 CompletionItemKind::SymbolKind(symbol) => match symbol {
108 SymbolKind::Const => lsp_types::CompletionItemKind::Constant,
109 SymbolKind::ConstParam => lsp_types::CompletionItemKind::TypeParameter,
110 SymbolKind::Enum => lsp_types::CompletionItemKind::Enum,
111 SymbolKind::Field => lsp_types::CompletionItemKind::Field,
112 SymbolKind::Function => lsp_types::CompletionItemKind::Function,
113 SymbolKind::Impl => lsp_types::CompletionItemKind::Text,
114 SymbolKind::Label => lsp_types::CompletionItemKind::Variable,
115 SymbolKind::LifetimeParam => lsp_types::CompletionItemKind::TypeParameter,
116 SymbolKind::Local => lsp_types::CompletionItemKind::Variable,
117 SymbolKind::Macro => lsp_types::CompletionItemKind::Method,
118 SymbolKind::Module => lsp_types::CompletionItemKind::Module,
119 SymbolKind::SelfParam => lsp_types::CompletionItemKind::Value,
120 SymbolKind::Static => lsp_types::CompletionItemKind::Value,
121 SymbolKind::Struct => lsp_types::CompletionItemKind::Struct,
122 SymbolKind::Trait => lsp_types::CompletionItemKind::Interface,
123 SymbolKind::TypeAlias => lsp_types::CompletionItemKind::Struct,
124 SymbolKind::TypeParam => lsp_types::CompletionItemKind::TypeParameter,
125 SymbolKind::Union => lsp_types::CompletionItemKind::Struct,
126 SymbolKind::ValueParam => lsp_types::CompletionItemKind::Value,
127 SymbolKind::Variant => lsp_types::CompletionItemKind::EnumMember,
132 pub(crate) fn text_edit(line_index: &LineIndex, indel: Indel) -> lsp_types::TextEdit {
133 let range = range(line_index, indel.delete);
134 let new_text = match line_index.endings {
135 LineEndings::Unix => indel.insert,
136 LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
138 lsp_types::TextEdit { range, new_text }
141 pub(crate) fn snippet_text_edit(
142 line_index: &LineIndex,
145 ) -> lsp_ext::SnippetTextEdit {
146 let text_edit = text_edit(line_index, indel);
147 let insert_text_format =
148 if is_snippet { Some(lsp_types::InsertTextFormat::Snippet) } else { None };
149 lsp_ext::SnippetTextEdit {
150 range: text_edit.range,
151 new_text: text_edit.new_text,
156 pub(crate) fn text_edit_vec(
157 line_index: &LineIndex,
159 ) -> Vec<lsp_types::TextEdit> {
160 text_edit.into_iter().map(|indel| self::text_edit(line_index, indel)).collect()
163 pub(crate) fn snippet_text_edit_vec(
164 line_index: &LineIndex,
167 ) -> Vec<lsp_ext::SnippetTextEdit> {
170 .map(|indel| self::snippet_text_edit(line_index, is_snippet, indel))
174 pub(crate) fn completion_item(
175 line_index: &LineIndex,
176 completion_item: CompletionItem,
177 ) -> Vec<lsp_types::CompletionItem> {
178 fn set_score(res: &mut lsp_types::CompletionItem, label: &str) {
179 res.preselect = Some(true);
180 // HACK: sort preselect items first
181 res.sort_text = Some(format!(" {}", label));
184 let mut additional_text_edits = Vec::new();
185 let mut text_edit = None;
186 // LSP does not allow arbitrary edits in completion, so we have to do a
187 // non-trivial mapping here.
188 let source_range = completion_item.source_range();
189 for indel in completion_item.text_edit().iter() {
190 if indel.delete.contains_range(source_range) {
191 text_edit = Some(if indel.delete == source_range {
192 self::text_edit(line_index, indel.clone())
194 assert!(source_range.end() == indel.delete.end());
195 let range1 = TextRange::new(indel.delete.start(), source_range.start());
196 let range2 = source_range;
197 let indel1 = Indel::replace(range1, String::new());
198 let indel2 = Indel::replace(range2, indel.insert.clone());
199 additional_text_edits.push(self::text_edit(line_index, indel1));
200 self::text_edit(line_index, indel2)
203 assert!(source_range.intersect(indel.delete).is_none());
204 let text_edit = self::text_edit(line_index, indel.clone());
205 additional_text_edits.push(text_edit);
208 let text_edit = text_edit.unwrap();
210 let mut res = lsp_types::CompletionItem {
211 label: completion_item.label().to_string(),
212 detail: completion_item.detail().map(|it| it.to_string()),
213 filter_text: Some(completion_item.lookup().to_string()),
214 kind: completion_item.kind().map(completion_item_kind),
215 text_edit: Some(text_edit.into()),
216 additional_text_edits: Some(additional_text_edits),
217 documentation: completion_item.documentation().map(documentation),
218 deprecated: Some(completion_item.deprecated()),
222 if completion_item.score().is_some() {
223 set_score(&mut res, completion_item.label());
226 if completion_item.deprecated() {
227 res.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
230 if completion_item.trigger_call_info() {
231 res.command = Some(command::trigger_parameter_hints());
234 let mut all_results = match completion_item.ref_match() {
236 let mut refed = res.clone();
237 let (mutability, _score) = ref_match;
238 let label = format!("&{}{}", mutability.as_keyword_for_ref(), refed.label);
239 set_score(&mut refed, &label);
246 for mut r in all_results.iter_mut() {
247 r.insert_text_format = Some(insert_text_format(completion_item.insert_text_format()));
252 pub(crate) fn signature_help(
256 ) -> lsp_types::SignatureHelp {
257 let (label, parameters) = match (concise, label_offsets) {
259 let params = call_info
261 .map(|label| lsp_types::ParameterInformation {
262 label: lsp_types::ParameterLabel::Simple(label.to_string()),
265 .collect::<Vec<_>>();
267 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
271 let params = call_info
274 .map(|it| [u32::from(it.start()).into(), u32::from(it.end()).into()])
275 .map(|label_offsets| lsp_types::ParameterInformation {
276 label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
279 .collect::<Vec<_>>();
280 (call_info.signature, params)
283 let mut params = Vec::new();
284 let mut label = String::new();
285 let mut first = true;
286 for param in call_info.parameter_labels() {
288 label.push_str(", ");
291 let start = label.len() as u32;
292 label.push_str(param);
293 let end = label.len() as u32;
294 params.push(lsp_types::ParameterInformation {
295 label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
304 let documentation = if concise {
307 call_info.doc.map(|doc| {
308 lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
309 kind: lsp_types::MarkupKind::Markdown,
315 let active_parameter = call_info.active_parameter.map(|it| it as u32);
317 let signature = lsp_types::SignatureInformation {
320 parameters: Some(parameters),
323 lsp_types::SignatureHelp {
324 signatures: vec![signature],
325 active_signature: None,
330 pub(crate) fn inlay_hint(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
332 label: inlay_hint.label.to_string(),
333 range: range(line_index, inlay_hint.range),
334 kind: match inlay_hint.kind {
335 InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
336 InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
337 InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
342 static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
344 pub(crate) fn semantic_tokens(
346 line_index: &LineIndex,
347 highlights: Vec<HlRange>,
348 ) -> lsp_types::SemanticTokens {
349 let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
350 let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
352 for highlight_range in highlights {
353 if highlight_range.highlight.is_empty() {
356 let (type_, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
357 let token_index = semantic_tokens::type_index(type_);
358 let modifier_bitset = mods.0;
360 for mut text_range in line_index.index.lines(highlight_range.range) {
361 if text[text_range].ends_with('\n') {
363 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
365 let range = range(&line_index, text_range);
366 builder.push(range, token_index, modifier_bitset);
373 pub(crate) fn semantic_token_delta(
374 previous: &lsp_types::SemanticTokens,
375 current: &lsp_types::SemanticTokens,
376 ) -> lsp_types::SemanticTokensDelta {
377 let result_id = current.result_id.clone();
378 let edits = semantic_tokens::diff_tokens(&previous.data, ¤t.data);
379 lsp_types::SemanticTokensDelta { result_id, edits }
382 fn semantic_token_type_and_modifiers(
383 highlight: Highlight,
384 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
385 let mut mods = semantic_tokens::ModifierSet::default();
386 let type_ = match highlight.tag {
387 HlTag::Symbol(symbol) => match symbol {
388 SymbolKind::Module => lsp_types::SemanticTokenType::NAMESPACE,
389 SymbolKind::Impl => lsp_types::SemanticTokenType::TYPE,
390 SymbolKind::Field => lsp_types::SemanticTokenType::PROPERTY,
391 SymbolKind::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
392 SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
393 SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
394 SymbolKind::Label => semantic_tokens::LABEL,
395 SymbolKind::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
396 SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
397 SymbolKind::Local => lsp_types::SemanticTokenType::VARIABLE,
398 SymbolKind::Function => {
399 if highlight.mods.contains(HlMod::Associated) {
400 lsp_types::SemanticTokenType::METHOD
402 lsp_types::SemanticTokenType::FUNCTION
405 SymbolKind::Const => {
406 mods |= semantic_tokens::CONSTANT;
407 mods |= lsp_types::SemanticTokenModifier::STATIC;
408 lsp_types::SemanticTokenType::VARIABLE
410 SymbolKind::Static => {
411 mods |= lsp_types::SemanticTokenModifier::STATIC;
412 lsp_types::SemanticTokenType::VARIABLE
414 SymbolKind::Struct => lsp_types::SemanticTokenType::STRUCT,
415 SymbolKind::Enum => lsp_types::SemanticTokenType::ENUM,
416 SymbolKind::Variant => lsp_types::SemanticTokenType::ENUM_MEMBER,
417 SymbolKind::Union => semantic_tokens::UNION,
418 SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
419 SymbolKind::Trait => lsp_types::SemanticTokenType::INTERFACE,
420 SymbolKind::Macro => lsp_types::SemanticTokenType::MACRO,
422 HlTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
423 HlTag::None => semantic_tokens::GENERIC,
424 HlTag::ByteLiteral | HlTag::NumericLiteral => lsp_types::SemanticTokenType::NUMBER,
425 HlTag::BoolLiteral => semantic_tokens::BOOLEAN,
426 HlTag::StringLiteral => lsp_types::SemanticTokenType::STRING,
427 HlTag::CharLiteral => semantic_tokens::CHAR_LITERAL,
428 HlTag::Comment => lsp_types::SemanticTokenType::COMMENT,
429 HlTag::Attribute => semantic_tokens::ATTRIBUTE,
430 HlTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
431 HlTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
432 HlTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
433 HlTag::Operator => lsp_types::SemanticTokenType::OPERATOR,
434 HlTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
435 HlTag::Punctuation(punct) => match punct {
436 HlPunct::Bracket => semantic_tokens::BRACKET,
437 HlPunct::Brace => semantic_tokens::BRACE,
438 HlPunct::Parenthesis => semantic_tokens::PARENTHESIS,
439 HlPunct::Angle => semantic_tokens::ANGLE,
440 HlPunct::Comma => semantic_tokens::COMMA,
441 HlPunct::Dot => semantic_tokens::DOT,
442 HlPunct::Colon => semantic_tokens::COLON,
443 HlPunct::Semi => semantic_tokens::SEMICOLON,
444 HlPunct::Other => semantic_tokens::PUNCTUATION,
448 for modifier in highlight.mods.iter() {
449 let modifier = match modifier {
450 HlMod::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
451 HlMod::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
452 HlMod::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
453 HlMod::Injected => semantic_tokens::INJECTED,
454 HlMod::ControlFlow => semantic_tokens::CONTROL_FLOW,
455 HlMod::Mutable => semantic_tokens::MUTABLE,
456 HlMod::Consuming => semantic_tokens::CONSUMING,
457 HlMod::Unsafe => semantic_tokens::UNSAFE,
458 HlMod::Callable => semantic_tokens::CALLABLE,
459 HlMod::Static => lsp_types::SemanticTokenModifier::STATIC,
460 HlMod::Associated => continue,
468 pub(crate) fn folding_range(
470 line_index: &LineIndex,
471 line_folding_only: bool,
473 ) -> lsp_types::FoldingRange {
474 let kind = match fold.kind {
475 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
476 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
477 FoldKind::Mods | FoldKind::Block | FoldKind::ArgList => None,
480 let range = range(line_index, fold.range);
482 if line_folding_only {
483 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
484 // even if it contains text not in the folding range. To prevent that we exclude
485 // range.end.line from the folding region if there is more text after range.end
487 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
489 .take_while(|it| *it != '\n')
490 .any(|it| !it.is_whitespace());
492 let end_line = if has_more_text_on_end_line {
493 range.end.line.saturating_sub(1)
498 lsp_types::FoldingRange {
499 start_line: range.start.line,
500 start_character: None,
506 lsp_types::FoldingRange {
507 start_line: range.start.line,
508 start_character: Some(range.start.character),
509 end_line: range.end.line,
510 end_character: Some(range.end.character),
516 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
517 snap.file_id_to_url(file_id)
520 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
521 /// This will only happen when processing windows paths.
523 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
524 pub(crate) fn url_from_abs_path(path: &Path) -> lsp_types::Url {
525 assert!(path.is_absolute());
526 let url = lsp_types::Url::from_file_path(path).unwrap();
527 match path.components().next() {
528 Some(path::Component::Prefix(prefix))
529 if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
531 // Need to lowercase driver letter
536 let driver_letter_range = {
537 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
541 let start = scheme.len() + ':'.len_utf8();
542 start..(start + drive_letter.len())
545 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
546 // machinery *also* canonicalizes the drive letter. So, just massage the
548 let mut url = url.into_string();
549 url[driver_letter_range].make_ascii_lowercase();
550 lsp_types::Url::parse(&url).unwrap()
553 pub(crate) fn optional_versioned_text_document_identifier(
554 snap: &GlobalStateSnapshot,
556 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
557 let url = url(snap, file_id);
558 let version = snap.url_file_version(&url);
559 lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
562 pub(crate) fn location(
563 snap: &GlobalStateSnapshot,
565 ) -> Result<lsp_types::Location> {
566 let url = url(snap, frange.file_id);
567 let line_index = snap.file_line_index(frange.file_id)?;
568 let range = range(&line_index, frange.range);
569 let loc = lsp_types::Location::new(url, range);
573 /// Perefer using `location_link`, if the client has the cap.
574 pub(crate) fn location_from_nav(
575 snap: &GlobalStateSnapshot,
576 nav: NavigationTarget,
577 ) -> Result<lsp_types::Location> {
578 let url = url(snap, nav.file_id);
579 let line_index = snap.file_line_index(nav.file_id)?;
580 let range = range(&line_index, nav.full_range);
581 let loc = lsp_types::Location::new(url, range);
585 pub(crate) fn location_link(
586 snap: &GlobalStateSnapshot,
587 src: Option<FileRange>,
588 target: NavigationTarget,
589 ) -> Result<lsp_types::LocationLink> {
590 let origin_selection_range = match src {
592 let line_index = snap.file_line_index(src.file_id)?;
593 let range = range(&line_index, src.range);
598 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
599 let res = lsp_types::LocationLink {
600 origin_selection_range,
603 target_selection_range,
609 snap: &GlobalStateSnapshot,
610 target: NavigationTarget,
611 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
612 let line_index = snap.file_line_index(target.file_id)?;
614 let target_uri = url(snap, target.file_id);
615 let target_range = range(&line_index, target.full_range);
616 let target_selection_range =
617 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
618 Ok((target_uri, target_range, target_selection_range))
621 pub(crate) fn goto_definition_response(
622 snap: &GlobalStateSnapshot,
623 src: Option<FileRange>,
624 targets: Vec<NavigationTarget>,
625 ) -> Result<lsp_types::GotoDefinitionResponse> {
626 if snap.config.location_link() {
629 .map(|nav| location_link(snap, src, nav))
630 .collect::<Result<Vec<_>>>()?;
633 let locations = targets
636 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
638 .collect::<Result<Vec<_>>>()?;
643 pub(crate) fn snippet_text_document_edit(
644 snap: &GlobalStateSnapshot,
648 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
649 let text_document = optional_versioned_text_document_identifier(snap, file_id);
650 let line_index = snap.file_line_index(file_id)?;
651 let edits = edit.into_iter().map(|it| snippet_text_edit(&line_index, is_snippet, it)).collect();
652 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
655 pub(crate) fn snippet_text_document_ops(
656 snap: &GlobalStateSnapshot,
657 file_system_edit: FileSystemEdit,
658 ) -> Vec<lsp_ext::SnippetDocumentChangeOperation> {
659 let mut ops = Vec::new();
660 match file_system_edit {
661 FileSystemEdit::CreateFile { dst, initial_contents } => {
662 let uri = snap.anchored_path(&dst);
663 let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
668 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
669 if !initial_contents.is_empty() {
671 lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
672 let text_edit = lsp_ext::SnippetTextEdit {
673 range: lsp_types::Range::default(),
674 new_text: initial_contents,
675 insert_text_format: Some(lsp_types::InsertTextFormat::PlainText),
678 lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
679 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
682 FileSystemEdit::MoveFile { src, dst } => {
683 let old_uri = snap.file_id_to_url(src);
684 let new_uri = snap.anchored_path(&dst);
685 let rename_file = lsp_types::ResourceOp::Rename(lsp_types::RenameFile {
691 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(rename_file))
697 pub(crate) fn snippet_workspace_edit(
698 snap: &GlobalStateSnapshot,
699 source_change: SourceChange,
700 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
701 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
702 for op in source_change.file_system_edits {
703 let ops = snippet_text_document_ops(snap, op);
704 document_changes.extend_from_slice(&ops);
706 for (file_id, edit) in source_change.source_file_edits {
707 let edit = snippet_text_document_edit(&snap, source_change.is_snippet, file_id, edit)?;
708 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
711 lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
715 pub(crate) fn workspace_edit(
716 snap: &GlobalStateSnapshot,
717 source_change: SourceChange,
718 ) -> Result<lsp_types::WorkspaceEdit> {
719 assert!(!source_change.is_snippet);
720 snippet_workspace_edit(snap, source_change).map(|it| it.into())
723 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
724 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
725 lsp_types::WorkspaceEdit {
727 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
728 lsp_types::DocumentChanges::Operations(
731 .map(|change| match change {
732 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
733 lsp_types::DocumentChangeOperation::Op(op)
735 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
736 lsp_types::DocumentChangeOperation::Edit(
737 lsp_types::TextDocumentEdit {
738 text_document: edit.text_document,
743 lsp_types::OneOf::Left(lsp_types::TextEdit {
745 new_text: edit.new_text,
756 change_annotations: None,
761 pub(crate) fn call_hierarchy_item(
762 snap: &GlobalStateSnapshot,
763 target: NavigationTarget,
764 ) -> Result<lsp_types::CallHierarchyItem> {
765 let name = target.name.to_string();
766 let detail = target.description.clone();
767 let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::Function);
768 let (uri, range, selection_range) = location_info(snap, target)?;
769 Ok(lsp_types::CallHierarchyItem {
781 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
783 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
784 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
785 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
786 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
787 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
788 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
792 pub(crate) fn unresolved_code_action(
793 snap: &GlobalStateSnapshot,
794 code_action_params: lsp_types::CodeActionParams,
797 ) -> Result<lsp_ext::CodeAction> {
798 assert!(assist.source_change.is_none());
799 let res = lsp_ext::CodeAction {
800 title: assist.label.to_string(),
801 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
802 kind: Some(code_action_kind(assist.id.1)),
805 data: Some(lsp_ext::CodeActionData {
806 id: format!("{}:{}", assist.id.0, index.to_string()),
813 pub(crate) fn resolved_code_action(
814 snap: &GlobalStateSnapshot,
816 ) -> Result<lsp_ext::CodeAction> {
817 let change = assist.source_change.unwrap();
818 let res = lsp_ext::CodeAction {
819 edit: Some(snippet_workspace_edit(snap, change)?),
820 title: assist.label.to_string(),
821 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
822 kind: Some(code_action_kind(assist.id.1)),
829 pub(crate) fn runnable(
830 snap: &GlobalStateSnapshot,
833 ) -> Result<lsp_ext::Runnable> {
834 let config = snap.config.runnables();
835 let spec = CargoTargetSpec::for_file(snap, file_id)?;
836 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
837 let target = spec.as_ref().map(|s| s.target.clone());
838 let (cargo_args, executable_args) =
839 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
840 let label = runnable.label(target);
841 let location = location_link(snap, None, runnable.nav)?;
843 Ok(lsp_ext::Runnable {
845 location: Some(location),
846 kind: lsp_ext::RunnableKind::Cargo,
847 args: lsp_ext::CargoRunnable {
848 workspace_root: workspace_root.map(|it| it.into()),
849 override_cargo: config.override_cargo,
851 cargo_extra_args: config.cargo_extra_args,
858 pub(crate) fn code_lens(
859 snap: &GlobalStateSnapshot,
860 annotation: Annotation,
861 ) -> Result<lsp_types::CodeLens> {
862 match annotation.kind {
863 AnnotationKind::Runnable { debug, runnable: run } => {
864 let line_index = snap.file_line_index(run.nav.file_id)?;
865 let annotation_range = range(&line_index, annotation.range);
867 let action = run.action();
868 let r = runnable(&snap, run.nav.file_id, run)?;
870 let command = if debug {
871 command::debug_single(&r)
873 let title = action.run_title.to_string();
874 command::run_single(&r, &title)
877 Ok(lsp_types::CodeLens { range: annotation_range, command: Some(command), data: None })
879 AnnotationKind::HasImpls { position: file_position, data } => {
880 let line_index = snap.file_line_index(file_position.file_id)?;
881 let annotation_range = range(&line_index, annotation.range);
882 let url = url(snap, file_position.file_id);
884 let position = position(&line_index, file_position.offset);
886 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
888 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
890 let goto_params = lsp_types::request::GotoImplementationParams {
891 text_document_position_params: doc_pos,
892 work_done_progress_params: Default::default(),
893 partial_result_params: Default::default(),
896 let command = data.map(|ranges| {
897 let locations: Vec<lsp_types::Location> = ranges
899 .filter_map(|target| {
902 FileRange { file_id: target.file_id, range: target.full_range },
908 command::show_references(
909 implementation_title(locations.len()),
916 Ok(lsp_types::CodeLens {
917 range: annotation_range,
919 data: Some(to_value(lsp_ext::CodeLensResolveData::Impls(goto_params)).unwrap()),
922 AnnotationKind::HasReferences { position: file_position, data } => {
923 let line_index = snap.file_line_index(file_position.file_id)?;
924 let annotation_range = range(&line_index, annotation.range);
925 let url = url(snap, file_position.file_id);
927 let position = position(&line_index, file_position.offset);
929 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
931 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
933 let command = data.map(|ranges| {
934 let locations: Vec<lsp_types::Location> =
935 ranges.into_iter().filter_map(|range| location(snap, range).ok()).collect();
937 command::show_references(
938 reference_title(locations.len()),
945 Ok(lsp_types::CodeLens {
946 range: annotation_range,
948 data: Some(to_value(lsp_ext::CodeLensResolveData::References(doc_pos)).unwrap()),
954 pub(crate) mod command {
955 use ide::{FileRange, NavigationTarget};
956 use serde_json::to_value;
959 global_state::GlobalStateSnapshot,
961 to_proto::{location, location_link},
964 pub(crate) fn show_references(
966 uri: &lsp_types::Url,
967 position: lsp_types::Position,
968 locations: Vec<lsp_types::Location>,
969 ) -> lsp_types::Command {
970 // We cannot use the 'editor.action.showReferences' command directly
971 // because that command requires vscode types which we convert in the handler
972 // on the client side.
976 command: "rust-analyzer.showReferences".into(),
977 arguments: Some(vec![
978 to_value(uri).unwrap(),
979 to_value(position).unwrap(),
980 to_value(locations).unwrap(),
985 pub(crate) fn run_single(runnable: &lsp_ext::Runnable, title: &str) -> lsp_types::Command {
987 title: title.to_string(),
988 command: "rust-analyzer.runSingle".into(),
989 arguments: Some(vec![to_value(runnable).unwrap()]),
993 pub(crate) fn debug_single(runnable: &lsp_ext::Runnable) -> lsp_types::Command {
995 title: "Debug".into(),
996 command: "rust-analyzer.debugSingle".into(),
997 arguments: Some(vec![to_value(runnable).unwrap()]),
1001 pub(crate) fn goto_location(
1002 snap: &GlobalStateSnapshot,
1003 nav: &NavigationTarget,
1004 ) -> Option<lsp_types::Command> {
1005 let value = if snap.config.location_link() {
1006 let link = location_link(snap, None, nav.clone()).ok()?;
1007 to_value(link).ok()?
1009 let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1010 let location = location(snap, range).ok()?;
1011 to_value(location).ok()?
1014 Some(lsp_types::Command {
1015 title: nav.name.to_string(),
1016 command: "rust-analyzer.gotoLocation".into(),
1017 arguments: Some(vec![value]),
1021 pub(crate) fn trigger_parameter_hints() -> lsp_types::Command {
1022 lsp_types::Command {
1023 title: "triggerParameterHints".into(),
1024 command: "editor.action.triggerParameterHints".into(),
1030 pub(crate) fn implementation_title(count: usize) -> String {
1032 "1 implementation".into()
1034 format!("{} implementations", count)
1038 pub(crate) fn reference_title(count: usize) -> String {
1040 "1 reference".into()
1042 format!("{} references", count)
1046 pub(crate) fn markup_content(markup: Markup) -> lsp_types::MarkupContent {
1047 let value = crate::markdown::format_docs(markup.as_str());
1048 lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value }
1051 pub(crate) fn rename_error(err: RenameError) -> crate::LspError {
1052 crate::LspError { code: lsp_server::ErrorCode::InvalidParams as i32, message: err.to_string() }
1059 use hir::PrefixKind;
1061 use ide_db::helpers::{insert_use::InsertUseConfig, SnippetCap};
1066 fn test_completion_with_ref() {
1069 fn foo(arg: &Foo) {}
1075 let (offset, text) = test_utils::extract_offset(fixture);
1076 let line_index = LineIndex {
1077 index: Arc::new(ide::LineIndex::new(&text)),
1078 endings: LineEndings::Unix,
1079 encoding: OffsetEncoding::Utf16,
1081 let (analysis, file_id) = Analysis::from_single_file(text);
1082 let completions: Vec<(String, Option<String>)> = analysis
1084 &ide::CompletionConfig {
1085 enable_postfix_completions: true,
1086 enable_imports_on_the_fly: true,
1087 add_call_parenthesis: true,
1088 add_call_argument_snippets: true,
1089 snippet_cap: SnippetCap::new(true),
1090 insert_use: InsertUseConfig { merge: None, prefix_kind: PrefixKind::Plain },
1092 ide_db::base_db::FilePosition { file_id, offset },
1097 .filter(|c| c.label().ends_with("arg"))
1098 .map(|c| completion_item(&line_index, c))
1099 .flat_map(|comps| comps.into_iter().map(|c| (c.label, c.sort_text)))
1101 expect_test::expect![[r#"
1115 .assert_debug_eq(&completions);
1119 fn conv_fold_line_folding_only_fixup() {
1120 let text = r#"mod a;
1132 let (analysis, file_id) = Analysis::from_single_file(text.to_string());
1133 let folds = analysis.folding_ranges(file_id).unwrap();
1134 assert_eq!(folds.len(), 4);
1136 let line_index = LineIndex {
1137 index: Arc::new(ide::LineIndex::new(&text)),
1138 endings: LineEndings::Unix,
1139 encoding: OffsetEncoding::Utf16,
1141 let converted: Vec<lsp_types::FoldingRange> =
1142 folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
1144 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
1145 assert_eq!(converted.len(), expected_lines.len());
1146 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
1147 assert_eq!(folding_range.start_line, *start_line);
1148 assert_eq!(folding_range.start_character, None);
1149 assert_eq!(folding_range.end_line, *end_line);
1150 assert_eq!(folding_range.end_character, None);
1154 // `Url` is not able to parse windows paths on unix machines.
1156 #[cfg(target_os = "windows")]
1157 fn test_lowercase_drive_letter_with_drive() {
1158 let url = url_from_abs_path(Path::new("C:\\Test"));
1159 assert_eq!(url.to_string(), "file:///c:/Test");
1163 #[cfg(target_os = "windows")]
1164 fn test_drive_without_colon_passthrough() {
1165 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#));
1166 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");