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 item: CompletionItem,
177 ) -> Vec<lsp_types::CompletionItem> {
178 fn set_score(lsp_item: &mut lsp_types::CompletionItem, label: &str) {
179 lsp_item.preselect = Some(true);
180 // HACK: sort preselect items first
181 lsp_item.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 = item.source_range();
189 for indel in 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 lsp_item = lsp_types::CompletionItem {
211 label: item.label().to_string(),
212 detail: item.detail().map(|it| it.to_string()),
213 filter_text: Some(item.lookup().to_string()),
214 kind: item.kind().map(completion_item_kind),
215 text_edit: Some(text_edit.into()),
216 additional_text_edits: Some(additional_text_edits),
217 documentation: item.documentation().map(documentation),
218 deprecated: Some(item.deprecated()),
222 if item.score().is_some() {
223 set_score(&mut lsp_item, item.label());
226 if item.deprecated() {
227 lsp_item.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
230 if item.trigger_call_info() {
231 lsp_item.command = Some(command::trigger_parameter_hints());
234 let mut res = match item.ref_match() {
235 Some(mutability) => {
236 let mut refed = lsp_item.clone();
237 let label = format!("&{}{}", mutability.as_keyword_for_ref(), refed.label);
238 set_score(&mut refed, &label);
240 vec![lsp_item, refed]
242 None => vec![lsp_item],
245 for lsp_item in res.iter_mut() {
246 lsp_item.insert_text_format = Some(insert_text_format(item.insert_text_format()));
251 pub(crate) fn signature_help(
255 ) -> lsp_types::SignatureHelp {
256 let (label, parameters) = match (concise, label_offsets) {
258 let params = call_info
260 .map(|label| lsp_types::ParameterInformation {
261 label: lsp_types::ParameterLabel::Simple(label.to_string()),
264 .collect::<Vec<_>>();
266 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
270 let params = call_info
273 .map(|it| [u32::from(it.start()).into(), u32::from(it.end()).into()])
274 .map(|label_offsets| lsp_types::ParameterInformation {
275 label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
278 .collect::<Vec<_>>();
279 (call_info.signature, params)
282 let mut params = Vec::new();
283 let mut label = String::new();
284 let mut first = true;
285 for param in call_info.parameter_labels() {
287 label.push_str(", ");
290 let start = label.len() as u32;
291 label.push_str(param);
292 let end = label.len() as u32;
293 params.push(lsp_types::ParameterInformation {
294 label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
303 let documentation = if concise {
306 call_info.doc.map(|doc| {
307 lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
308 kind: lsp_types::MarkupKind::Markdown,
314 let active_parameter = call_info.active_parameter.map(|it| it as u32);
316 let signature = lsp_types::SignatureInformation {
319 parameters: Some(parameters),
322 lsp_types::SignatureHelp {
323 signatures: vec![signature],
324 active_signature: None,
329 pub(crate) fn inlay_hint(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
331 label: inlay_hint.label.to_string(),
332 range: range(line_index, inlay_hint.range),
333 kind: match inlay_hint.kind {
334 InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
335 InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
336 InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
341 static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
343 pub(crate) fn semantic_tokens(
345 line_index: &LineIndex,
346 highlights: Vec<HlRange>,
347 ) -> lsp_types::SemanticTokens {
348 let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
349 let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
351 for highlight_range in highlights {
352 if highlight_range.highlight.is_empty() {
355 let (type_, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
356 let token_index = semantic_tokens::type_index(type_);
357 let modifier_bitset = mods.0;
359 for mut text_range in line_index.index.lines(highlight_range.range) {
360 if text[text_range].ends_with('\n') {
362 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
364 let range = range(&line_index, text_range);
365 builder.push(range, token_index, modifier_bitset);
372 pub(crate) fn semantic_token_delta(
373 previous: &lsp_types::SemanticTokens,
374 current: &lsp_types::SemanticTokens,
375 ) -> lsp_types::SemanticTokensDelta {
376 let result_id = current.result_id.clone();
377 let edits = semantic_tokens::diff_tokens(&previous.data, ¤t.data);
378 lsp_types::SemanticTokensDelta { result_id, edits }
381 fn semantic_token_type_and_modifiers(
382 highlight: Highlight,
383 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
384 let mut mods = semantic_tokens::ModifierSet::default();
385 let type_ = match highlight.tag {
386 HlTag::Symbol(symbol) => match symbol {
387 SymbolKind::Module => lsp_types::SemanticTokenType::NAMESPACE,
388 SymbolKind::Impl => lsp_types::SemanticTokenType::TYPE,
389 SymbolKind::Field => lsp_types::SemanticTokenType::PROPERTY,
390 SymbolKind::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
391 SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
392 SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
393 SymbolKind::Label => semantic_tokens::LABEL,
394 SymbolKind::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
395 SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
396 SymbolKind::Local => lsp_types::SemanticTokenType::VARIABLE,
397 SymbolKind::Function => {
398 if highlight.mods.contains(HlMod::Associated) {
399 lsp_types::SemanticTokenType::METHOD
401 lsp_types::SemanticTokenType::FUNCTION
404 SymbolKind::Const => {
405 mods |= semantic_tokens::CONSTANT;
406 mods |= lsp_types::SemanticTokenModifier::STATIC;
407 lsp_types::SemanticTokenType::VARIABLE
409 SymbolKind::Static => {
410 mods |= lsp_types::SemanticTokenModifier::STATIC;
411 lsp_types::SemanticTokenType::VARIABLE
413 SymbolKind::Struct => lsp_types::SemanticTokenType::STRUCT,
414 SymbolKind::Enum => lsp_types::SemanticTokenType::ENUM,
415 SymbolKind::Variant => lsp_types::SemanticTokenType::ENUM_MEMBER,
416 SymbolKind::Union => semantic_tokens::UNION,
417 SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
418 SymbolKind::Trait => lsp_types::SemanticTokenType::INTERFACE,
419 SymbolKind::Macro => lsp_types::SemanticTokenType::MACRO,
421 HlTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
422 HlTag::None => semantic_tokens::GENERIC,
423 HlTag::ByteLiteral | HlTag::NumericLiteral => lsp_types::SemanticTokenType::NUMBER,
424 HlTag::BoolLiteral => semantic_tokens::BOOLEAN,
425 HlTag::StringLiteral => lsp_types::SemanticTokenType::STRING,
426 HlTag::CharLiteral => semantic_tokens::CHAR_LITERAL,
427 HlTag::Comment => lsp_types::SemanticTokenType::COMMENT,
428 HlTag::Attribute => semantic_tokens::ATTRIBUTE,
429 HlTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
430 HlTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
431 HlTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
432 HlTag::Operator => lsp_types::SemanticTokenType::OPERATOR,
433 HlTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
434 HlTag::Punctuation(punct) => match punct {
435 HlPunct::Bracket => semantic_tokens::BRACKET,
436 HlPunct::Brace => semantic_tokens::BRACE,
437 HlPunct::Parenthesis => semantic_tokens::PARENTHESIS,
438 HlPunct::Angle => semantic_tokens::ANGLE,
439 HlPunct::Comma => semantic_tokens::COMMA,
440 HlPunct::Dot => semantic_tokens::DOT,
441 HlPunct::Colon => semantic_tokens::COLON,
442 HlPunct::Semi => semantic_tokens::SEMICOLON,
443 HlPunct::Other => semantic_tokens::PUNCTUATION,
447 for modifier in highlight.mods.iter() {
448 let modifier = match modifier {
449 HlMod::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
450 HlMod::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
451 HlMod::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
452 HlMod::Injected => semantic_tokens::INJECTED,
453 HlMod::ControlFlow => semantic_tokens::CONTROL_FLOW,
454 HlMod::Mutable => semantic_tokens::MUTABLE,
455 HlMod::Consuming => semantic_tokens::CONSUMING,
456 HlMod::Unsafe => semantic_tokens::UNSAFE,
457 HlMod::Callable => semantic_tokens::CALLABLE,
458 HlMod::Static => lsp_types::SemanticTokenModifier::STATIC,
459 HlMod::Associated => continue,
467 pub(crate) fn folding_range(
469 line_index: &LineIndex,
470 line_folding_only: bool,
472 ) -> lsp_types::FoldingRange {
473 let kind = match fold.kind {
474 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
475 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
476 FoldKind::Mods | FoldKind::Block | FoldKind::ArgList | FoldKind::Region => None,
479 let range = range(line_index, fold.range);
481 if line_folding_only {
482 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
483 // even if it contains text not in the folding range. To prevent that we exclude
484 // range.end.line from the folding region if there is more text after range.end
486 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
488 .take_while(|it| *it != '\n')
489 .any(|it| !it.is_whitespace());
491 let end_line = if has_more_text_on_end_line {
492 range.end.line.saturating_sub(1)
497 lsp_types::FoldingRange {
498 start_line: range.start.line,
499 start_character: None,
505 lsp_types::FoldingRange {
506 start_line: range.start.line,
507 start_character: Some(range.start.character),
508 end_line: range.end.line,
509 end_character: Some(range.end.character),
515 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
516 snap.file_id_to_url(file_id)
519 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
520 /// This will only happen when processing windows paths.
522 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
523 pub(crate) fn url_from_abs_path(path: &Path) -> lsp_types::Url {
524 assert!(path.is_absolute());
525 let url = lsp_types::Url::from_file_path(path).unwrap();
526 match path.components().next() {
527 Some(path::Component::Prefix(prefix))
528 if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
530 // Need to lowercase driver letter
535 let driver_letter_range = {
536 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
540 let start = scheme.len() + ':'.len_utf8();
541 start..(start + drive_letter.len())
544 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
545 // machinery *also* canonicalizes the drive letter. So, just massage the
547 let mut url = url.into_string();
548 url[driver_letter_range].make_ascii_lowercase();
549 lsp_types::Url::parse(&url).unwrap()
552 pub(crate) fn optional_versioned_text_document_identifier(
553 snap: &GlobalStateSnapshot,
555 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
556 let url = url(snap, file_id);
557 let version = snap.url_file_version(&url);
558 lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
561 pub(crate) fn location(
562 snap: &GlobalStateSnapshot,
564 ) -> Result<lsp_types::Location> {
565 let url = url(snap, frange.file_id);
566 let line_index = snap.file_line_index(frange.file_id)?;
567 let range = range(&line_index, frange.range);
568 let loc = lsp_types::Location::new(url, range);
572 /// Perefer using `location_link`, if the client has the cap.
573 pub(crate) fn location_from_nav(
574 snap: &GlobalStateSnapshot,
575 nav: NavigationTarget,
576 ) -> Result<lsp_types::Location> {
577 let url = url(snap, nav.file_id);
578 let line_index = snap.file_line_index(nav.file_id)?;
579 let range = range(&line_index, nav.full_range);
580 let loc = lsp_types::Location::new(url, range);
584 pub(crate) fn location_link(
585 snap: &GlobalStateSnapshot,
586 src: Option<FileRange>,
587 target: NavigationTarget,
588 ) -> Result<lsp_types::LocationLink> {
589 let origin_selection_range = match src {
591 let line_index = snap.file_line_index(src.file_id)?;
592 let range = range(&line_index, src.range);
597 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
598 let res = lsp_types::LocationLink {
599 origin_selection_range,
602 target_selection_range,
608 snap: &GlobalStateSnapshot,
609 target: NavigationTarget,
610 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
611 let line_index = snap.file_line_index(target.file_id)?;
613 let target_uri = url(snap, target.file_id);
614 let target_range = range(&line_index, target.full_range);
615 let target_selection_range =
616 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
617 Ok((target_uri, target_range, target_selection_range))
620 pub(crate) fn goto_definition_response(
621 snap: &GlobalStateSnapshot,
622 src: Option<FileRange>,
623 targets: Vec<NavigationTarget>,
624 ) -> Result<lsp_types::GotoDefinitionResponse> {
625 if snap.config.location_link() {
628 .map(|nav| location_link(snap, src, nav))
629 .collect::<Result<Vec<_>>>()?;
632 let locations = targets
635 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
637 .collect::<Result<Vec<_>>>()?;
642 pub(crate) fn snippet_text_document_edit(
643 snap: &GlobalStateSnapshot,
647 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
648 let text_document = optional_versioned_text_document_identifier(snap, file_id);
649 let line_index = snap.file_line_index(file_id)?;
650 let edits = edit.into_iter().map(|it| snippet_text_edit(&line_index, is_snippet, it)).collect();
651 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
654 pub(crate) fn snippet_text_document_ops(
655 snap: &GlobalStateSnapshot,
656 file_system_edit: FileSystemEdit,
657 ) -> Vec<lsp_ext::SnippetDocumentChangeOperation> {
658 let mut ops = Vec::new();
659 match file_system_edit {
660 FileSystemEdit::CreateFile { dst, initial_contents } => {
661 let uri = snap.anchored_path(&dst);
662 let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
667 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
668 if !initial_contents.is_empty() {
670 lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
671 let text_edit = lsp_ext::SnippetTextEdit {
672 range: lsp_types::Range::default(),
673 new_text: initial_contents,
674 insert_text_format: Some(lsp_types::InsertTextFormat::PlainText),
677 lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
678 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
681 FileSystemEdit::MoveFile { src, dst } => {
682 let old_uri = snap.file_id_to_url(src);
683 let new_uri = snap.anchored_path(&dst);
684 let rename_file = lsp_types::ResourceOp::Rename(lsp_types::RenameFile {
690 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(rename_file))
696 pub(crate) fn snippet_workspace_edit(
697 snap: &GlobalStateSnapshot,
698 source_change: SourceChange,
699 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
700 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
701 for op in source_change.file_system_edits {
702 let ops = snippet_text_document_ops(snap, op);
703 document_changes.extend_from_slice(&ops);
705 for (file_id, edit) in source_change.source_file_edits {
706 let edit = snippet_text_document_edit(&snap, source_change.is_snippet, file_id, edit)?;
707 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
710 lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
714 pub(crate) fn workspace_edit(
715 snap: &GlobalStateSnapshot,
716 source_change: SourceChange,
717 ) -> Result<lsp_types::WorkspaceEdit> {
718 assert!(!source_change.is_snippet);
719 snippet_workspace_edit(snap, source_change).map(|it| it.into())
722 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
723 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
724 lsp_types::WorkspaceEdit {
726 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
727 lsp_types::DocumentChanges::Operations(
730 .map(|change| match change {
731 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
732 lsp_types::DocumentChangeOperation::Op(op)
734 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
735 lsp_types::DocumentChangeOperation::Edit(
736 lsp_types::TextDocumentEdit {
737 text_document: edit.text_document,
742 lsp_types::OneOf::Left(lsp_types::TextEdit {
744 new_text: edit.new_text,
755 change_annotations: None,
760 pub(crate) fn call_hierarchy_item(
761 snap: &GlobalStateSnapshot,
762 target: NavigationTarget,
763 ) -> Result<lsp_types::CallHierarchyItem> {
764 let name = target.name.to_string();
765 let detail = target.description.clone();
766 let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::Function);
767 let (uri, range, selection_range) = location_info(snap, target)?;
768 Ok(lsp_types::CallHierarchyItem {
780 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
782 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
783 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
784 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
785 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
786 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
787 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
791 pub(crate) fn unresolved_code_action(
792 snap: &GlobalStateSnapshot,
793 code_action_params: lsp_types::CodeActionParams,
796 ) -> Result<lsp_ext::CodeAction> {
797 assert!(assist.source_change.is_none());
798 let res = lsp_ext::CodeAction {
799 title: assist.label.to_string(),
800 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
801 kind: Some(code_action_kind(assist.id.1)),
804 data: Some(lsp_ext::CodeActionData {
805 id: format!("{}:{}", assist.id.0, index.to_string()),
812 pub(crate) fn resolved_code_action(
813 snap: &GlobalStateSnapshot,
815 ) -> Result<lsp_ext::CodeAction> {
816 let change = assist.source_change.unwrap();
817 let res = lsp_ext::CodeAction {
818 edit: Some(snippet_workspace_edit(snap, change)?),
819 title: assist.label.to_string(),
820 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
821 kind: Some(code_action_kind(assist.id.1)),
828 pub(crate) fn runnable(
829 snap: &GlobalStateSnapshot,
832 ) -> Result<lsp_ext::Runnable> {
833 let config = snap.config.runnables();
834 let spec = CargoTargetSpec::for_file(snap, file_id)?;
835 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
836 let target = spec.as_ref().map(|s| s.target.clone());
837 let (cargo_args, executable_args) =
838 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
839 let label = runnable.label(target);
840 let location = location_link(snap, None, runnable.nav)?;
842 Ok(lsp_ext::Runnable {
844 location: Some(location),
845 kind: lsp_ext::RunnableKind::Cargo,
846 args: lsp_ext::CargoRunnable {
847 workspace_root: workspace_root.map(|it| it.into()),
848 override_cargo: config.override_cargo,
850 cargo_extra_args: config.cargo_extra_args,
857 pub(crate) fn code_lens(
858 snap: &GlobalStateSnapshot,
859 annotation: Annotation,
860 ) -> Result<lsp_types::CodeLens> {
861 match annotation.kind {
862 AnnotationKind::Runnable { debug, runnable: run } => {
863 let line_index = snap.file_line_index(run.nav.file_id)?;
864 let annotation_range = range(&line_index, annotation.range);
866 let action = run.action();
867 let r = runnable(&snap, run.nav.file_id, run)?;
869 let command = if debug {
870 command::debug_single(&r)
872 let title = action.run_title.to_string();
873 command::run_single(&r, &title)
876 Ok(lsp_types::CodeLens { range: annotation_range, command: Some(command), data: None })
878 AnnotationKind::HasImpls { position: file_position, data } => {
879 let line_index = snap.file_line_index(file_position.file_id)?;
880 let annotation_range = range(&line_index, annotation.range);
881 let url = url(snap, file_position.file_id);
883 let position = position(&line_index, file_position.offset);
885 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
887 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
889 let goto_params = lsp_types::request::GotoImplementationParams {
890 text_document_position_params: doc_pos,
891 work_done_progress_params: Default::default(),
892 partial_result_params: Default::default(),
895 let command = data.map(|ranges| {
896 let locations: Vec<lsp_types::Location> = ranges
898 .filter_map(|target| {
901 FileRange { file_id: target.file_id, range: target.full_range },
907 command::show_references(
908 implementation_title(locations.len()),
915 Ok(lsp_types::CodeLens {
916 range: annotation_range,
918 data: Some(to_value(lsp_ext::CodeLensResolveData::Impls(goto_params)).unwrap()),
921 AnnotationKind::HasReferences { position: file_position, data } => {
922 let line_index = snap.file_line_index(file_position.file_id)?;
923 let annotation_range = range(&line_index, annotation.range);
924 let url = url(snap, file_position.file_id);
926 let position = position(&line_index, file_position.offset);
928 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
930 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
932 let command = data.map(|ranges| {
933 let locations: Vec<lsp_types::Location> =
934 ranges.into_iter().filter_map(|range| location(snap, range).ok()).collect();
936 command::show_references(
937 reference_title(locations.len()),
944 Ok(lsp_types::CodeLens {
945 range: annotation_range,
947 data: Some(to_value(lsp_ext::CodeLensResolveData::References(doc_pos)).unwrap()),
953 pub(crate) mod command {
954 use ide::{FileRange, NavigationTarget};
955 use serde_json::to_value;
958 global_state::GlobalStateSnapshot,
960 to_proto::{location, location_link},
963 pub(crate) fn show_references(
965 uri: &lsp_types::Url,
966 position: lsp_types::Position,
967 locations: Vec<lsp_types::Location>,
968 ) -> lsp_types::Command {
969 // We cannot use the 'editor.action.showReferences' command directly
970 // because that command requires vscode types which we convert in the handler
971 // on the client side.
975 command: "rust-analyzer.showReferences".into(),
976 arguments: Some(vec![
977 to_value(uri).unwrap(),
978 to_value(position).unwrap(),
979 to_value(locations).unwrap(),
984 pub(crate) fn run_single(runnable: &lsp_ext::Runnable, title: &str) -> lsp_types::Command {
986 title: title.to_string(),
987 command: "rust-analyzer.runSingle".into(),
988 arguments: Some(vec![to_value(runnable).unwrap()]),
992 pub(crate) fn debug_single(runnable: &lsp_ext::Runnable) -> lsp_types::Command {
994 title: "Debug".into(),
995 command: "rust-analyzer.debugSingle".into(),
996 arguments: Some(vec![to_value(runnable).unwrap()]),
1000 pub(crate) fn goto_location(
1001 snap: &GlobalStateSnapshot,
1002 nav: &NavigationTarget,
1003 ) -> Option<lsp_types::Command> {
1004 let value = if snap.config.location_link() {
1005 let link = location_link(snap, None, nav.clone()).ok()?;
1006 to_value(link).ok()?
1008 let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1009 let location = location(snap, range).ok()?;
1010 to_value(location).ok()?
1013 Some(lsp_types::Command {
1014 title: nav.name.to_string(),
1015 command: "rust-analyzer.gotoLocation".into(),
1016 arguments: Some(vec![value]),
1020 pub(crate) fn trigger_parameter_hints() -> lsp_types::Command {
1021 lsp_types::Command {
1022 title: "triggerParameterHints".into(),
1023 command: "editor.action.triggerParameterHints".into(),
1029 pub(crate) fn implementation_title(count: usize) -> String {
1031 "1 implementation".into()
1033 format!("{} implementations", count)
1037 pub(crate) fn reference_title(count: usize) -> String {
1039 "1 reference".into()
1041 format!("{} references", count)
1045 pub(crate) fn markup_content(markup: Markup) -> lsp_types::MarkupContent {
1046 let value = crate::markdown::format_docs(markup.as_str());
1047 lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value }
1050 pub(crate) fn rename_error(err: RenameError) -> crate::LspError {
1051 crate::LspError { code: lsp_server::ErrorCode::InvalidParams as i32, message: err.to_string() }
1058 use hir::PrefixKind;
1060 use ide_db::helpers::{insert_use::InsertUseConfig, SnippetCap};
1065 fn test_completion_with_ref() {
1068 fn foo(arg: &Foo) {}
1074 let (offset, text) = test_utils::extract_offset(fixture);
1075 let line_index = LineIndex {
1076 index: Arc::new(ide::LineIndex::new(&text)),
1077 endings: LineEndings::Unix,
1078 encoding: OffsetEncoding::Utf16,
1080 let (analysis, file_id) = Analysis::from_single_file(text);
1081 let completions: Vec<(String, Option<String>)> = analysis
1083 &ide::CompletionConfig {
1084 enable_postfix_completions: true,
1085 enable_imports_on_the_fly: true,
1086 add_call_parenthesis: true,
1087 add_call_argument_snippets: true,
1088 snippet_cap: SnippetCap::new(true),
1089 insert_use: InsertUseConfig {
1091 prefix_kind: PrefixKind::Plain,
1095 ide_db::base_db::FilePosition { file_id, offset },
1100 .filter(|c| c.label().ends_with("arg"))
1101 .map(|c| completion_item(&line_index, c))
1102 .flat_map(|comps| comps.into_iter().map(|c| (c.label, c.sort_text)))
1104 expect_test::expect![[r#"
1118 .assert_debug_eq(&completions);
1122 fn conv_fold_line_folding_only_fixup() {
1123 let text = r#"mod a;
1135 let (analysis, file_id) = Analysis::from_single_file(text.to_string());
1136 let folds = analysis.folding_ranges(file_id).unwrap();
1137 assert_eq!(folds.len(), 4);
1139 let line_index = LineIndex {
1140 index: Arc::new(ide::LineIndex::new(&text)),
1141 endings: LineEndings::Unix,
1142 encoding: OffsetEncoding::Utf16,
1144 let converted: Vec<lsp_types::FoldingRange> =
1145 folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
1147 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
1148 assert_eq!(converted.len(), expected_lines.len());
1149 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
1150 assert_eq!(folding_range.start_line, *start_line);
1151 assert_eq!(folding_range.start_character, None);
1152 assert_eq!(folding_range.end_line, *end_line);
1153 assert_eq!(folding_range.end_character, None);
1157 // `Url` is not able to parse windows paths on unix machines.
1159 #[cfg(target_os = "windows")]
1160 fn test_lowercase_drive_letter_with_drive() {
1161 let url = url_from_abs_path(Path::new("C:\\Test"));
1162 assert_eq!(url.to_string(), "file:///c:/Test");
1166 #[cfg(target_os = "windows")]
1167 fn test_drive_without_colon_passthrough() {
1168 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#));
1169 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");