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, LineIndex, Markup,
11 NavigationTarget, ReferenceAccess, RenameError, Runnable, Severity, SourceChange, TextEdit,
14 use ide_db::SymbolKind;
15 use itertools::Itertools;
16 use serde_json::to_value;
19 cargo_target_spec::CargoTargetSpec, global_state::GlobalStateSnapshot,
20 line_endings::LineEndings, lsp_ext, semantic_tokens, Result,
23 pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position {
24 let line_col = line_index.line_col(offset);
25 lsp_types::Position::new(line_col.line, line_col.col_utf16)
28 pub(crate) fn range(line_index: &LineIndex, range: TextRange) -> lsp_types::Range {
29 let start = position(line_index, range.start());
30 let end = position(line_index, range.end());
31 lsp_types::Range::new(start, end)
34 pub(crate) fn symbol_kind(symbol_kind: SymbolKind) -> lsp_types::SymbolKind {
36 SymbolKind::Function => lsp_types::SymbolKind::Function,
37 SymbolKind::Struct => lsp_types::SymbolKind::Struct,
38 SymbolKind::Enum => lsp_types::SymbolKind::Enum,
39 SymbolKind::Variant => lsp_types::SymbolKind::EnumMember,
40 SymbolKind::Trait => lsp_types::SymbolKind::Interface,
41 SymbolKind::Macro => lsp_types::SymbolKind::Function,
42 SymbolKind::Module => lsp_types::SymbolKind::Module,
43 SymbolKind::TypeAlias | SymbolKind::TypeParam => lsp_types::SymbolKind::TypeParameter,
44 SymbolKind::Field => lsp_types::SymbolKind::Field,
45 SymbolKind::Static => lsp_types::SymbolKind::Constant,
46 SymbolKind::Const => lsp_types::SymbolKind::Constant,
47 SymbolKind::ConstParam => lsp_types::SymbolKind::Constant,
48 SymbolKind::Impl => lsp_types::SymbolKind::Object,
50 | SymbolKind::SelfParam
51 | SymbolKind::LifetimeParam
52 | SymbolKind::ValueParam
53 | SymbolKind::Label => lsp_types::SymbolKind::Variable,
54 SymbolKind::Union => lsp_types::SymbolKind::Struct,
58 pub(crate) fn document_highlight_kind(
59 reference_access: ReferenceAccess,
60 ) -> lsp_types::DocumentHighlightKind {
61 match reference_access {
62 ReferenceAccess::Read => lsp_types::DocumentHighlightKind::Read,
63 ReferenceAccess::Write => lsp_types::DocumentHighlightKind::Write,
67 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
69 Severity::Error => lsp_types::DiagnosticSeverity::Error,
70 Severity::WeakWarning => lsp_types::DiagnosticSeverity::Hint,
74 pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
75 let value = crate::markdown::format_docs(documentation.as_str());
76 let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
77 lsp_types::Documentation::MarkupContent(markup_content)
80 pub(crate) fn insert_text_format(
81 insert_text_format: InsertTextFormat,
82 ) -> lsp_types::InsertTextFormat {
83 match insert_text_format {
84 InsertTextFormat::Snippet => lsp_types::InsertTextFormat::Snippet,
85 InsertTextFormat::PlainText => lsp_types::InsertTextFormat::PlainText,
89 pub(crate) fn completion_item_kind(
90 completion_item_kind: CompletionItemKind,
91 ) -> lsp_types::CompletionItemKind {
92 match completion_item_kind {
93 CompletionItemKind::Attribute => lsp_types::CompletionItemKind::EnumMember,
94 CompletionItemKind::Binding => lsp_types::CompletionItemKind::Variable,
95 CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::Struct,
96 CompletionItemKind::Keyword => lsp_types::CompletionItemKind::Keyword,
97 CompletionItemKind::Method => lsp_types::CompletionItemKind::Method,
98 CompletionItemKind::Snippet => lsp_types::CompletionItemKind::Snippet,
99 CompletionItemKind::UnresolvedReference => lsp_types::CompletionItemKind::Reference,
100 CompletionItemKind::SymbolKind(symbol) => match symbol {
101 SymbolKind::Const => lsp_types::CompletionItemKind::Constant,
102 SymbolKind::ConstParam => lsp_types::CompletionItemKind::TypeParameter,
103 SymbolKind::Enum => lsp_types::CompletionItemKind::Enum,
104 SymbolKind::Field => lsp_types::CompletionItemKind::Field,
105 SymbolKind::Function => lsp_types::CompletionItemKind::Function,
106 SymbolKind::Impl => lsp_types::CompletionItemKind::Text,
107 SymbolKind::Label => lsp_types::CompletionItemKind::Variable,
108 SymbolKind::LifetimeParam => lsp_types::CompletionItemKind::TypeParameter,
109 SymbolKind::Local => lsp_types::CompletionItemKind::Variable,
110 SymbolKind::Macro => lsp_types::CompletionItemKind::Method,
111 SymbolKind::Module => lsp_types::CompletionItemKind::Module,
112 SymbolKind::SelfParam => lsp_types::CompletionItemKind::Value,
113 SymbolKind::Static => lsp_types::CompletionItemKind::Value,
114 SymbolKind::Struct => lsp_types::CompletionItemKind::Struct,
115 SymbolKind::Trait => lsp_types::CompletionItemKind::Interface,
116 SymbolKind::TypeAlias => lsp_types::CompletionItemKind::Struct,
117 SymbolKind::TypeParam => lsp_types::CompletionItemKind::TypeParameter,
118 SymbolKind::Union => lsp_types::CompletionItemKind::Struct,
119 SymbolKind::ValueParam => lsp_types::CompletionItemKind::Value,
120 SymbolKind::Variant => lsp_types::CompletionItemKind::EnumMember,
125 pub(crate) fn text_edit(
126 line_index: &LineIndex,
127 line_endings: LineEndings,
129 ) -> lsp_types::TextEdit {
130 let range = range(line_index, indel.delete);
131 let new_text = match line_endings {
132 LineEndings::Unix => indel.insert,
133 LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
135 lsp_types::TextEdit { range, new_text }
138 pub(crate) fn snippet_text_edit(
139 line_index: &LineIndex,
140 line_endings: LineEndings,
143 ) -> lsp_ext::SnippetTextEdit {
144 let text_edit = text_edit(line_index, line_endings, indel);
145 let insert_text_format =
146 if is_snippet { Some(lsp_types::InsertTextFormat::Snippet) } else { None };
147 lsp_ext::SnippetTextEdit {
148 range: text_edit.range,
149 new_text: text_edit.new_text,
154 pub(crate) fn text_edit_vec(
155 line_index: &LineIndex,
156 line_endings: LineEndings,
158 ) -> Vec<lsp_types::TextEdit> {
159 text_edit.into_iter().map(|indel| self::text_edit(line_index, line_endings, indel)).collect()
162 pub(crate) fn snippet_text_edit_vec(
163 line_index: &LineIndex,
164 line_endings: LineEndings,
167 ) -> Vec<lsp_ext::SnippetTextEdit> {
170 .map(|indel| self::snippet_text_edit(line_index, line_endings, is_snippet, indel))
174 pub(crate) fn completion_item(
175 line_index: &LineIndex,
176 line_endings: LineEndings,
177 completion_item: CompletionItem,
178 ) -> Vec<lsp_types::CompletionItem> {
179 fn set_score(res: &mut lsp_types::CompletionItem, label: &str) {
180 res.preselect = Some(true);
181 // HACK: sort preselect items first
182 res.sort_text = Some(format!(" {}", label));
185 let mut additional_text_edits = Vec::new();
186 let mut text_edit = None;
187 // LSP does not allow arbitrary edits in completion, so we have to do a
188 // non-trivial mapping here.
189 let source_range = completion_item.source_range();
190 for indel in completion_item.text_edit().iter() {
191 if indel.delete.contains_range(source_range) {
192 text_edit = Some(if indel.delete == source_range {
193 self::text_edit(line_index, line_endings, indel.clone())
195 assert!(source_range.end() == indel.delete.end());
196 let range1 = TextRange::new(indel.delete.start(), source_range.start());
197 let range2 = source_range;
198 let indel1 = Indel::replace(range1, String::new());
199 let indel2 = Indel::replace(range2, indel.insert.clone());
200 additional_text_edits.push(self::text_edit(line_index, line_endings, indel1));
201 self::text_edit(line_index, line_endings, indel2)
204 assert!(source_range.intersect(indel.delete).is_none());
205 let text_edit = self::text_edit(line_index, line_endings, indel.clone());
206 additional_text_edits.push(text_edit);
209 let text_edit = text_edit.unwrap();
211 let mut res = lsp_types::CompletionItem {
212 label: completion_item.label().to_string(),
213 detail: completion_item.detail().map(|it| it.to_string()),
214 filter_text: Some(completion_item.lookup().to_string()),
215 kind: completion_item.kind().map(completion_item_kind),
216 text_edit: Some(text_edit.into()),
217 additional_text_edits: Some(additional_text_edits),
218 documentation: completion_item.documentation().map(documentation),
219 deprecated: Some(completion_item.deprecated()),
223 if completion_item.score().is_some() {
224 set_score(&mut res, completion_item.label());
227 if completion_item.deprecated() {
228 res.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
231 if completion_item.trigger_call_info() {
232 res.command = Some(command::trigger_parameter_hints());
235 let mut all_results = match completion_item.ref_match() {
237 let mut refed = res.clone();
238 let (mutability, _score) = ref_match;
239 let label = format!("&{}{}", mutability.as_keyword_for_ref(), refed.label);
240 set_score(&mut refed, &label);
247 for mut r in all_results.iter_mut() {
248 r.insert_text_format = Some(insert_text_format(completion_item.insert_text_format()));
253 pub(crate) fn signature_help(
257 ) -> lsp_types::SignatureHelp {
258 let (label, parameters) = match (concise, label_offsets) {
260 let params = call_info
262 .map(|label| lsp_types::ParameterInformation {
263 label: lsp_types::ParameterLabel::Simple(label.to_string()),
266 .collect::<Vec<_>>();
268 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
272 let params = call_info
275 .map(|it| [u32::from(it.start()).into(), u32::from(it.end()).into()])
276 .map(|label_offsets| lsp_types::ParameterInformation {
277 label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
280 .collect::<Vec<_>>();
281 (call_info.signature, params)
284 let mut params = Vec::new();
285 let mut label = String::new();
286 let mut first = true;
287 for param in call_info.parameter_labels() {
289 label.push_str(", ");
292 let start = label.len() as u32;
293 label.push_str(param);
294 let end = label.len() as u32;
295 params.push(lsp_types::ParameterInformation {
296 label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
305 let documentation = if concise {
308 call_info.doc.map(|doc| {
309 lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
310 kind: lsp_types::MarkupKind::Markdown,
316 let active_parameter = call_info.active_parameter.map(|it| it as u32);
318 let signature = lsp_types::SignatureInformation {
321 parameters: Some(parameters),
324 lsp_types::SignatureHelp {
325 signatures: vec![signature],
326 active_signature: None,
331 pub(crate) fn inlay_hint(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
333 label: inlay_hint.label.to_string(),
334 range: range(line_index, inlay_hint.range),
335 kind: match inlay_hint.kind {
336 InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
337 InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
338 InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
343 static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
345 pub(crate) fn semantic_tokens(
347 line_index: &LineIndex,
348 highlights: Vec<HlRange>,
349 ) -> lsp_types::SemanticTokens {
350 let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
351 let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
353 for highlight_range in highlights {
354 if highlight_range.highlight.is_empty() {
357 let (type_, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
358 let token_index = semantic_tokens::type_index(type_);
359 let modifier_bitset = mods.0;
361 for mut text_range in line_index.lines(highlight_range.range) {
362 if text[text_range].ends_with('\n') {
364 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
366 let range = range(&line_index, text_range);
367 builder.push(range, token_index, modifier_bitset);
374 pub(crate) fn semantic_token_delta(
375 previous: &lsp_types::SemanticTokens,
376 current: &lsp_types::SemanticTokens,
377 ) -> lsp_types::SemanticTokensDelta {
378 let result_id = current.result_id.clone();
379 let edits = semantic_tokens::diff_tokens(&previous.data, ¤t.data);
380 lsp_types::SemanticTokensDelta { result_id, edits }
383 fn semantic_token_type_and_modifiers(
384 highlight: Highlight,
385 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
386 let mut mods = semantic_tokens::ModifierSet::default();
387 let type_ = match highlight.tag {
388 HlTag::Symbol(symbol) => match symbol {
389 SymbolKind::Module => lsp_types::SemanticTokenType::NAMESPACE,
390 SymbolKind::Impl => lsp_types::SemanticTokenType::TYPE,
391 SymbolKind::Field => lsp_types::SemanticTokenType::PROPERTY,
392 SymbolKind::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
393 SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
394 SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
395 SymbolKind::Label => semantic_tokens::LABEL,
396 SymbolKind::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
397 SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
398 SymbolKind::Local => lsp_types::SemanticTokenType::VARIABLE,
399 SymbolKind::Function => {
400 if highlight.mods.contains(HlMod::Associated) {
401 lsp_types::SemanticTokenType::METHOD
403 lsp_types::SemanticTokenType::FUNCTION
406 SymbolKind::Const => {
407 mods |= semantic_tokens::CONSTANT;
408 mods |= lsp_types::SemanticTokenModifier::STATIC;
409 lsp_types::SemanticTokenType::VARIABLE
411 SymbolKind::Static => {
412 mods |= lsp_types::SemanticTokenModifier::STATIC;
413 lsp_types::SemanticTokenType::VARIABLE
415 SymbolKind::Struct => lsp_types::SemanticTokenType::STRUCT,
416 SymbolKind::Enum => lsp_types::SemanticTokenType::ENUM,
417 SymbolKind::Variant => lsp_types::SemanticTokenType::ENUM_MEMBER,
418 SymbolKind::Union => semantic_tokens::UNION,
419 SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
420 SymbolKind::Trait => lsp_types::SemanticTokenType::INTERFACE,
421 SymbolKind::Macro => lsp_types::SemanticTokenType::MACRO,
423 HlTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
424 HlTag::None => semantic_tokens::GENERIC,
425 HlTag::ByteLiteral | HlTag::NumericLiteral => lsp_types::SemanticTokenType::NUMBER,
426 HlTag::BoolLiteral => semantic_tokens::BOOLEAN,
427 HlTag::StringLiteral => lsp_types::SemanticTokenType::STRING,
428 HlTag::CharLiteral => semantic_tokens::CHAR_LITERAL,
429 HlTag::Comment => lsp_types::SemanticTokenType::COMMENT,
430 HlTag::Attribute => semantic_tokens::ATTRIBUTE,
431 HlTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
432 HlTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
433 HlTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
434 HlTag::Operator => lsp_types::SemanticTokenType::OPERATOR,
435 HlTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
436 HlTag::Punctuation(punct) => match punct {
437 HlPunct::Bracket => semantic_tokens::BRACKET,
438 HlPunct::Brace => semantic_tokens::BRACE,
439 HlPunct::Parenthesis => semantic_tokens::PARENTHESIS,
440 HlPunct::Angle => semantic_tokens::ANGLE,
441 HlPunct::Comma => semantic_tokens::COMMA,
442 HlPunct::Dot => semantic_tokens::DOT,
443 HlPunct::Colon => semantic_tokens::COLON,
444 HlPunct::Semi => semantic_tokens::SEMICOLON,
445 HlPunct::Other => semantic_tokens::PUNCTUATION,
449 for modifier in highlight.mods.iter() {
450 let modifier = match modifier {
451 HlMod::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
452 HlMod::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
453 HlMod::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
454 HlMod::Injected => semantic_tokens::INJECTED,
455 HlMod::ControlFlow => semantic_tokens::CONTROL_FLOW,
456 HlMod::Mutable => semantic_tokens::MUTABLE,
457 HlMod::Consuming => semantic_tokens::CONSUMING,
458 HlMod::Unsafe => semantic_tokens::UNSAFE,
459 HlMod::Callable => semantic_tokens::CALLABLE,
460 HlMod::Static => lsp_types::SemanticTokenModifier::STATIC,
461 HlMod::Associated => continue,
469 pub(crate) fn folding_range(
471 line_index: &LineIndex,
472 line_folding_only: bool,
474 ) -> lsp_types::FoldingRange {
475 let kind = match fold.kind {
476 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
477 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
478 FoldKind::Mods | FoldKind::Block | FoldKind::ArgList => None,
481 let range = range(line_index, fold.range);
483 if line_folding_only {
484 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
485 // even if it contains text not in the folding range. To prevent that we exclude
486 // range.end.line from the folding region if there is more text after range.end
488 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
490 .take_while(|it| *it != '\n')
491 .any(|it| !it.is_whitespace());
493 let end_line = if has_more_text_on_end_line {
494 range.end.line.saturating_sub(1)
499 lsp_types::FoldingRange {
500 start_line: range.start.line,
501 start_character: None,
507 lsp_types::FoldingRange {
508 start_line: range.start.line,
509 start_character: Some(range.start.character),
510 end_line: range.end.line,
511 end_character: Some(range.end.character),
517 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
518 snap.file_id_to_url(file_id)
521 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
522 /// This will only happen when processing windows paths.
524 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
525 pub(crate) fn url_from_abs_path(path: &Path) -> lsp_types::Url {
526 assert!(path.is_absolute());
527 let url = lsp_types::Url::from_file_path(path).unwrap();
528 match path.components().next() {
529 Some(path::Component::Prefix(prefix))
530 if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
532 // Need to lowercase driver letter
537 let driver_letter_range = {
538 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
542 let start = scheme.len() + ':'.len_utf8();
543 start..(start + drive_letter.len())
546 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
547 // machinery *also* canonicalizes the drive letter. So, just massage the
549 let mut url = url.into_string();
550 url[driver_letter_range].make_ascii_lowercase();
551 lsp_types::Url::parse(&url).unwrap()
554 pub(crate) fn optional_versioned_text_document_identifier(
555 snap: &GlobalStateSnapshot,
557 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
558 let url = url(snap, file_id);
559 let version = snap.url_file_version(&url);
560 lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
563 pub(crate) fn location(
564 snap: &GlobalStateSnapshot,
566 ) -> Result<lsp_types::Location> {
567 let url = url(snap, frange.file_id);
568 let line_index = snap.analysis.file_line_index(frange.file_id)?;
569 let range = range(&line_index, frange.range);
570 let loc = lsp_types::Location::new(url, range);
574 /// Perefer using `location_link`, if the client has the cap.
575 pub(crate) fn location_from_nav(
576 snap: &GlobalStateSnapshot,
577 nav: NavigationTarget,
578 ) -> Result<lsp_types::Location> {
579 let url = url(snap, nav.file_id);
580 let line_index = snap.analysis.file_line_index(nav.file_id)?;
581 let range = range(&line_index, nav.full_range);
582 let loc = lsp_types::Location::new(url, range);
586 pub(crate) fn location_link(
587 snap: &GlobalStateSnapshot,
588 src: Option<FileRange>,
589 target: NavigationTarget,
590 ) -> Result<lsp_types::LocationLink> {
591 let origin_selection_range = match src {
593 let line_index = snap.analysis.file_line_index(src.file_id)?;
594 let range = range(&line_index, src.range);
599 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
600 let res = lsp_types::LocationLink {
601 origin_selection_range,
604 target_selection_range,
610 snap: &GlobalStateSnapshot,
611 target: NavigationTarget,
612 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
613 let line_index = snap.analysis.file_line_index(target.file_id)?;
615 let target_uri = url(snap, target.file_id);
616 let target_range = range(&line_index, target.full_range);
617 let target_selection_range =
618 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
619 Ok((target_uri, target_range, target_selection_range))
622 pub(crate) fn goto_definition_response(
623 snap: &GlobalStateSnapshot,
624 src: Option<FileRange>,
625 targets: Vec<NavigationTarget>,
626 ) -> Result<lsp_types::GotoDefinitionResponse> {
627 if snap.config.location_link() {
630 .map(|nav| location_link(snap, src, nav))
631 .collect::<Result<Vec<_>>>()?;
634 let locations = targets
637 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
639 .collect::<Result<Vec<_>>>()?;
644 pub(crate) fn snippet_text_document_edit(
645 snap: &GlobalStateSnapshot,
649 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
650 let text_document = optional_versioned_text_document_identifier(snap, file_id);
651 let line_index = snap.analysis.file_line_index(file_id)?;
652 let line_endings = snap.file_line_endings(file_id);
655 .map(|it| snippet_text_edit(&line_index, line_endings, is_snippet, it))
657 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
660 pub(crate) fn snippet_text_document_ops(
661 snap: &GlobalStateSnapshot,
662 file_system_edit: FileSystemEdit,
663 ) -> Vec<lsp_ext::SnippetDocumentChangeOperation> {
664 let mut ops = Vec::new();
665 match file_system_edit {
666 FileSystemEdit::CreateFile { dst, initial_contents } => {
667 let uri = snap.anchored_path(&dst);
668 let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
673 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
674 if !initial_contents.is_empty() {
676 lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
677 let range = range(&LineIndex::new(""), TextRange::empty(TextSize::from(0)));
678 let text_edit = lsp_ext::SnippetTextEdit {
680 new_text: initial_contents,
681 insert_text_format: Some(lsp_types::InsertTextFormat::PlainText),
684 lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
685 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
688 FileSystemEdit::MoveFile { src, dst } => {
689 let old_uri = snap.file_id_to_url(src);
690 let new_uri = snap.anchored_path(&dst);
691 let rename_file = lsp_types::ResourceOp::Rename(lsp_types::RenameFile {
697 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(rename_file))
703 pub(crate) fn snippet_workspace_edit(
704 snap: &GlobalStateSnapshot,
705 source_change: SourceChange,
706 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
707 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
708 for op in source_change.file_system_edits {
709 let ops = snippet_text_document_ops(snap, op);
710 document_changes.extend_from_slice(&ops);
712 for (file_id, edit) in source_change.source_file_edits {
713 let edit = snippet_text_document_edit(&snap, source_change.is_snippet, file_id, edit)?;
714 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
717 lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
721 pub(crate) fn workspace_edit(
722 snap: &GlobalStateSnapshot,
723 source_change: SourceChange,
724 ) -> Result<lsp_types::WorkspaceEdit> {
725 assert!(!source_change.is_snippet);
726 snippet_workspace_edit(snap, source_change).map(|it| it.into())
729 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
730 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
731 lsp_types::WorkspaceEdit {
733 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
734 lsp_types::DocumentChanges::Operations(
737 .map(|change| match change {
738 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
739 lsp_types::DocumentChangeOperation::Op(op)
741 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
742 lsp_types::DocumentChangeOperation::Edit(
743 lsp_types::TextDocumentEdit {
744 text_document: edit.text_document,
749 lsp_types::OneOf::Left(lsp_types::TextEdit {
751 new_text: edit.new_text,
762 change_annotations: None,
767 pub(crate) fn call_hierarchy_item(
768 snap: &GlobalStateSnapshot,
769 target: NavigationTarget,
770 ) -> Result<lsp_types::CallHierarchyItem> {
771 let name = target.name.to_string();
772 let detail = target.description.clone();
773 let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::Function);
774 let (uri, range, selection_range) = location_info(snap, target)?;
775 Ok(lsp_types::CallHierarchyItem {
787 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
789 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
790 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
791 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
792 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
793 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
794 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
798 pub(crate) fn unresolved_code_action(
799 snap: &GlobalStateSnapshot,
800 code_action_params: lsp_types::CodeActionParams,
803 ) -> Result<lsp_ext::CodeAction> {
804 assert!(assist.source_change.is_none());
805 let res = lsp_ext::CodeAction {
806 title: assist.label.to_string(),
807 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
808 kind: Some(code_action_kind(assist.id.1)),
811 data: Some(lsp_ext::CodeActionData {
812 id: format!("{}:{}", assist.id.0, index.to_string()),
819 pub(crate) fn resolved_code_action(
820 snap: &GlobalStateSnapshot,
822 ) -> Result<lsp_ext::CodeAction> {
823 let change = assist.source_change.unwrap();
824 let res = lsp_ext::CodeAction {
825 edit: Some(snippet_workspace_edit(snap, change)?),
826 title: assist.label.to_string(),
827 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
828 kind: Some(code_action_kind(assist.id.1)),
835 pub(crate) fn runnable(
836 snap: &GlobalStateSnapshot,
839 ) -> Result<lsp_ext::Runnable> {
840 let config = snap.config.runnables();
841 let spec = CargoTargetSpec::for_file(snap, file_id)?;
842 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
843 let target = spec.as_ref().map(|s| s.target.clone());
844 let (cargo_args, executable_args) =
845 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
846 let label = runnable.label(target);
847 let location = location_link(snap, None, runnable.nav)?;
849 Ok(lsp_ext::Runnable {
851 location: Some(location),
852 kind: lsp_ext::RunnableKind::Cargo,
853 args: lsp_ext::CargoRunnable {
854 workspace_root: workspace_root.map(|it| it.into()),
855 override_cargo: config.override_cargo,
857 cargo_extra_args: config.cargo_extra_args,
864 pub(crate) fn code_lens(
865 snap: &GlobalStateSnapshot,
866 annotation: Annotation,
867 ) -> Result<lsp_types::CodeLens> {
868 match annotation.kind {
869 AnnotationKind::Runnable { debug, runnable: run } => {
870 let line_index = snap.analysis.file_line_index(run.nav.file_id)?;
871 let annotation_range = range(&line_index, annotation.range);
873 let action = run.action();
874 let r = runnable(&snap, run.nav.file_id, run)?;
876 let command = if debug {
877 command::debug_single(&r)
879 let title = action.run_title.to_string();
880 command::run_single(&r, &title)
883 Ok(lsp_types::CodeLens { range: annotation_range, command: Some(command), data: None })
885 AnnotationKind::HasImpls { position: file_position, data } => {
886 let line_index = snap.analysis.file_line_index(file_position.file_id)?;
887 let annotation_range = range(&line_index, annotation.range);
888 let url = url(snap, file_position.file_id);
890 let position = position(&line_index, file_position.offset);
892 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
894 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
896 let goto_params = lsp_types::request::GotoImplementationParams {
897 text_document_position_params: doc_pos,
898 work_done_progress_params: Default::default(),
899 partial_result_params: Default::default(),
902 let command = data.map(|ranges| {
903 let locations: Vec<lsp_types::Location> = ranges
905 .filter_map(|target| {
908 FileRange { file_id: target.file_id, range: target.full_range },
914 command::show_references(
915 implementation_title(locations.len()),
922 Ok(lsp_types::CodeLens {
923 range: annotation_range,
925 data: Some(to_value(lsp_ext::CodeLensResolveData::Impls(goto_params)).unwrap()),
928 AnnotationKind::HasReferences { position: file_position, data } => {
929 let line_index = snap.analysis.file_line_index(file_position.file_id)?;
930 let annotation_range = range(&line_index, annotation.range);
931 let url = url(snap, file_position.file_id);
933 let position = position(&line_index, file_position.offset);
935 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
937 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
939 let command = data.map(|ranges| {
940 let locations: Vec<lsp_types::Location> =
941 ranges.into_iter().filter_map(|range| location(snap, range).ok()).collect();
943 command::show_references(
944 reference_title(locations.len()),
951 Ok(lsp_types::CodeLens {
952 range: annotation_range,
954 data: Some(to_value(lsp_ext::CodeLensResolveData::References(doc_pos)).unwrap()),
960 pub(crate) mod command {
961 use ide::{FileRange, NavigationTarget};
962 use serde_json::to_value;
965 global_state::GlobalStateSnapshot,
967 to_proto::{location, location_link},
970 pub(crate) fn show_references(
972 uri: &lsp_types::Url,
973 position: lsp_types::Position,
974 locations: Vec<lsp_types::Location>,
975 ) -> lsp_types::Command {
976 // We cannot use the 'editor.action.showReferences' command directly
977 // because that command requires vscode types which we convert in the handler
978 // on the client side.
982 command: "rust-analyzer.showReferences".into(),
983 arguments: Some(vec![
984 to_value(uri).unwrap(),
985 to_value(position).unwrap(),
986 to_value(locations).unwrap(),
991 pub(crate) fn run_single(runnable: &lsp_ext::Runnable, title: &str) -> lsp_types::Command {
993 title: title.to_string(),
994 command: "rust-analyzer.runSingle".into(),
995 arguments: Some(vec![to_value(runnable).unwrap()]),
999 pub(crate) fn debug_single(runnable: &lsp_ext::Runnable) -> lsp_types::Command {
1000 lsp_types::Command {
1001 title: "Debug".into(),
1002 command: "rust-analyzer.debugSingle".into(),
1003 arguments: Some(vec![to_value(runnable).unwrap()]),
1007 pub(crate) fn goto_location(
1008 snap: &GlobalStateSnapshot,
1009 nav: &NavigationTarget,
1010 ) -> Option<lsp_types::Command> {
1011 let value = if snap.config.location_link() {
1012 let link = location_link(snap, None, nav.clone()).ok()?;
1013 to_value(link).ok()?
1015 let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1016 let location = location(snap, range).ok()?;
1017 to_value(location).ok()?
1020 Some(lsp_types::Command {
1021 title: nav.name.to_string(),
1022 command: "rust-analyzer.gotoLocation".into(),
1023 arguments: Some(vec![value]),
1027 pub(crate) fn trigger_parameter_hints() -> lsp_types::Command {
1028 lsp_types::Command {
1029 title: "triggerParameterHints".into(),
1030 command: "editor.action.triggerParameterHints".into(),
1036 pub(crate) fn implementation_title(count: usize) -> String {
1038 "1 implementation".into()
1040 format!("{} implementations", count)
1044 pub(crate) fn reference_title(count: usize) -> String {
1046 "1 reference".into()
1048 format!("{} references", count)
1052 pub(crate) fn markup_content(markup: Markup) -> lsp_types::MarkupContent {
1053 let value = crate::markdown::format_docs(markup.as_str());
1054 lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value }
1057 pub(crate) fn rename_error(err: RenameError) -> crate::LspError {
1058 crate::LspError { code: lsp_server::ErrorCode::InvalidParams as i32, message: err.to_string() }
1063 use hir::PrefixKind;
1065 use ide_db::helpers::{insert_use::InsertUseConfig, SnippetCap};
1070 fn test_completion_with_ref() {
1073 fn foo(arg: &Foo) {}
1079 let (offset, text) = test_utils::extract_offset(fixture);
1080 let line_index = LineIndex::new(&text);
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, LineEndings::Unix, 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::new(&text);
1137 let converted: Vec<lsp_types::FoldingRange> =
1138 folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
1140 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
1141 assert_eq!(converted.len(), expected_lines.len());
1142 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
1143 assert_eq!(folding_range.start_line, *start_line);
1144 assert_eq!(folding_range.start_character, None);
1145 assert_eq!(folding_range.end_line, *end_line);
1146 assert_eq!(folding_range.end_character, None);
1150 // `Url` is not able to parse windows paths on unix machines.
1152 #[cfg(target_os = "windows")]
1153 fn test_lowercase_drive_letter_with_drive() {
1154 let url = url_from_abs_path(Path::new("C:\\Test"));
1155 assert_eq!(url.to_string(), "file:///c:/Test");
1159 #[cfg(target_os = "windows")]
1160 fn test_drive_without_colon_passthrough() {
1161 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#));
1162 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");