1 //! Conversion of rust-analyzer specific types to lsp_types equivalents.
5 sync::atomic::{AtomicU32, Ordering},
9 Annotation, AnnotationKind, Assist, AssistKind, CallInfo, Cancellable, CompletionItem,
10 CompletionItemKind, CompletionRelevance, Documentation, FileId, FileRange, FileSystemEdit,
11 Fold, FoldKind, Highlight, HlMod, HlOperator, HlPunct, HlRange, HlTag, Indel, InlayHint,
12 InlayKind, Markup, NavigationTarget, ReferenceAccess, RenameError, Runnable, Severity,
13 SourceChange, StructureNodeKind, SymbolKind, TextEdit, TextRange, TextSize,
15 use itertools::Itertools;
16 use serde_json::to_value;
20 cargo_target_spec::CargoTargetSpec,
22 global_state::GlobalStateSnapshot,
23 line_index::{LineEndings, LineIndex, OffsetEncoding},
24 lsp_ext, semantic_tokens, Result,
27 pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position {
28 let line_col = line_index.index.line_col(offset);
29 match line_index.encoding {
30 OffsetEncoding::Utf8 => lsp_types::Position::new(line_col.line, line_col.col),
31 OffsetEncoding::Utf16 => {
32 let line_col = line_index.index.to_utf16(line_col);
33 lsp_types::Position::new(line_col.line, line_col.col)
38 pub(crate) fn range(line_index: &LineIndex, range: TextRange) -> lsp_types::Range {
39 let start = position(line_index, range.start());
40 let end = position(line_index, range.end());
41 lsp_types::Range::new(start, end)
44 pub(crate) fn symbol_kind(symbol_kind: SymbolKind) -> lsp_types::SymbolKind {
46 SymbolKind::Function => lsp_types::SymbolKind::Function,
47 SymbolKind::Struct => lsp_types::SymbolKind::Struct,
48 SymbolKind::Enum => lsp_types::SymbolKind::Enum,
49 SymbolKind::Variant => lsp_types::SymbolKind::EnumMember,
50 SymbolKind::Trait => lsp_types::SymbolKind::Interface,
51 SymbolKind::Macro => lsp_types::SymbolKind::Function,
52 SymbolKind::Module => lsp_types::SymbolKind::Module,
53 SymbolKind::TypeAlias | SymbolKind::TypeParam => lsp_types::SymbolKind::TypeParameter,
54 SymbolKind::Field => lsp_types::SymbolKind::Field,
55 SymbolKind::Static => lsp_types::SymbolKind::Constant,
56 SymbolKind::Const => lsp_types::SymbolKind::Constant,
57 SymbolKind::ConstParam => lsp_types::SymbolKind::Constant,
58 SymbolKind::Impl => lsp_types::SymbolKind::Object,
60 | SymbolKind::SelfParam
61 | SymbolKind::LifetimeParam
62 | SymbolKind::ValueParam
63 | SymbolKind::Label => lsp_types::SymbolKind::Variable,
64 SymbolKind::Union => lsp_types::SymbolKind::Struct,
68 pub(crate) fn structure_node_kind(kind: StructureNodeKind) -> lsp_types::SymbolKind {
70 StructureNodeKind::SymbolKind(symbol) => symbol_kind(symbol),
71 StructureNodeKind::Region => lsp_types::SymbolKind::Namespace,
75 pub(crate) fn document_highlight_kind(
76 reference_access: ReferenceAccess,
77 ) -> lsp_types::DocumentHighlightKind {
78 match reference_access {
79 ReferenceAccess::Read => lsp_types::DocumentHighlightKind::Read,
80 ReferenceAccess::Write => lsp_types::DocumentHighlightKind::Write,
84 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
86 Severity::Error => lsp_types::DiagnosticSeverity::Error,
87 Severity::WeakWarning => lsp_types::DiagnosticSeverity::Hint,
91 pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
92 let value = crate::markdown::format_docs(documentation.as_str());
93 let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
94 lsp_types::Documentation::MarkupContent(markup_content)
97 pub(crate) fn completion_item_kind(
98 completion_item_kind: CompletionItemKind,
99 ) -> lsp_types::CompletionItemKind {
100 match completion_item_kind {
101 CompletionItemKind::Attribute => lsp_types::CompletionItemKind::EnumMember,
102 CompletionItemKind::Binding => lsp_types::CompletionItemKind::Variable,
103 CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::Struct,
104 CompletionItemKind::Keyword => lsp_types::CompletionItemKind::Keyword,
105 CompletionItemKind::Method => lsp_types::CompletionItemKind::Method,
106 CompletionItemKind::Snippet => lsp_types::CompletionItemKind::Snippet,
107 CompletionItemKind::UnresolvedReference => lsp_types::CompletionItemKind::Reference,
108 CompletionItemKind::SymbolKind(symbol) => match symbol {
109 SymbolKind::Const => lsp_types::CompletionItemKind::Constant,
110 SymbolKind::ConstParam => lsp_types::CompletionItemKind::TypeParameter,
111 SymbolKind::Enum => lsp_types::CompletionItemKind::Enum,
112 SymbolKind::Field => lsp_types::CompletionItemKind::Field,
113 SymbolKind::Function => lsp_types::CompletionItemKind::Function,
114 SymbolKind::Impl => lsp_types::CompletionItemKind::Text,
115 SymbolKind::Label => lsp_types::CompletionItemKind::Variable,
116 SymbolKind::LifetimeParam => lsp_types::CompletionItemKind::TypeParameter,
117 SymbolKind::Local => lsp_types::CompletionItemKind::Variable,
118 SymbolKind::Macro => lsp_types::CompletionItemKind::Method,
119 SymbolKind::Module => lsp_types::CompletionItemKind::Module,
120 SymbolKind::SelfParam => lsp_types::CompletionItemKind::Value,
121 SymbolKind::Static => lsp_types::CompletionItemKind::Value,
122 SymbolKind::Struct => lsp_types::CompletionItemKind::Struct,
123 SymbolKind::Trait => lsp_types::CompletionItemKind::Interface,
124 SymbolKind::TypeAlias => lsp_types::CompletionItemKind::Struct,
125 SymbolKind::TypeParam => lsp_types::CompletionItemKind::TypeParameter,
126 SymbolKind::Union => lsp_types::CompletionItemKind::Struct,
127 SymbolKind::ValueParam => lsp_types::CompletionItemKind::Value,
128 SymbolKind::Variant => lsp_types::CompletionItemKind::EnumMember,
133 pub(crate) fn text_edit(line_index: &LineIndex, indel: Indel) -> lsp_types::TextEdit {
134 let range = range(line_index, indel.delete);
135 let new_text = match line_index.endings {
136 LineEndings::Unix => indel.insert,
137 LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
139 lsp_types::TextEdit { range, new_text }
142 pub(crate) fn completion_text_edit(
143 line_index: &LineIndex,
144 insert_replace_support: Option<lsp_types::Position>,
146 ) -> lsp_types::CompletionTextEdit {
147 let text_edit = text_edit(line_index, indel);
148 match insert_replace_support {
149 Some(cursor_pos) => lsp_types::InsertReplaceEdit {
150 new_text: text_edit.new_text,
151 insert: lsp_types::Range { start: text_edit.range.start, end: cursor_pos },
152 replace: text_edit.range,
155 None => text_edit.into(),
159 pub(crate) fn snippet_text_edit(
160 line_index: &LineIndex,
163 ) -> lsp_ext::SnippetTextEdit {
164 let text_edit = text_edit(line_index, indel);
165 let insert_text_format =
166 if is_snippet { Some(lsp_types::InsertTextFormat::Snippet) } else { None };
167 lsp_ext::SnippetTextEdit {
168 range: text_edit.range,
169 new_text: text_edit.new_text,
175 pub(crate) fn text_edit_vec(
176 line_index: &LineIndex,
178 ) -> Vec<lsp_types::TextEdit> {
179 text_edit.into_iter().map(|indel| self::text_edit(line_index, indel)).collect()
182 pub(crate) fn snippet_text_edit_vec(
183 line_index: &LineIndex,
186 ) -> Vec<lsp_ext::SnippetTextEdit> {
189 .map(|indel| self::snippet_text_edit(line_index, is_snippet, indel))
193 pub(crate) fn completion_items(
195 line_index: &LineIndex,
196 tdpp: lsp_types::TextDocumentPositionParams,
197 items: Vec<CompletionItem>,
198 ) -> Vec<lsp_types::CompletionItem> {
199 let max_relevance = items.iter().map(|it| it.relevance().score()).max().unwrap_or_default();
200 let mut res = Vec::with_capacity(items.len());
202 completion_item(&mut res, config, line_index, &tdpp, max_relevance, item)
208 acc: &mut Vec<lsp_types::CompletionItem>,
210 line_index: &LineIndex,
211 tdpp: &lsp_types::TextDocumentPositionParams,
213 item: CompletionItem,
215 let mut additional_text_edits = Vec::new();
217 // LSP does not allow arbitrary edits in completion, so we have to do a
218 // non-trivial mapping here.
220 let mut text_edit = None;
221 let source_range = item.source_range();
222 for indel in item.text_edit().iter() {
223 if indel.delete.contains_range(source_range) {
224 let insert_replace_support = config.insert_replace_support().then(|| tdpp.position);
225 text_edit = Some(if indel.delete == source_range {
226 self::completion_text_edit(line_index, insert_replace_support, indel.clone())
228 assert!(source_range.end() == indel.delete.end());
229 let range1 = TextRange::new(indel.delete.start(), source_range.start());
230 let range2 = source_range;
231 let indel1 = Indel::replace(range1, String::new());
232 let indel2 = Indel::replace(range2, indel.insert.clone());
233 additional_text_edits.push(self::text_edit(line_index, indel1));
234 self::completion_text_edit(line_index, insert_replace_support, indel2)
237 assert!(source_range.intersect(indel.delete).is_none());
238 let text_edit = self::text_edit(line_index, indel.clone());
239 additional_text_edits.push(text_edit);
245 let mut lsp_item = lsp_types::CompletionItem {
246 label: item.label().to_string(),
247 detail: item.detail().map(|it| it.to_string()),
248 filter_text: Some(item.lookup().to_string()),
249 kind: item.kind().map(completion_item_kind),
250 text_edit: Some(text_edit),
251 additional_text_edits: Some(additional_text_edits),
252 documentation: item.documentation().map(documentation),
253 deprecated: Some(item.deprecated()),
257 set_score(&mut lsp_item, max_relevance, item.relevance());
259 if item.deprecated() {
260 lsp_item.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
263 if item.trigger_call_info() && config.client_commands().trigger_parameter_hints {
264 lsp_item.command = Some(command::trigger_parameter_hints());
267 if item.is_snippet() {
268 lsp_item.insert_text_format = Some(lsp_types::InsertTextFormat::Snippet);
270 if config.completion().enable_imports_on_the_fly {
271 if let Some(import_edit) = item.import_to_add() {
272 let import_path = &import_edit.import.import_path;
273 if let Some(import_name) = import_path.segments().last() {
274 let data = lsp_ext::CompletionResolveData {
275 position: tdpp.clone(),
276 full_import_path: import_path.to_string(),
277 imported_name: import_name.to_string(),
279 lsp_item.data = Some(to_value(data).unwrap());
284 if let Some((mutability, relevance)) = item.ref_match() {
285 let mut lsp_item_with_ref = lsp_item.clone();
286 set_score(&mut lsp_item_with_ref, max_relevance, relevance);
287 lsp_item_with_ref.label =
288 format!("&{}{}", mutability.as_keyword_for_ref(), lsp_item_with_ref.label);
289 if let Some(it) = &mut lsp_item_with_ref.text_edit {
290 let new_text = match it {
291 lsp_types::CompletionTextEdit::Edit(it) => &mut it.new_text,
292 lsp_types::CompletionTextEdit::InsertAndReplace(it) => &mut it.new_text,
294 *new_text = format!("&{}{}", mutability.as_keyword_for_ref(), new_text);
297 acc.push(lsp_item_with_ref);
303 res: &mut lsp_types::CompletionItem,
305 relevance: CompletionRelevance,
307 if relevance.is_relevant() && relevance.score() == max_relevance {
308 res.preselect = Some(true);
310 // The relevance needs to be inverted to come up with a sort score
311 // because the client will sort ascending.
312 let sort_score = relevance.score() ^ 0xFF_FF_FF_FF;
313 // Zero pad the string to ensure values can be properly sorted
314 // by the client. Hex format is used because it is easier to
315 // visually compare very large values, which the sort text
316 // tends to be since it is the opposite of the score.
317 res.sort_text = Some(format!("{:08x}", sort_score));
321 pub(crate) fn signature_help(
325 ) -> lsp_types::SignatureHelp {
326 let (label, parameters) = match (concise, label_offsets) {
328 let params = call_info
330 .map(|label| lsp_types::ParameterInformation {
331 label: lsp_types::ParameterLabel::Simple(label.to_string()),
334 .collect::<Vec<_>>();
336 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
340 let params = call_info
343 .map(|it| [u32::from(it.start()), u32::from(it.end())])
344 .map(|label_offsets| lsp_types::ParameterInformation {
345 label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
348 .collect::<Vec<_>>();
349 (call_info.signature, params)
352 let mut params = Vec::new();
353 let mut label = String::new();
354 let mut first = true;
355 for param in call_info.parameter_labels() {
357 label.push_str(", ");
360 let start = label.len() as u32;
361 label.push_str(param);
362 let end = label.len() as u32;
363 params.push(lsp_types::ParameterInformation {
364 label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
373 let documentation = if concise {
376 call_info.doc.map(|doc| {
377 lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
378 kind: lsp_types::MarkupKind::Markdown,
384 let active_parameter = call_info.active_parameter.map(|it| it as u32);
386 let signature = lsp_types::SignatureInformation {
389 parameters: Some(parameters),
392 lsp_types::SignatureHelp {
393 signatures: vec![signature],
394 active_signature: None,
399 pub(crate) fn inlay_hint(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
401 label: inlay_hint.label.to_string(),
402 range: range(line_index, inlay_hint.range),
403 kind: match inlay_hint.kind {
404 InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
405 InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
406 InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
411 static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
413 pub(crate) fn semantic_tokens(
415 line_index: &LineIndex,
416 highlights: Vec<HlRange>,
417 highlight_strings: bool,
418 ) -> lsp_types::SemanticTokens {
419 let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
420 let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
422 for highlight_range in highlights {
423 if highlight_range.highlight.is_empty() {
426 let (ty, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
427 if !highlight_strings && ty == lsp_types::SemanticTokenType::STRING {
430 let token_index = semantic_tokens::type_index(ty);
431 let modifier_bitset = mods.0;
433 for mut text_range in line_index.index.lines(highlight_range.range) {
434 if text[text_range].ends_with('\n') {
436 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
438 let range = range(line_index, text_range);
439 builder.push(range, token_index, modifier_bitset);
446 pub(crate) fn semantic_token_delta(
447 previous: &lsp_types::SemanticTokens,
448 current: &lsp_types::SemanticTokens,
449 ) -> lsp_types::SemanticTokensDelta {
450 let result_id = current.result_id.clone();
451 let edits = semantic_tokens::diff_tokens(&previous.data, ¤t.data);
452 lsp_types::SemanticTokensDelta { result_id, edits }
455 fn semantic_token_type_and_modifiers(
456 highlight: Highlight,
457 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
458 let mut mods = semantic_tokens::ModifierSet::default();
459 let type_ = match highlight.tag {
460 HlTag::Symbol(symbol) => match symbol {
461 SymbolKind::Module => lsp_types::SemanticTokenType::NAMESPACE,
462 SymbolKind::Impl => semantic_tokens::TYPE_ALIAS,
463 SymbolKind::Field => lsp_types::SemanticTokenType::PROPERTY,
464 SymbolKind::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
465 SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
466 SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
467 SymbolKind::Label => semantic_tokens::LABEL,
468 SymbolKind::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
469 SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
470 SymbolKind::Local => lsp_types::SemanticTokenType::VARIABLE,
471 SymbolKind::Function => {
472 if highlight.mods.contains(HlMod::Associated) {
473 lsp_types::SemanticTokenType::METHOD
475 lsp_types::SemanticTokenType::FUNCTION
478 SymbolKind::Const => {
479 mods |= semantic_tokens::CONSTANT;
480 mods |= lsp_types::SemanticTokenModifier::STATIC;
481 lsp_types::SemanticTokenType::VARIABLE
483 SymbolKind::Static => {
484 mods |= lsp_types::SemanticTokenModifier::STATIC;
485 lsp_types::SemanticTokenType::VARIABLE
487 SymbolKind::Struct => lsp_types::SemanticTokenType::STRUCT,
488 SymbolKind::Enum => lsp_types::SemanticTokenType::ENUM,
489 SymbolKind::Variant => lsp_types::SemanticTokenType::ENUM_MEMBER,
490 SymbolKind::Union => semantic_tokens::UNION,
491 SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
492 SymbolKind::Trait => lsp_types::SemanticTokenType::INTERFACE,
493 SymbolKind::Macro => lsp_types::SemanticTokenType::MACRO,
495 HlTag::Attribute => semantic_tokens::ATTRIBUTE,
496 HlTag::BoolLiteral => semantic_tokens::BOOLEAN,
497 HlTag::BuiltinAttr => semantic_tokens::BUILTIN_ATTRIBUTE,
498 HlTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
499 HlTag::ByteLiteral | HlTag::NumericLiteral => lsp_types::SemanticTokenType::NUMBER,
500 HlTag::CharLiteral => semantic_tokens::CHAR,
501 HlTag::Comment => lsp_types::SemanticTokenType::COMMENT,
502 HlTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
503 HlTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
504 HlTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
505 HlTag::None => semantic_tokens::GENERIC,
506 HlTag::Operator(op) => match op {
507 HlOperator::Bitwise => semantic_tokens::BITWISE,
508 HlOperator::Arithmetic => semantic_tokens::ARITHMETIC,
509 HlOperator::Logical => semantic_tokens::LOGICAL,
510 HlOperator::Comparison => semantic_tokens::COMPARISON,
511 HlOperator::Other => semantic_tokens::OPERATOR,
513 HlTag::StringLiteral => lsp_types::SemanticTokenType::STRING,
514 HlTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
515 HlTag::Punctuation(punct) => match punct {
516 HlPunct::Bracket => semantic_tokens::BRACKET,
517 HlPunct::Brace => semantic_tokens::BRACE,
518 HlPunct::Parenthesis => semantic_tokens::PARENTHESIS,
519 HlPunct::Angle => semantic_tokens::ANGLE,
520 HlPunct::Comma => semantic_tokens::COMMA,
521 HlPunct::Dot => semantic_tokens::DOT,
522 HlPunct::Colon => semantic_tokens::COLON,
523 HlPunct::Semi => semantic_tokens::SEMICOLON,
524 HlPunct::Other => semantic_tokens::PUNCTUATION,
528 for modifier in highlight.mods.iter() {
529 let modifier = match modifier {
530 HlMod::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
531 HlMod::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
532 HlMod::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
533 HlMod::Injected => semantic_tokens::INJECTED,
534 HlMod::ControlFlow => semantic_tokens::CONTROL_FLOW,
535 HlMod::Mutable => semantic_tokens::MUTABLE,
536 HlMod::Reference => semantic_tokens::REFERENCE,
537 HlMod::Consuming => semantic_tokens::CONSUMING,
538 HlMod::Async => semantic_tokens::ASYNC,
539 HlMod::Library => semantic_tokens::LIBRARY,
540 HlMod::Public => semantic_tokens::PUBLIC,
541 HlMod::Unsafe => semantic_tokens::UNSAFE,
542 HlMod::Callable => semantic_tokens::CALLABLE,
543 HlMod::Static => lsp_types::SemanticTokenModifier::STATIC,
544 HlMod::IntraDocLink => semantic_tokens::INTRA_DOC_LINK,
545 HlMod::Trait => semantic_tokens::TRAIT_MODIFIER,
546 HlMod::Associated => continue,
554 pub(crate) fn folding_range(
556 line_index: &LineIndex,
557 line_folding_only: bool,
559 ) -> lsp_types::FoldingRange {
560 let kind = match fold.kind {
561 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
562 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
563 FoldKind::Region => Some(lsp_types::FoldingRangeKind::Region),
569 | FoldKind::WhereClause
570 | FoldKind::ReturnType
571 | FoldKind::Array => None,
574 let range = range(line_index, fold.range);
576 if line_folding_only {
577 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
578 // even if it contains text not in the folding range. To prevent that we exclude
579 // range.end.line from the folding region if there is more text after range.end
581 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
583 .take_while(|it| *it != '\n')
584 .any(|it| !it.is_whitespace());
586 let end_line = if has_more_text_on_end_line {
587 range.end.line.saturating_sub(1)
592 lsp_types::FoldingRange {
593 start_line: range.start.line,
594 start_character: None,
600 lsp_types::FoldingRange {
601 start_line: range.start.line,
602 start_character: Some(range.start.character),
603 end_line: range.end.line,
604 end_character: Some(range.end.character),
610 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
611 snap.file_id_to_url(file_id)
614 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
615 /// This will only happen when processing windows paths.
617 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
618 pub(crate) fn url_from_abs_path(path: &AbsPath) -> lsp_types::Url {
619 let url = lsp_types::Url::from_file_path(path).unwrap();
620 match path.as_ref().components().next() {
621 Some(path::Component::Prefix(prefix))
622 if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
624 // Need to lowercase driver letter
629 let driver_letter_range = {
630 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
634 let start = scheme.len() + ':'.len_utf8();
635 start..(start + drive_letter.len())
638 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
639 // machinery *also* canonicalizes the drive letter. So, just massage the
641 let mut url: String = url.into();
642 url[driver_letter_range].make_ascii_lowercase();
643 lsp_types::Url::parse(&url).unwrap()
646 pub(crate) fn optional_versioned_text_document_identifier(
647 snap: &GlobalStateSnapshot,
649 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
650 let url = url(snap, file_id);
651 let version = snap.url_file_version(&url);
652 lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
655 pub(crate) fn location(
656 snap: &GlobalStateSnapshot,
658 ) -> Result<lsp_types::Location> {
659 let url = url(snap, frange.file_id);
660 let line_index = snap.file_line_index(frange.file_id)?;
661 let range = range(&line_index, frange.range);
662 let loc = lsp_types::Location::new(url, range);
666 /// Perefer using `location_link`, if the client has the cap.
667 pub(crate) fn location_from_nav(
668 snap: &GlobalStateSnapshot,
669 nav: NavigationTarget,
670 ) -> Result<lsp_types::Location> {
671 let url = url(snap, nav.file_id);
672 let line_index = snap.file_line_index(nav.file_id)?;
673 let range = range(&line_index, nav.full_range);
674 let loc = lsp_types::Location::new(url, range);
678 pub(crate) fn location_link(
679 snap: &GlobalStateSnapshot,
680 src: Option<FileRange>,
681 target: NavigationTarget,
682 ) -> Result<lsp_types::LocationLink> {
683 let origin_selection_range = match src {
685 let line_index = snap.file_line_index(src.file_id)?;
686 let range = range(&line_index, src.range);
691 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
692 let res = lsp_types::LocationLink {
693 origin_selection_range,
696 target_selection_range,
702 snap: &GlobalStateSnapshot,
703 target: NavigationTarget,
704 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
705 let line_index = snap.file_line_index(target.file_id)?;
707 let target_uri = url(snap, target.file_id);
708 let target_range = range(&line_index, target.full_range);
709 let target_selection_range =
710 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
711 Ok((target_uri, target_range, target_selection_range))
714 pub(crate) fn goto_definition_response(
715 snap: &GlobalStateSnapshot,
716 src: Option<FileRange>,
717 targets: Vec<NavigationTarget>,
718 ) -> Result<lsp_types::GotoDefinitionResponse> {
719 if snap.config.location_link() {
722 .map(|nav| location_link(snap, src, nav))
723 .collect::<Result<Vec<_>>>()?;
726 let locations = targets
729 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
731 .collect::<Result<Vec<_>>>()?;
736 fn outside_workspace_annotation_id() -> String {
737 String::from("OutsideWorkspace")
740 pub(crate) fn snippet_text_document_edit(
741 snap: &GlobalStateSnapshot,
745 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
746 let text_document = optional_versioned_text_document_identifier(snap, file_id);
747 let line_index = snap.file_line_index(file_id)?;
748 let mut edits: Vec<_> =
749 edit.into_iter().map(|it| snippet_text_edit(&line_index, is_snippet, it)).collect();
751 if snap.analysis.is_library_file(file_id)? && snap.config.change_annotation_support() {
752 for edit in &mut edits {
753 edit.annotation_id = Some(outside_workspace_annotation_id())
756 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
759 pub(crate) fn snippet_text_document_ops(
760 snap: &GlobalStateSnapshot,
761 file_system_edit: FileSystemEdit,
762 ) -> Cancellable<Vec<lsp_ext::SnippetDocumentChangeOperation>> {
763 let mut ops = Vec::new();
764 match file_system_edit {
765 FileSystemEdit::CreateFile { dst, initial_contents } => {
766 let uri = snap.anchored_path(&dst);
767 let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
772 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
773 if !initial_contents.is_empty() {
775 lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
776 let text_edit = lsp_ext::SnippetTextEdit {
777 range: lsp_types::Range::default(),
778 new_text: initial_contents,
779 insert_text_format: Some(lsp_types::InsertTextFormat::PlainText),
783 lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
784 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
787 FileSystemEdit::MoveFile { src, dst } => {
788 let old_uri = snap.file_id_to_url(src);
789 let new_uri = snap.anchored_path(&dst);
790 let mut rename_file =
791 lsp_types::RenameFile { old_uri, new_uri, options: None, annotation_id: None };
792 if snap.analysis.is_library_file(src).ok() == Some(true)
793 && snap.config.change_annotation_support()
795 rename_file.annotation_id = Some(outside_workspace_annotation_id())
797 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(lsp_types::ResourceOp::Rename(
805 pub(crate) fn snippet_workspace_edit(
806 snap: &GlobalStateSnapshot,
807 source_change: SourceChange,
808 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
809 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
811 for op in source_change.file_system_edits {
812 let ops = snippet_text_document_ops(snap, op)?;
813 document_changes.extend_from_slice(&ops);
815 for (file_id, edit) in source_change.source_file_edits {
816 let edit = snippet_text_document_edit(snap, source_change.is_snippet, file_id, edit)?;
817 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
819 let mut workspace_edit = lsp_ext::SnippetWorkspaceEdit {
821 document_changes: Some(document_changes),
822 change_annotations: None,
824 if snap.config.change_annotation_support() {
825 workspace_edit.change_annotations = Some(
827 outside_workspace_annotation_id(),
828 lsp_types::ChangeAnnotation {
829 label: String::from("Edit outside of the workspace"),
830 needs_confirmation: Some(true),
831 description: Some(String::from(
832 "This edit lies outside of the workspace and may affect dependencies",
842 pub(crate) fn workspace_edit(
843 snap: &GlobalStateSnapshot,
844 source_change: SourceChange,
845 ) -> Result<lsp_types::WorkspaceEdit> {
846 assert!(!source_change.is_snippet);
847 snippet_workspace_edit(snap, source_change).map(|it| it.into())
850 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
851 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
852 lsp_types::WorkspaceEdit {
854 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
855 lsp_types::DocumentChanges::Operations(
858 .map(|change| match change {
859 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
860 lsp_types::DocumentChangeOperation::Op(op)
862 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
863 lsp_types::DocumentChangeOperation::Edit(
864 lsp_types::TextDocumentEdit {
865 text_document: edit.text_document,
866 edits: edit.edits.into_iter().map(From::from).collect(),
874 change_annotations: snippet_workspace_edit.change_annotations,
879 impl From<lsp_ext::SnippetTextEdit>
880 for lsp_types::OneOf<lsp_types::TextEdit, lsp_types::AnnotatedTextEdit>
883 lsp_ext::SnippetTextEdit { annotation_id, insert_text_format:_, new_text, range }: lsp_ext::SnippetTextEdit,
885 match annotation_id {
886 Some(annotation_id) => lsp_types::OneOf::Right(lsp_types::AnnotatedTextEdit {
887 text_edit: lsp_types::TextEdit { range, new_text },
890 None => lsp_types::OneOf::Left(lsp_types::TextEdit { range, new_text }),
895 pub(crate) fn call_hierarchy_item(
896 snap: &GlobalStateSnapshot,
897 target: NavigationTarget,
898 ) -> Result<lsp_types::CallHierarchyItem> {
899 let name = target.name.to_string();
900 let detail = target.description.clone();
901 let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::Function);
902 let (uri, range, selection_range) = location_info(snap, target)?;
903 Ok(lsp_types::CallHierarchyItem {
915 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
917 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
918 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
919 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
920 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
921 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
922 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
926 pub(crate) fn code_action(
927 snap: &GlobalStateSnapshot,
929 resolve_data: Option<(usize, lsp_types::CodeActionParams)>,
930 ) -> Result<lsp_ext::CodeAction> {
931 let mut res = lsp_ext::CodeAction {
932 title: assist.label.to_string(),
933 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
934 kind: Some(code_action_kind(assist.id.1)),
939 match (assist.source_change, resolve_data) {
940 (Some(it), _) => res.edit = Some(snippet_workspace_edit(snap, it)?),
941 (None, Some((index, code_action_params))) => {
942 res.data = Some(lsp_ext::CodeActionData {
943 id: format!("{}:{}:{}", assist.id.0, assist.id.1.name(), index),
948 stdx::never!("assist should always be resolved if client can't do lazy resolving")
954 pub(crate) fn runnable(
955 snap: &GlobalStateSnapshot,
957 ) -> Result<lsp_ext::Runnable> {
958 let config = snap.config.runnables();
959 let spec = CargoTargetSpec::for_file(snap, runnable.nav.file_id)?;
960 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
961 let target = spec.as_ref().map(|s| s.target.clone());
962 let (cargo_args, executable_args) =
963 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
964 let label = runnable.label(target);
965 let location = location_link(snap, None, runnable.nav)?;
967 Ok(lsp_ext::Runnable {
969 location: Some(location),
970 kind: lsp_ext::RunnableKind::Cargo,
971 args: lsp_ext::CargoRunnable {
972 workspace_root: workspace_root.map(|it| it.into()),
973 override_cargo: config.override_cargo,
975 cargo_extra_args: config.cargo_extra_args,
982 pub(crate) fn code_lens(
983 acc: &mut Vec<lsp_types::CodeLens>,
984 snap: &GlobalStateSnapshot,
985 annotation: Annotation,
987 let client_commands_config = snap.config.client_commands();
988 match annotation.kind {
989 AnnotationKind::Runnable(run) => {
990 let line_index = snap.file_line_index(run.nav.file_id)?;
991 let annotation_range = range(&line_index, annotation.range);
993 let title = run.title();
994 let can_debug = match run.kind {
995 ide::RunnableKind::DocTest { .. } => false,
996 ide::RunnableKind::TestMod { .. }
997 | ide::RunnableKind::Test { .. }
998 | ide::RunnableKind::Bench { .. }
999 | ide::RunnableKind::Bin => true,
1001 let r = runnable(snap, run)?;
1003 let lens_config = snap.config.lens();
1004 if lens_config.run && client_commands_config.run_single {
1005 let command = command::run_single(&r, &title);
1006 acc.push(lsp_types::CodeLens {
1007 range: annotation_range,
1008 command: Some(command),
1012 if lens_config.debug && can_debug && client_commands_config.debug_single {
1013 let command = command::debug_single(&r);
1014 acc.push(lsp_types::CodeLens {
1015 range: annotation_range,
1016 command: Some(command),
1021 AnnotationKind::HasImpls { position: file_position, data } => {
1022 if !client_commands_config.show_reference {
1025 let line_index = snap.file_line_index(file_position.file_id)?;
1026 let annotation_range = range(&line_index, annotation.range);
1027 let url = url(snap, file_position.file_id);
1029 let position = position(&line_index, file_position.offset);
1031 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1033 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
1035 let goto_params = lsp_types::request::GotoImplementationParams {
1036 text_document_position_params: doc_pos,
1037 work_done_progress_params: Default::default(),
1038 partial_result_params: Default::default(),
1041 let command = data.map(|ranges| {
1042 let locations: Vec<lsp_types::Location> = ranges
1044 .filter_map(|target| {
1047 FileRange { file_id: target.file_id, range: target.full_range },
1053 command::show_references(
1054 implementation_title(locations.len()),
1061 acc.push(lsp_types::CodeLens {
1062 range: annotation_range,
1064 data: Some(to_value(lsp_ext::CodeLensResolveData::Impls(goto_params)).unwrap()),
1067 AnnotationKind::HasReferences { position: file_position, data } => {
1068 if !client_commands_config.show_reference {
1071 let line_index = snap.file_line_index(file_position.file_id)?;
1072 let annotation_range = range(&line_index, annotation.range);
1073 let url = url(snap, file_position.file_id);
1075 let position = position(&line_index, file_position.offset);
1077 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1079 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
1081 let command = data.map(|ranges| {
1082 let locations: Vec<lsp_types::Location> =
1083 ranges.into_iter().filter_map(|range| location(snap, range).ok()).collect();
1085 command::show_references(
1086 reference_title(locations.len()),
1093 acc.push(lsp_types::CodeLens {
1094 range: annotation_range,
1096 data: Some(to_value(lsp_ext::CodeLensResolveData::References(doc_pos)).unwrap()),
1103 pub(crate) mod command {
1104 use ide::{FileRange, NavigationTarget};
1105 use serde_json::to_value;
1108 global_state::GlobalStateSnapshot,
1110 to_proto::{location, location_link},
1113 pub(crate) fn show_references(
1115 uri: &lsp_types::Url,
1116 position: lsp_types::Position,
1117 locations: Vec<lsp_types::Location>,
1118 ) -> lsp_types::Command {
1119 // We cannot use the 'editor.action.showReferences' command directly
1120 // because that command requires vscode types which we convert in the handler
1121 // on the client side.
1123 lsp_types::Command {
1125 command: "rust-analyzer.showReferences".into(),
1126 arguments: Some(vec![
1127 to_value(uri).unwrap(),
1128 to_value(position).unwrap(),
1129 to_value(locations).unwrap(),
1134 pub(crate) fn run_single(runnable: &lsp_ext::Runnable, title: &str) -> lsp_types::Command {
1135 lsp_types::Command {
1136 title: title.to_string(),
1137 command: "rust-analyzer.runSingle".into(),
1138 arguments: Some(vec![to_value(runnable).unwrap()]),
1142 pub(crate) fn debug_single(runnable: &lsp_ext::Runnable) -> lsp_types::Command {
1143 lsp_types::Command {
1144 title: "Debug".into(),
1145 command: "rust-analyzer.debugSingle".into(),
1146 arguments: Some(vec![to_value(runnable).unwrap()]),
1150 pub(crate) fn goto_location(
1151 snap: &GlobalStateSnapshot,
1152 nav: &NavigationTarget,
1153 ) -> Option<lsp_types::Command> {
1154 let value = if snap.config.location_link() {
1155 let link = location_link(snap, None, nav.clone()).ok()?;
1156 to_value(link).ok()?
1158 let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1159 let location = location(snap, range).ok()?;
1160 to_value(location).ok()?
1163 Some(lsp_types::Command {
1164 title: nav.name.to_string(),
1165 command: "rust-analyzer.gotoLocation".into(),
1166 arguments: Some(vec![value]),
1170 pub(crate) fn trigger_parameter_hints() -> lsp_types::Command {
1171 lsp_types::Command {
1172 title: "triggerParameterHints".into(),
1173 command: "editor.action.triggerParameterHints".into(),
1179 pub(crate) fn implementation_title(count: usize) -> String {
1181 "1 implementation".into()
1183 format!("{} implementations", count)
1187 pub(crate) fn reference_title(count: usize) -> String {
1189 "1 reference".into()
1191 format!("{} references", count)
1195 pub(crate) fn markup_content(markup: Markup) -> lsp_types::MarkupContent {
1196 let value = crate::markdown::format_docs(markup.as_str());
1197 lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value }
1200 pub(crate) fn rename_error(err: RenameError) -> crate::LspError {
1201 crate::LspError { code: lsp_server::ErrorCode::InvalidParams as i32, message: err.to_string() }
1213 fn conv_fold_line_folding_only_fixup() {
1214 let text = r#"mod a;
1226 let (analysis, file_id) = Analysis::from_single_file(text.to_string());
1227 let folds = analysis.folding_ranges(file_id).unwrap();
1228 assert_eq!(folds.len(), 4);
1230 let line_index = LineIndex {
1231 index: Arc::new(ide::LineIndex::new(text)),
1232 endings: LineEndings::Unix,
1233 encoding: OffsetEncoding::Utf16,
1235 let converted: Vec<lsp_types::FoldingRange> =
1236 folds.into_iter().map(|it| folding_range(text, &line_index, true, it)).collect();
1238 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
1239 assert_eq!(converted.len(), expected_lines.len());
1240 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
1241 assert_eq!(folding_range.start_line, *start_line);
1242 assert_eq!(folding_range.start_character, None);
1243 assert_eq!(folding_range.end_line, *end_line);
1244 assert_eq!(folding_range.end_character, None);
1248 // `Url` is not able to parse windows paths on unix machines.
1250 #[cfg(target_os = "windows")]
1251 fn test_lowercase_drive_letter() {
1252 use std::{convert::TryInto, path::Path};
1254 let url = url_from_abs_path(Path::new("C:\\Test").try_into().unwrap());
1255 assert_eq!(url.to_string(), "file:///c:/Test");
1257 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#).try_into().unwrap());
1258 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");