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,
21 global_state::GlobalStateSnapshot,
22 line_index::{LineEndings, LineIndex, OffsetEncoding},
23 lsp_ext, semantic_tokens, Result,
26 pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position {
27 let line_col = line_index.index.line_col(offset);
28 match line_index.encoding {
29 OffsetEncoding::Utf8 => lsp_types::Position::new(line_col.line, line_col.col),
30 OffsetEncoding::Utf16 => {
31 let line_col = line_index.index.to_utf16(line_col);
32 lsp_types::Position::new(line_col.line, line_col.col)
37 pub(crate) fn range(line_index: &LineIndex, range: TextRange) -> lsp_types::Range {
38 let start = position(line_index, range.start());
39 let end = position(line_index, range.end());
40 lsp_types::Range::new(start, end)
43 pub(crate) fn symbol_kind(symbol_kind: SymbolKind) -> lsp_types::SymbolKind {
45 SymbolKind::Function => lsp_types::SymbolKind::Function,
46 SymbolKind::Struct => lsp_types::SymbolKind::Struct,
47 SymbolKind::Enum => lsp_types::SymbolKind::Enum,
48 SymbolKind::Variant => lsp_types::SymbolKind::EnumMember,
49 SymbolKind::Trait => lsp_types::SymbolKind::Interface,
50 SymbolKind::Macro => lsp_types::SymbolKind::Function,
51 SymbolKind::Module => lsp_types::SymbolKind::Module,
52 SymbolKind::TypeAlias | SymbolKind::TypeParam => lsp_types::SymbolKind::TypeParameter,
53 SymbolKind::Field => lsp_types::SymbolKind::Field,
54 SymbolKind::Static => lsp_types::SymbolKind::Constant,
55 SymbolKind::Const => lsp_types::SymbolKind::Constant,
56 SymbolKind::ConstParam => lsp_types::SymbolKind::Constant,
57 SymbolKind::Impl => lsp_types::SymbolKind::Object,
59 | SymbolKind::SelfParam
60 | SymbolKind::LifetimeParam
61 | SymbolKind::ValueParam
62 | SymbolKind::Label => lsp_types::SymbolKind::Variable,
63 SymbolKind::Union => lsp_types::SymbolKind::Struct,
67 pub(crate) fn structure_node_kind(kind: StructureNodeKind) -> lsp_types::SymbolKind {
69 StructureNodeKind::SymbolKind(symbol) => symbol_kind(symbol),
70 StructureNodeKind::Region => lsp_types::SymbolKind::Namespace,
74 pub(crate) fn document_highlight_kind(
75 reference_access: ReferenceAccess,
76 ) -> lsp_types::DocumentHighlightKind {
77 match reference_access {
78 ReferenceAccess::Read => lsp_types::DocumentHighlightKind::Read,
79 ReferenceAccess::Write => lsp_types::DocumentHighlightKind::Write,
83 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
85 Severity::Error => lsp_types::DiagnosticSeverity::Error,
86 Severity::WeakWarning => lsp_types::DiagnosticSeverity::Hint,
90 pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
91 let value = crate::markdown::format_docs(documentation.as_str());
92 let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
93 lsp_types::Documentation::MarkupContent(markup_content)
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 completion_text_edit(
142 line_index: &LineIndex,
143 insert_replace_support: Option<lsp_types::Position>,
145 ) -> lsp_types::CompletionTextEdit {
146 let text_edit = text_edit(line_index, indel);
147 match insert_replace_support {
148 Some(cursor_pos) => lsp_types::InsertReplaceEdit {
149 new_text: text_edit.new_text,
150 insert: lsp_types::Range { start: text_edit.range.start, end: cursor_pos },
151 replace: text_edit.range,
154 None => text_edit.into(),
158 pub(crate) fn snippet_text_edit(
159 line_index: &LineIndex,
162 ) -> lsp_ext::SnippetTextEdit {
163 let text_edit = text_edit(line_index, indel);
164 let insert_text_format =
165 if is_snippet { Some(lsp_types::InsertTextFormat::Snippet) } else { None };
166 lsp_ext::SnippetTextEdit {
167 range: text_edit.range,
168 new_text: text_edit.new_text,
174 pub(crate) fn text_edit_vec(
175 line_index: &LineIndex,
177 ) -> Vec<lsp_types::TextEdit> {
178 text_edit.into_iter().map(|indel| self::text_edit(line_index, indel)).collect()
181 pub(crate) fn snippet_text_edit_vec(
182 line_index: &LineIndex,
185 ) -> Vec<lsp_ext::SnippetTextEdit> {
188 .map(|indel| self::snippet_text_edit(line_index, is_snippet, indel))
192 pub(crate) fn completion_items(
193 insert_replace_support: bool,
194 enable_imports_on_the_fly: bool,
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());
204 insert_replace_support,
205 enable_imports_on_the_fly,
216 acc: &mut Vec<lsp_types::CompletionItem>,
217 insert_replace_support: bool,
218 enable_imports_on_the_fly: bool,
219 line_index: &LineIndex,
220 tdpp: &lsp_types::TextDocumentPositionParams,
222 item: CompletionItem,
224 let mut additional_text_edits = Vec::new();
226 // LSP does not allow arbitrary edits in completion, so we have to do a
227 // non-trivial mapping here.
229 let mut text_edit = None;
230 let source_range = item.source_range();
231 for indel in item.text_edit().iter() {
232 if indel.delete.contains_range(source_range) {
233 let insert_replace_support = insert_replace_support.then(|| tdpp.position);
234 text_edit = Some(if indel.delete == source_range {
235 self::completion_text_edit(line_index, insert_replace_support, indel.clone())
237 assert!(source_range.end() == indel.delete.end());
238 let range1 = TextRange::new(indel.delete.start(), source_range.start());
239 let range2 = source_range;
240 let indel1 = Indel::replace(range1, String::new());
241 let indel2 = Indel::replace(range2, indel.insert.clone());
242 additional_text_edits.push(self::text_edit(line_index, indel1));
243 self::completion_text_edit(line_index, insert_replace_support, indel2)
246 assert!(source_range.intersect(indel.delete).is_none());
247 let text_edit = self::text_edit(line_index, indel.clone());
248 additional_text_edits.push(text_edit);
254 let mut lsp_item = lsp_types::CompletionItem {
255 label: item.label().to_string(),
256 detail: item.detail().map(|it| it.to_string()),
257 filter_text: Some(item.lookup().to_string()),
258 kind: item.kind().map(completion_item_kind),
259 text_edit: Some(text_edit),
260 additional_text_edits: Some(additional_text_edits),
261 documentation: item.documentation().map(documentation),
262 deprecated: Some(item.deprecated()),
266 set_score(&mut lsp_item, max_relevance, item.relevance());
268 if item.deprecated() {
269 lsp_item.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
272 if item.trigger_call_info() {
273 lsp_item.command = Some(command::trigger_parameter_hints());
276 if item.is_snippet() {
277 lsp_item.insert_text_format = Some(lsp_types::InsertTextFormat::Snippet);
279 if enable_imports_on_the_fly {
280 if let Some(import_edit) = item.import_to_add() {
281 let import_path = &import_edit.import.import_path;
282 if let Some(import_name) = import_path.segments().last() {
283 let data = lsp_ext::CompletionResolveData {
284 position: tdpp.clone(),
285 full_import_path: import_path.to_string(),
286 imported_name: import_name.to_string(),
288 lsp_item.data = Some(to_value(data).unwrap());
293 if let Some((mutability, relevance)) = item.ref_match() {
294 let mut lsp_item_with_ref = lsp_item.clone();
295 set_score(&mut lsp_item_with_ref, max_relevance, relevance);
296 lsp_item_with_ref.label =
297 format!("&{}{}", mutability.as_keyword_for_ref(), lsp_item_with_ref.label);
298 if let Some(it) = &mut lsp_item_with_ref.text_edit {
299 let new_text = match it {
300 lsp_types::CompletionTextEdit::Edit(it) => &mut it.new_text,
301 lsp_types::CompletionTextEdit::InsertAndReplace(it) => &mut it.new_text,
303 *new_text = format!("&{}{}", mutability.as_keyword_for_ref(), new_text);
306 acc.push(lsp_item_with_ref);
312 res: &mut lsp_types::CompletionItem,
314 relevance: CompletionRelevance,
316 if relevance.is_relevant() && relevance.score() == max_relevance {
317 res.preselect = Some(true);
319 // The relevance needs to be inverted to come up with a sort score
320 // because the client will sort ascending.
321 let sort_score = relevance.score() ^ 0xFF_FF_FF_FF;
322 // Zero pad the string to ensure values can be properly sorted
323 // by the client. Hex format is used because it is easier to
324 // visually compare very large values, which the sort text
325 // tends to be since it is the opposite of the score.
326 res.sort_text = Some(format!("{:08x}", sort_score));
330 pub(crate) fn signature_help(
334 ) -> lsp_types::SignatureHelp {
335 let (label, parameters) = match (concise, label_offsets) {
337 let params = call_info
339 .map(|label| lsp_types::ParameterInformation {
340 label: lsp_types::ParameterLabel::Simple(label.to_string()),
343 .collect::<Vec<_>>();
345 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
349 let params = call_info
352 .map(|it| [u32::from(it.start()), u32::from(it.end())])
353 .map(|label_offsets| lsp_types::ParameterInformation {
354 label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
357 .collect::<Vec<_>>();
358 (call_info.signature, params)
361 let mut params = Vec::new();
362 let mut label = String::new();
363 let mut first = true;
364 for param in call_info.parameter_labels() {
366 label.push_str(", ");
369 let start = label.len() as u32;
370 label.push_str(param);
371 let end = label.len() as u32;
372 params.push(lsp_types::ParameterInformation {
373 label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
382 let documentation = if concise {
385 call_info.doc.map(|doc| {
386 lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
387 kind: lsp_types::MarkupKind::Markdown,
393 let active_parameter = call_info.active_parameter.map(|it| it as u32);
395 let signature = lsp_types::SignatureInformation {
398 parameters: Some(parameters),
401 lsp_types::SignatureHelp {
402 signatures: vec![signature],
403 active_signature: None,
408 pub(crate) fn inlay_hint(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
410 label: inlay_hint.label.to_string(),
411 range: range(line_index, inlay_hint.range),
412 kind: match inlay_hint.kind {
413 InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
414 InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
415 InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
420 static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
422 pub(crate) fn semantic_tokens(
424 line_index: &LineIndex,
425 highlights: Vec<HlRange>,
426 highlight_strings: bool,
427 ) -> lsp_types::SemanticTokens {
428 let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
429 let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
431 for highlight_range in highlights {
432 if highlight_range.highlight.is_empty() {
435 let (ty, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
436 if !highlight_strings && ty == lsp_types::SemanticTokenType::STRING {
439 let token_index = semantic_tokens::type_index(ty);
440 let modifier_bitset = mods.0;
442 for mut text_range in line_index.index.lines(highlight_range.range) {
443 if text[text_range].ends_with('\n') {
445 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
447 let range = range(line_index, text_range);
448 builder.push(range, token_index, modifier_bitset);
455 pub(crate) fn semantic_token_delta(
456 previous: &lsp_types::SemanticTokens,
457 current: &lsp_types::SemanticTokens,
458 ) -> lsp_types::SemanticTokensDelta {
459 let result_id = current.result_id.clone();
460 let edits = semantic_tokens::diff_tokens(&previous.data, ¤t.data);
461 lsp_types::SemanticTokensDelta { result_id, edits }
464 fn semantic_token_type_and_modifiers(
465 highlight: Highlight,
466 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
467 let mut mods = semantic_tokens::ModifierSet::default();
468 let type_ = match highlight.tag {
469 HlTag::Symbol(symbol) => match symbol {
470 SymbolKind::Module => lsp_types::SemanticTokenType::NAMESPACE,
471 SymbolKind::Impl => semantic_tokens::TYPE_ALIAS,
472 SymbolKind::Field => lsp_types::SemanticTokenType::PROPERTY,
473 SymbolKind::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
474 SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
475 SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
476 SymbolKind::Label => semantic_tokens::LABEL,
477 SymbolKind::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
478 SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
479 SymbolKind::Local => lsp_types::SemanticTokenType::VARIABLE,
480 SymbolKind::Function => {
481 if highlight.mods.contains(HlMod::Associated) {
482 lsp_types::SemanticTokenType::METHOD
484 lsp_types::SemanticTokenType::FUNCTION
487 SymbolKind::Const => {
488 mods |= semantic_tokens::CONSTANT;
489 mods |= lsp_types::SemanticTokenModifier::STATIC;
490 lsp_types::SemanticTokenType::VARIABLE
492 SymbolKind::Static => {
493 mods |= lsp_types::SemanticTokenModifier::STATIC;
494 lsp_types::SemanticTokenType::VARIABLE
496 SymbolKind::Struct => lsp_types::SemanticTokenType::STRUCT,
497 SymbolKind::Enum => lsp_types::SemanticTokenType::ENUM,
498 SymbolKind::Variant => lsp_types::SemanticTokenType::ENUM_MEMBER,
499 SymbolKind::Union => semantic_tokens::UNION,
500 SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
501 SymbolKind::Trait => lsp_types::SemanticTokenType::INTERFACE,
502 SymbolKind::Macro => lsp_types::SemanticTokenType::MACRO,
504 HlTag::Attribute => semantic_tokens::ATTRIBUTE,
505 HlTag::BoolLiteral => semantic_tokens::BOOLEAN,
506 HlTag::BuiltinAttr => semantic_tokens::BUILTIN_ATTRIBUTE,
507 HlTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
508 HlTag::ByteLiteral | HlTag::NumericLiteral => lsp_types::SemanticTokenType::NUMBER,
509 HlTag::CharLiteral => semantic_tokens::CHAR,
510 HlTag::Comment => lsp_types::SemanticTokenType::COMMENT,
511 HlTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
512 HlTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
513 HlTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
514 HlTag::None => semantic_tokens::GENERIC,
515 HlTag::Operator(op) => match op {
516 HlOperator::Bitwise => semantic_tokens::BITWISE,
517 HlOperator::Arithmetic => semantic_tokens::ARITHMETIC,
518 HlOperator::Logical => semantic_tokens::LOGICAL,
519 HlOperator::Comparison => semantic_tokens::COMPARISON,
520 HlOperator::Other => semantic_tokens::OPERATOR,
522 HlTag::StringLiteral => lsp_types::SemanticTokenType::STRING,
523 HlTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
524 HlTag::Punctuation(punct) => match punct {
525 HlPunct::Bracket => semantic_tokens::BRACKET,
526 HlPunct::Brace => semantic_tokens::BRACE,
527 HlPunct::Parenthesis => semantic_tokens::PARENTHESIS,
528 HlPunct::Angle => semantic_tokens::ANGLE,
529 HlPunct::Comma => semantic_tokens::COMMA,
530 HlPunct::Dot => semantic_tokens::DOT,
531 HlPunct::Colon => semantic_tokens::COLON,
532 HlPunct::Semi => semantic_tokens::SEMICOLON,
533 HlPunct::Other => semantic_tokens::PUNCTUATION,
537 for modifier in highlight.mods.iter() {
538 let modifier = match modifier {
539 HlMod::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
540 HlMod::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
541 HlMod::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
542 HlMod::Injected => semantic_tokens::INJECTED,
543 HlMod::ControlFlow => semantic_tokens::CONTROL_FLOW,
544 HlMod::Mutable => semantic_tokens::MUTABLE,
545 HlMod::Consuming => semantic_tokens::CONSUMING,
546 HlMod::Async => semantic_tokens::ASYNC,
547 HlMod::Library => semantic_tokens::LIBRARY,
548 HlMod::Public => semantic_tokens::PUBLIC,
549 HlMod::Unsafe => semantic_tokens::UNSAFE,
550 HlMod::Callable => semantic_tokens::CALLABLE,
551 HlMod::Static => lsp_types::SemanticTokenModifier::STATIC,
552 HlMod::IntraDocLink => semantic_tokens::INTRA_DOC_LINK,
553 HlMod::Trait => semantic_tokens::TRAIT_MODIFIER,
554 HlMod::Associated => continue,
562 pub(crate) fn folding_range(
564 line_index: &LineIndex,
565 line_folding_only: bool,
567 ) -> lsp_types::FoldingRange {
568 let kind = match fold.kind {
569 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
570 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
571 FoldKind::Region => Some(lsp_types::FoldingRangeKind::Region),
577 | FoldKind::WhereClause
578 | FoldKind::ReturnType
579 | FoldKind::Array => None,
582 let range = range(line_index, fold.range);
584 if line_folding_only {
585 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
586 // even if it contains text not in the folding range. To prevent that we exclude
587 // range.end.line from the folding region if there is more text after range.end
589 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
591 .take_while(|it| *it != '\n')
592 .any(|it| !it.is_whitespace());
594 let end_line = if has_more_text_on_end_line {
595 range.end.line.saturating_sub(1)
600 lsp_types::FoldingRange {
601 start_line: range.start.line,
602 start_character: None,
608 lsp_types::FoldingRange {
609 start_line: range.start.line,
610 start_character: Some(range.start.character),
611 end_line: range.end.line,
612 end_character: Some(range.end.character),
618 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
619 snap.file_id_to_url(file_id)
622 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
623 /// This will only happen when processing windows paths.
625 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
626 pub(crate) fn url_from_abs_path(path: &AbsPath) -> lsp_types::Url {
627 let url = lsp_types::Url::from_file_path(path).unwrap();
628 match path.as_ref().components().next() {
629 Some(path::Component::Prefix(prefix))
630 if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
632 // Need to lowercase driver letter
637 let driver_letter_range = {
638 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
642 let start = scheme.len() + ':'.len_utf8();
643 start..(start + drive_letter.len())
646 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
647 // machinery *also* canonicalizes the drive letter. So, just massage the
649 let mut url: String = url.into();
650 url[driver_letter_range].make_ascii_lowercase();
651 lsp_types::Url::parse(&url).unwrap()
654 pub(crate) fn optional_versioned_text_document_identifier(
655 snap: &GlobalStateSnapshot,
657 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
658 let url = url(snap, file_id);
659 let version = snap.url_file_version(&url);
660 lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
663 pub(crate) fn location(
664 snap: &GlobalStateSnapshot,
666 ) -> Result<lsp_types::Location> {
667 let url = url(snap, frange.file_id);
668 let line_index = snap.file_line_index(frange.file_id)?;
669 let range = range(&line_index, frange.range);
670 let loc = lsp_types::Location::new(url, range);
674 /// Perefer using `location_link`, if the client has the cap.
675 pub(crate) fn location_from_nav(
676 snap: &GlobalStateSnapshot,
677 nav: NavigationTarget,
678 ) -> Result<lsp_types::Location> {
679 let url = url(snap, nav.file_id);
680 let line_index = snap.file_line_index(nav.file_id)?;
681 let range = range(&line_index, nav.full_range);
682 let loc = lsp_types::Location::new(url, range);
686 pub(crate) fn location_link(
687 snap: &GlobalStateSnapshot,
688 src: Option<FileRange>,
689 target: NavigationTarget,
690 ) -> Result<lsp_types::LocationLink> {
691 let origin_selection_range = match src {
693 let line_index = snap.file_line_index(src.file_id)?;
694 let range = range(&line_index, src.range);
699 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
700 let res = lsp_types::LocationLink {
701 origin_selection_range,
704 target_selection_range,
710 snap: &GlobalStateSnapshot,
711 target: NavigationTarget,
712 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
713 let line_index = snap.file_line_index(target.file_id)?;
715 let target_uri = url(snap, target.file_id);
716 let target_range = range(&line_index, target.full_range);
717 let target_selection_range =
718 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
719 Ok((target_uri, target_range, target_selection_range))
722 pub(crate) fn goto_definition_response(
723 snap: &GlobalStateSnapshot,
724 src: Option<FileRange>,
725 targets: Vec<NavigationTarget>,
726 ) -> Result<lsp_types::GotoDefinitionResponse> {
727 if snap.config.location_link() {
730 .map(|nav| location_link(snap, src, nav))
731 .collect::<Result<Vec<_>>>()?;
734 let locations = targets
737 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
739 .collect::<Result<Vec<_>>>()?;
744 fn outside_workspace_annotation_id() -> String {
745 String::from("OutsideWorkspace")
748 pub(crate) fn snippet_text_document_edit(
749 snap: &GlobalStateSnapshot,
753 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
754 let text_document = optional_versioned_text_document_identifier(snap, file_id);
755 let line_index = snap.file_line_index(file_id)?;
756 let mut edits: Vec<_> =
757 edit.into_iter().map(|it| snippet_text_edit(&line_index, is_snippet, it)).collect();
759 if snap.analysis.is_library_file(file_id)? && snap.config.change_annotation_support() {
760 for edit in &mut edits {
761 edit.annotation_id = Some(outside_workspace_annotation_id())
764 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
767 pub(crate) fn snippet_text_document_ops(
768 snap: &GlobalStateSnapshot,
769 file_system_edit: FileSystemEdit,
770 ) -> Cancellable<Vec<lsp_ext::SnippetDocumentChangeOperation>> {
771 let mut ops = Vec::new();
772 match file_system_edit {
773 FileSystemEdit::CreateFile { dst, initial_contents } => {
774 let uri = snap.anchored_path(&dst);
775 let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
780 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
781 if !initial_contents.is_empty() {
783 lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
784 let text_edit = lsp_ext::SnippetTextEdit {
785 range: lsp_types::Range::default(),
786 new_text: initial_contents,
787 insert_text_format: Some(lsp_types::InsertTextFormat::PlainText),
791 lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
792 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
795 FileSystemEdit::MoveFile { src, dst } => {
796 let old_uri = snap.file_id_to_url(src);
797 let new_uri = snap.anchored_path(&dst);
798 let mut rename_file =
799 lsp_types::RenameFile { old_uri, new_uri, options: None, annotation_id: None };
800 if snap.analysis.is_library_file(src).ok() == Some(true)
801 && snap.config.change_annotation_support()
803 rename_file.annotation_id = Some(outside_workspace_annotation_id())
805 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(lsp_types::ResourceOp::Rename(
813 pub(crate) fn snippet_workspace_edit(
814 snap: &GlobalStateSnapshot,
815 source_change: SourceChange,
816 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
817 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
819 for op in source_change.file_system_edits {
820 let ops = snippet_text_document_ops(snap, op)?;
821 document_changes.extend_from_slice(&ops);
823 for (file_id, edit) in source_change.source_file_edits {
824 let edit = snippet_text_document_edit(snap, source_change.is_snippet, file_id, edit)?;
825 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
827 let mut workspace_edit = lsp_ext::SnippetWorkspaceEdit {
829 document_changes: Some(document_changes),
830 change_annotations: None,
832 if snap.config.change_annotation_support() {
833 workspace_edit.change_annotations = Some(
835 outside_workspace_annotation_id(),
836 lsp_types::ChangeAnnotation {
837 label: String::from("Edit outside of the workspace"),
838 needs_confirmation: Some(true),
839 description: Some(String::from(
840 "This edit lies outside of the workspace and may affect dependencies",
850 pub(crate) fn workspace_edit(
851 snap: &GlobalStateSnapshot,
852 source_change: SourceChange,
853 ) -> Result<lsp_types::WorkspaceEdit> {
854 assert!(!source_change.is_snippet);
855 snippet_workspace_edit(snap, source_change).map(|it| it.into())
858 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
859 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
860 lsp_types::WorkspaceEdit {
862 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
863 lsp_types::DocumentChanges::Operations(
866 .map(|change| match change {
867 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
868 lsp_types::DocumentChangeOperation::Op(op)
870 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
871 lsp_types::DocumentChangeOperation::Edit(
872 lsp_types::TextDocumentEdit {
873 text_document: edit.text_document,
874 edits: edit.edits.into_iter().map(From::from).collect(),
882 change_annotations: snippet_workspace_edit.change_annotations,
887 impl From<lsp_ext::SnippetTextEdit>
888 for lsp_types::OneOf<lsp_types::TextEdit, lsp_types::AnnotatedTextEdit>
891 lsp_ext::SnippetTextEdit { annotation_id, insert_text_format:_, new_text, range }: lsp_ext::SnippetTextEdit,
893 match annotation_id {
894 Some(annotation_id) => lsp_types::OneOf::Right(lsp_types::AnnotatedTextEdit {
895 text_edit: lsp_types::TextEdit { range, new_text },
898 None => lsp_types::OneOf::Left(lsp_types::TextEdit { range, new_text }),
903 pub(crate) fn call_hierarchy_item(
904 snap: &GlobalStateSnapshot,
905 target: NavigationTarget,
906 ) -> Result<lsp_types::CallHierarchyItem> {
907 let name = target.name.to_string();
908 let detail = target.description.clone();
909 let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::Function);
910 let (uri, range, selection_range) = location_info(snap, target)?;
911 Ok(lsp_types::CallHierarchyItem {
923 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
925 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
926 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
927 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
928 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
929 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
930 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
934 pub(crate) fn code_action(
935 snap: &GlobalStateSnapshot,
937 resolve_data: Option<(usize, lsp_types::CodeActionParams)>,
938 ) -> Result<lsp_ext::CodeAction> {
939 let mut res = lsp_ext::CodeAction {
940 title: assist.label.to_string(),
941 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
942 kind: Some(code_action_kind(assist.id.1)),
947 match (assist.source_change, resolve_data) {
948 (Some(it), _) => res.edit = Some(snippet_workspace_edit(snap, it)?),
949 (None, Some((index, code_action_params))) => {
950 res.data = Some(lsp_ext::CodeActionData {
951 id: format!("{}:{}:{}", assist.id.0, assist.id.1.name(), index),
956 stdx::never!("assist should always be resolved if client can't do lazy resolving")
962 pub(crate) fn runnable(
963 snap: &GlobalStateSnapshot,
965 ) -> Result<lsp_ext::Runnable> {
966 let config = snap.config.runnables();
967 let spec = CargoTargetSpec::for_file(snap, runnable.nav.file_id)?;
968 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
969 let target = spec.as_ref().map(|s| s.target.clone());
970 let (cargo_args, executable_args) =
971 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
972 let label = runnable.label(target);
973 let location = location_link(snap, None, runnable.nav)?;
975 Ok(lsp_ext::Runnable {
977 location: Some(location),
978 kind: lsp_ext::RunnableKind::Cargo,
979 args: lsp_ext::CargoRunnable {
980 workspace_root: workspace_root.map(|it| it.into()),
981 override_cargo: config.override_cargo,
983 cargo_extra_args: config.cargo_extra_args,
990 pub(crate) fn code_lens(
991 acc: &mut Vec<lsp_types::CodeLens>,
992 snap: &GlobalStateSnapshot,
993 annotation: Annotation,
995 match annotation.kind {
996 AnnotationKind::Runnable(run) => {
997 let line_index = snap.file_line_index(run.nav.file_id)?;
998 let annotation_range = range(&line_index, annotation.range);
1000 let title = run.title();
1001 let can_debug = match run.kind {
1002 ide::RunnableKind::DocTest { .. } => false,
1003 ide::RunnableKind::TestMod { .. }
1004 | ide::RunnableKind::Test { .. }
1005 | ide::RunnableKind::Bench { .. }
1006 | ide::RunnableKind::Bin => true,
1008 let r = runnable(snap, run)?;
1010 let lens_config = snap.config.lens();
1011 if lens_config.run {
1012 let command = command::run_single(&r, &title);
1013 acc.push(lsp_types::CodeLens {
1014 range: annotation_range,
1015 command: Some(command),
1019 if lens_config.debug && can_debug {
1020 let command = command::debug_single(&r);
1021 acc.push(lsp_types::CodeLens {
1022 range: annotation_range,
1023 command: Some(command),
1028 AnnotationKind::HasImpls { position: file_position, data } => {
1029 let line_index = snap.file_line_index(file_position.file_id)?;
1030 let annotation_range = range(&line_index, annotation.range);
1031 let url = url(snap, file_position.file_id);
1033 let position = position(&line_index, file_position.offset);
1035 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1037 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
1039 let goto_params = lsp_types::request::GotoImplementationParams {
1040 text_document_position_params: doc_pos,
1041 work_done_progress_params: Default::default(),
1042 partial_result_params: Default::default(),
1045 let command = data.map(|ranges| {
1046 let locations: Vec<lsp_types::Location> = ranges
1048 .filter_map(|target| {
1051 FileRange { file_id: target.file_id, range: target.full_range },
1057 command::show_references(
1058 implementation_title(locations.len()),
1065 acc.push(lsp_types::CodeLens {
1066 range: annotation_range,
1068 data: Some(to_value(lsp_ext::CodeLensResolveData::Impls(goto_params)).unwrap()),
1071 AnnotationKind::HasReferences { position: file_position, data } => {
1072 let line_index = snap.file_line_index(file_position.file_id)?;
1073 let annotation_range = range(&line_index, annotation.range);
1074 let url = url(snap, file_position.file_id);
1076 let position = position(&line_index, file_position.offset);
1078 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1080 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
1082 let command = data.map(|ranges| {
1083 let locations: Vec<lsp_types::Location> =
1084 ranges.into_iter().filter_map(|range| location(snap, range).ok()).collect();
1086 command::show_references(
1087 reference_title(locations.len()),
1094 acc.push(lsp_types::CodeLens {
1095 range: annotation_range,
1097 data: Some(to_value(lsp_ext::CodeLensResolveData::References(doc_pos)).unwrap()),
1104 pub(crate) mod command {
1105 use ide::{FileRange, NavigationTarget};
1106 use serde_json::to_value;
1109 global_state::GlobalStateSnapshot,
1111 to_proto::{location, location_link},
1114 pub(crate) fn show_references(
1116 uri: &lsp_types::Url,
1117 position: lsp_types::Position,
1118 locations: Vec<lsp_types::Location>,
1119 ) -> lsp_types::Command {
1120 // We cannot use the 'editor.action.showReferences' command directly
1121 // because that command requires vscode types which we convert in the handler
1122 // on the client side.
1124 lsp_types::Command {
1126 command: "rust-analyzer.showReferences".into(),
1127 arguments: Some(vec![
1128 to_value(uri).unwrap(),
1129 to_value(position).unwrap(),
1130 to_value(locations).unwrap(),
1135 pub(crate) fn run_single(runnable: &lsp_ext::Runnable, title: &str) -> lsp_types::Command {
1136 lsp_types::Command {
1137 title: title.to_string(),
1138 command: "rust-analyzer.runSingle".into(),
1139 arguments: Some(vec![to_value(runnable).unwrap()]),
1143 pub(crate) fn debug_single(runnable: &lsp_ext::Runnable) -> lsp_types::Command {
1144 lsp_types::Command {
1145 title: "Debug".into(),
1146 command: "rust-analyzer.debugSingle".into(),
1147 arguments: Some(vec![to_value(runnable).unwrap()]),
1151 pub(crate) fn goto_location(
1152 snap: &GlobalStateSnapshot,
1153 nav: &NavigationTarget,
1154 ) -> Option<lsp_types::Command> {
1155 let value = if snap.config.location_link() {
1156 let link = location_link(snap, None, nav.clone()).ok()?;
1157 to_value(link).ok()?
1159 let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1160 let location = location(snap, range).ok()?;
1161 to_value(location).ok()?
1164 Some(lsp_types::Command {
1165 title: nav.name.to_string(),
1166 command: "rust-analyzer.gotoLocation".into(),
1167 arguments: Some(vec![value]),
1171 pub(crate) fn trigger_parameter_hints() -> lsp_types::Command {
1172 lsp_types::Command {
1173 title: "triggerParameterHints".into(),
1174 command: "editor.action.triggerParameterHints".into(),
1180 pub(crate) fn implementation_title(count: usize) -> String {
1182 "1 implementation".into()
1184 format!("{} implementations", count)
1188 pub(crate) fn reference_title(count: usize) -> String {
1190 "1 reference".into()
1192 format!("{} references", count)
1196 pub(crate) fn markup_content(markup: Markup) -> lsp_types::MarkupContent {
1197 let value = crate::markdown::format_docs(markup.as_str());
1198 lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value }
1201 pub(crate) fn rename_error(err: RenameError) -> crate::LspError {
1202 crate::LspError { code: lsp_server::ErrorCode::InvalidParams as i32, message: err.to_string() }
1210 use ide_db::helpers::{
1211 insert_use::{ImportGranularity, InsertUseConfig, PrefixKind},
1218 fn test_completion_with_ref() {
1221 fn foo(arg: &Foo) {}
1227 let (offset, text) = test_utils::extract_offset(fixture);
1228 let line_index = LineIndex {
1229 index: Arc::new(ide::LineIndex::new(&text)),
1230 endings: LineEndings::Unix,
1231 encoding: OffsetEncoding::Utf16,
1233 let (analysis, file_id) = Analysis::from_single_file(text);
1235 let file_position = ide_db::base_db::FilePosition { file_id, offset };
1236 let mut items = analysis
1238 &ide::CompletionConfig {
1239 enable_postfix_completions: true,
1240 enable_imports_on_the_fly: true,
1241 enable_self_on_the_fly: true,
1242 add_call_parenthesis: true,
1243 add_call_argument_snippets: true,
1244 snippet_cap: SnippetCap::new(true),
1245 insert_use: InsertUseConfig {
1246 granularity: ImportGranularity::Item,
1247 prefix_kind: PrefixKind::Plain,
1248 enforce_granularity: true,
1250 skip_glob_imports: true,
1257 items.retain(|c| c.label().ends_with("arg"));
1258 let items = completion_items(
1262 lsp_types::TextDocumentPositionParams {
1263 text_document: lsp_types::TextDocumentIdentifier {
1264 uri: "file://main.rs".parse().unwrap(),
1266 position: position(&line_index, file_position.offset),
1270 let items: Vec<(String, Option<String>)> =
1271 items.into_iter().map(|c| (c.label, c.sort_text)).collect();
1273 expect_test::expect![[r#"
1289 .assert_debug_eq(&items);
1293 fn conv_fold_line_folding_only_fixup() {
1294 let text = r#"mod a;
1306 let (analysis, file_id) = Analysis::from_single_file(text.to_string());
1307 let folds = analysis.folding_ranges(file_id).unwrap();
1308 assert_eq!(folds.len(), 4);
1310 let line_index = LineIndex {
1311 index: Arc::new(ide::LineIndex::new(text)),
1312 endings: LineEndings::Unix,
1313 encoding: OffsetEncoding::Utf16,
1315 let converted: Vec<lsp_types::FoldingRange> =
1316 folds.into_iter().map(|it| folding_range(text, &line_index, true, it)).collect();
1318 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
1319 assert_eq!(converted.len(), expected_lines.len());
1320 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
1321 assert_eq!(folding_range.start_line, *start_line);
1322 assert_eq!(folding_range.start_character, None);
1323 assert_eq!(folding_range.end_line, *end_line);
1324 assert_eq!(folding_range.end_character, None);
1328 // `Url` is not able to parse windows paths on unix machines.
1330 #[cfg(target_os = "windows")]
1331 fn test_lowercase_drive_letter() {
1332 use std::{convert::TryInto, path::Path};
1334 let url = url_from_abs_path(Path::new("C:\\Test").try_into().unwrap());
1335 assert_eq!(url.to_string(), "file:///c:/Test");
1337 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#).try_into().unwrap());
1338 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");