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, ReferenceCategory, 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},
25 lsp_utils::invalid_params_error,
26 semantic_tokens, Result,
29 pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position {
30 let line_col = line_index.index.line_col(offset);
31 match line_index.encoding {
32 OffsetEncoding::Utf8 => lsp_types::Position::new(line_col.line, line_col.col),
33 OffsetEncoding::Utf16 => {
34 let line_col = line_index.index.to_utf16(line_col);
35 lsp_types::Position::new(line_col.line, line_col.col)
40 pub(crate) fn range(line_index: &LineIndex, range: TextRange) -> lsp_types::Range {
41 let start = position(line_index, range.start());
42 let end = position(line_index, range.end());
43 lsp_types::Range::new(start, end)
46 pub(crate) fn symbol_kind(symbol_kind: SymbolKind) -> lsp_types::SymbolKind {
48 SymbolKind::Function => lsp_types::SymbolKind::Function,
49 SymbolKind::Struct => lsp_types::SymbolKind::Struct,
50 SymbolKind::Enum => lsp_types::SymbolKind::Enum,
51 SymbolKind::Variant => lsp_types::SymbolKind::EnumMember,
52 SymbolKind::Trait => lsp_types::SymbolKind::Interface,
53 SymbolKind::Macro => lsp_types::SymbolKind::Function,
54 SymbolKind::Module => lsp_types::SymbolKind::Module,
55 SymbolKind::TypeAlias | SymbolKind::TypeParam => lsp_types::SymbolKind::TypeParameter,
56 SymbolKind::Field => lsp_types::SymbolKind::Field,
57 SymbolKind::Static => lsp_types::SymbolKind::Constant,
58 SymbolKind::Const => lsp_types::SymbolKind::Constant,
59 SymbolKind::ConstParam => lsp_types::SymbolKind::Constant,
60 SymbolKind::Impl => lsp_types::SymbolKind::Object,
62 | SymbolKind::SelfParam
63 | SymbolKind::LifetimeParam
64 | SymbolKind::ValueParam
65 | SymbolKind::Label => lsp_types::SymbolKind::Variable,
66 SymbolKind::Union => lsp_types::SymbolKind::Struct,
70 pub(crate) fn structure_node_kind(kind: StructureNodeKind) -> lsp_types::SymbolKind {
72 StructureNodeKind::SymbolKind(symbol) => symbol_kind(symbol),
73 StructureNodeKind::Region => lsp_types::SymbolKind::Namespace,
77 pub(crate) fn document_highlight_kind(
78 category: ReferenceCategory,
79 ) -> lsp_types::DocumentHighlightKind {
81 ReferenceCategory::Read => lsp_types::DocumentHighlightKind::Read,
82 ReferenceCategory::Write => lsp_types::DocumentHighlightKind::Write,
86 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
88 Severity::Error => lsp_types::DiagnosticSeverity::Error,
89 Severity::WeakWarning => lsp_types::DiagnosticSeverity::Hint,
93 pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
94 let value = crate::markdown::format_docs(documentation.as_str());
95 let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
96 lsp_types::Documentation::MarkupContent(markup_content)
99 pub(crate) fn completion_item_kind(
100 completion_item_kind: CompletionItemKind,
101 ) -> lsp_types::CompletionItemKind {
102 match completion_item_kind {
103 CompletionItemKind::Attribute => lsp_types::CompletionItemKind::EnumMember,
104 CompletionItemKind::Binding => lsp_types::CompletionItemKind::Variable,
105 CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::Struct,
106 CompletionItemKind::Keyword => lsp_types::CompletionItemKind::Keyword,
107 CompletionItemKind::Method => lsp_types::CompletionItemKind::Method,
108 CompletionItemKind::Snippet => lsp_types::CompletionItemKind::Snippet,
109 CompletionItemKind::UnresolvedReference => lsp_types::CompletionItemKind::Reference,
110 CompletionItemKind::SymbolKind(symbol) => match symbol {
111 SymbolKind::Const => lsp_types::CompletionItemKind::Constant,
112 SymbolKind::ConstParam => lsp_types::CompletionItemKind::TypeParameter,
113 SymbolKind::Enum => lsp_types::CompletionItemKind::Enum,
114 SymbolKind::Field => lsp_types::CompletionItemKind::Field,
115 SymbolKind::Function => lsp_types::CompletionItemKind::Function,
116 SymbolKind::Impl => lsp_types::CompletionItemKind::Text,
117 SymbolKind::Label => lsp_types::CompletionItemKind::Variable,
118 SymbolKind::LifetimeParam => lsp_types::CompletionItemKind::TypeParameter,
119 SymbolKind::Local => lsp_types::CompletionItemKind::Variable,
120 SymbolKind::Macro => lsp_types::CompletionItemKind::Method,
121 SymbolKind::Module => lsp_types::CompletionItemKind::Module,
122 SymbolKind::SelfParam => lsp_types::CompletionItemKind::Value,
123 SymbolKind::Static => lsp_types::CompletionItemKind::Value,
124 SymbolKind::Struct => lsp_types::CompletionItemKind::Struct,
125 SymbolKind::Trait => lsp_types::CompletionItemKind::Interface,
126 SymbolKind::TypeAlias => lsp_types::CompletionItemKind::Struct,
127 SymbolKind::TypeParam => lsp_types::CompletionItemKind::TypeParameter,
128 SymbolKind::Union => lsp_types::CompletionItemKind::Struct,
129 SymbolKind::ValueParam => lsp_types::CompletionItemKind::Value,
130 SymbolKind::Variant => lsp_types::CompletionItemKind::EnumMember,
135 pub(crate) fn text_edit(line_index: &LineIndex, indel: Indel) -> lsp_types::TextEdit {
136 let range = range(line_index, indel.delete);
137 let new_text = match line_index.endings {
138 LineEndings::Unix => indel.insert,
139 LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
141 lsp_types::TextEdit { range, new_text }
144 pub(crate) fn completion_text_edit(
145 line_index: &LineIndex,
146 insert_replace_support: Option<lsp_types::Position>,
148 ) -> lsp_types::CompletionTextEdit {
149 let text_edit = text_edit(line_index, indel);
150 match insert_replace_support {
151 Some(cursor_pos) => lsp_types::InsertReplaceEdit {
152 new_text: text_edit.new_text,
153 insert: lsp_types::Range { start: text_edit.range.start, end: cursor_pos },
154 replace: text_edit.range,
157 None => text_edit.into(),
161 pub(crate) fn snippet_text_edit(
162 line_index: &LineIndex,
165 ) -> lsp_ext::SnippetTextEdit {
166 let text_edit = text_edit(line_index, indel);
167 let insert_text_format =
168 if is_snippet { Some(lsp_types::InsertTextFormat::Snippet) } else { None };
169 lsp_ext::SnippetTextEdit {
170 range: text_edit.range,
171 new_text: text_edit.new_text,
177 pub(crate) fn text_edit_vec(
178 line_index: &LineIndex,
180 ) -> Vec<lsp_types::TextEdit> {
181 text_edit.into_iter().map(|indel| self::text_edit(line_index, indel)).collect()
184 pub(crate) fn snippet_text_edit_vec(
185 line_index: &LineIndex,
188 ) -> Vec<lsp_ext::SnippetTextEdit> {
191 .map(|indel| self::snippet_text_edit(line_index, is_snippet, indel))
195 pub(crate) fn completion_items(
197 line_index: &LineIndex,
198 tdpp: lsp_types::TextDocumentPositionParams,
199 items: Vec<CompletionItem>,
200 ) -> Vec<lsp_types::CompletionItem> {
201 let max_relevance = items.iter().map(|it| it.relevance().score()).max().unwrap_or_default();
202 let mut res = Vec::with_capacity(items.len());
204 completion_item(&mut res, config, line_index, &tdpp, max_relevance, item)
210 acc: &mut Vec<lsp_types::CompletionItem>,
212 line_index: &LineIndex,
213 tdpp: &lsp_types::TextDocumentPositionParams,
215 item: CompletionItem,
217 let mut additional_text_edits = Vec::new();
219 // LSP does not allow arbitrary edits in completion, so we have to do a
220 // non-trivial mapping here.
222 let mut text_edit = None;
223 let source_range = item.source_range();
224 for indel in item.text_edit().iter() {
225 if indel.delete.contains_range(source_range) {
226 let insert_replace_support = config.insert_replace_support().then(|| tdpp.position);
227 text_edit = Some(if indel.delete == source_range {
228 self::completion_text_edit(line_index, insert_replace_support, indel.clone())
230 assert!(source_range.end() == indel.delete.end());
231 let range1 = TextRange::new(indel.delete.start(), source_range.start());
232 let range2 = source_range;
233 let indel1 = Indel::replace(range1, String::new());
234 let indel2 = Indel::replace(range2, indel.insert.clone());
235 additional_text_edits.push(self::text_edit(line_index, indel1));
236 self::completion_text_edit(line_index, insert_replace_support, indel2)
239 assert!(source_range.intersect(indel.delete).is_none());
240 let text_edit = self::text_edit(line_index, indel.clone());
241 additional_text_edits.push(text_edit);
247 let mut lsp_item = lsp_types::CompletionItem {
248 label: item.label().to_string(),
249 detail: item.detail().map(|it| it.to_string()),
250 filter_text: Some(item.lookup().to_string()),
251 kind: item.kind().map(completion_item_kind),
252 text_edit: Some(text_edit),
253 additional_text_edits: Some(additional_text_edits),
254 documentation: item.documentation().map(documentation),
255 deprecated: Some(item.deprecated()),
259 set_score(&mut lsp_item, max_relevance, item.relevance());
261 if item.deprecated() {
262 lsp_item.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
265 if item.trigger_call_info() && config.client_commands().trigger_parameter_hints {
266 lsp_item.command = Some(command::trigger_parameter_hints());
269 if item.is_snippet() {
270 lsp_item.insert_text_format = Some(lsp_types::InsertTextFormat::Snippet);
272 if config.completion().enable_imports_on_the_fly {
273 if let imports @ [_, ..] = item.imports_to_add() {
274 let imports: Vec<_> = imports
276 .filter_map(|import_edit| {
277 let import_path = &import_edit.import.import_path;
278 let import_name = import_path.segments().last()?;
279 Some(lsp_ext::CompletionImport {
280 full_import_path: import_path.to_string(),
281 imported_name: import_name.to_string(),
285 if !imports.is_empty() {
286 let data = lsp_ext::CompletionResolveData { position: tdpp.clone(), imports };
287 lsp_item.data = Some(to_value(data).unwrap());
292 if let Some((mutability, relevance)) = item.ref_match() {
293 let mut lsp_item_with_ref = lsp_item.clone();
294 set_score(&mut lsp_item_with_ref, max_relevance, relevance);
295 lsp_item_with_ref.label =
296 format!("&{}{}", mutability.as_keyword_for_ref(), lsp_item_with_ref.label);
297 if let Some(it) = &mut lsp_item_with_ref.text_edit {
298 let new_text = match it {
299 lsp_types::CompletionTextEdit::Edit(it) => &mut it.new_text,
300 lsp_types::CompletionTextEdit::InsertAndReplace(it) => &mut it.new_text,
302 *new_text = format!("&{}{}", mutability.as_keyword_for_ref(), new_text);
305 acc.push(lsp_item_with_ref);
311 res: &mut lsp_types::CompletionItem,
313 relevance: CompletionRelevance,
315 if relevance.is_relevant() && relevance.score() == max_relevance {
316 res.preselect = Some(true);
318 // The relevance needs to be inverted to come up with a sort score
319 // because the client will sort ascending.
320 let sort_score = relevance.score() ^ 0xFF_FF_FF_FF;
321 // Zero pad the string to ensure values can be properly sorted
322 // by the client. Hex format is used because it is easier to
323 // visually compare very large values, which the sort text
324 // tends to be since it is the opposite of the score.
325 res.sort_text = Some(format!("{:08x}", sort_score));
329 pub(crate) fn signature_help(
333 ) -> lsp_types::SignatureHelp {
334 let (label, parameters) = match (concise, label_offsets) {
336 let params = call_info
338 .map(|label| lsp_types::ParameterInformation {
339 label: lsp_types::ParameterLabel::Simple(label.to_string()),
342 .collect::<Vec<_>>();
344 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
348 let params = call_info
351 .map(|it| [u32::from(it.start()), u32::from(it.end())])
352 .map(|label_offsets| lsp_types::ParameterInformation {
353 label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
356 .collect::<Vec<_>>();
357 (call_info.signature, params)
360 let mut params = Vec::new();
361 let mut label = String::new();
362 let mut first = true;
363 for param in call_info.parameter_labels() {
365 label.push_str(", ");
368 let start = label.len() as u32;
369 label.push_str(param);
370 let end = label.len() as u32;
371 params.push(lsp_types::ParameterInformation {
372 label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
381 let documentation = if concise {
384 call_info.doc.map(|doc| {
385 lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
386 kind: lsp_types::MarkupKind::Markdown,
392 let active_parameter = call_info.active_parameter.map(|it| it as u32);
394 let signature = lsp_types::SignatureInformation {
397 parameters: Some(parameters),
400 lsp_types::SignatureHelp {
401 signatures: vec![signature],
402 active_signature: Some(0),
407 pub(crate) fn inlay_hint(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
409 label: inlay_hint.label.to_string(),
410 range: range(line_index, inlay_hint.range),
411 kind: match inlay_hint.kind {
412 InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
413 InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
414 InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
419 static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
421 pub(crate) fn semantic_tokens(
423 line_index: &LineIndex,
424 highlights: Vec<HlRange>,
425 highlight_strings: bool,
426 ) -> lsp_types::SemanticTokens {
427 let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
428 let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
430 for highlight_range in highlights {
431 if highlight_range.highlight.is_empty() {
434 let (ty, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
435 if !highlight_strings && ty == lsp_types::SemanticTokenType::STRING {
438 let token_index = semantic_tokens::type_index(ty);
439 let modifier_bitset = mods.0;
441 for mut text_range in line_index.index.lines(highlight_range.range) {
442 if text[text_range].ends_with('\n') {
444 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
446 let range = range(line_index, text_range);
447 builder.push(range, token_index, modifier_bitset);
454 pub(crate) fn semantic_token_delta(
455 previous: &lsp_types::SemanticTokens,
456 current: &lsp_types::SemanticTokens,
457 ) -> lsp_types::SemanticTokensDelta {
458 let result_id = current.result_id.clone();
459 let edits = semantic_tokens::diff_tokens(&previous.data, ¤t.data);
460 lsp_types::SemanticTokensDelta { result_id, edits }
463 fn semantic_token_type_and_modifiers(
464 highlight: Highlight,
465 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
466 let mut mods = semantic_tokens::ModifierSet::default();
467 let type_ = match highlight.tag {
468 HlTag::Symbol(symbol) => match symbol {
469 SymbolKind::Module => lsp_types::SemanticTokenType::NAMESPACE,
470 SymbolKind::Impl => semantic_tokens::TYPE_ALIAS,
471 SymbolKind::Field => lsp_types::SemanticTokenType::PROPERTY,
472 SymbolKind::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
473 SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
474 SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
475 SymbolKind::Label => semantic_tokens::LABEL,
476 SymbolKind::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
477 SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
478 SymbolKind::Local => lsp_types::SemanticTokenType::VARIABLE,
479 SymbolKind::Function => {
480 if highlight.mods.contains(HlMod::Associated) {
481 lsp_types::SemanticTokenType::METHOD
483 lsp_types::SemanticTokenType::FUNCTION
486 SymbolKind::Const => {
487 mods |= semantic_tokens::CONSTANT;
488 mods |= lsp_types::SemanticTokenModifier::STATIC;
489 lsp_types::SemanticTokenType::VARIABLE
491 SymbolKind::Static => {
492 mods |= lsp_types::SemanticTokenModifier::STATIC;
493 lsp_types::SemanticTokenType::VARIABLE
495 SymbolKind::Struct => lsp_types::SemanticTokenType::STRUCT,
496 SymbolKind::Enum => lsp_types::SemanticTokenType::ENUM,
497 SymbolKind::Variant => lsp_types::SemanticTokenType::ENUM_MEMBER,
498 SymbolKind::Union => semantic_tokens::UNION,
499 SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
500 SymbolKind::Trait => lsp_types::SemanticTokenType::INTERFACE,
501 SymbolKind::Macro => lsp_types::SemanticTokenType::MACRO,
503 HlTag::Attribute => semantic_tokens::ATTRIBUTE,
504 HlTag::BoolLiteral => semantic_tokens::BOOLEAN,
505 HlTag::BuiltinAttr => semantic_tokens::BUILTIN_ATTRIBUTE,
506 HlTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
507 HlTag::ByteLiteral | HlTag::NumericLiteral => lsp_types::SemanticTokenType::NUMBER,
508 HlTag::CharLiteral => semantic_tokens::CHAR,
509 HlTag::Comment => lsp_types::SemanticTokenType::COMMENT,
510 HlTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
511 HlTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
512 HlTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
513 HlTag::None => semantic_tokens::GENERIC,
514 HlTag::Operator(op) => match op {
515 HlOperator::Bitwise => semantic_tokens::BITWISE,
516 HlOperator::Arithmetic => semantic_tokens::ARITHMETIC,
517 HlOperator::Logical => semantic_tokens::LOGICAL,
518 HlOperator::Comparison => semantic_tokens::COMPARISON,
519 HlOperator::Other => semantic_tokens::OPERATOR,
521 HlTag::StringLiteral => lsp_types::SemanticTokenType::STRING,
522 HlTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
523 HlTag::Punctuation(punct) => match punct {
524 HlPunct::Bracket => semantic_tokens::BRACKET,
525 HlPunct::Brace => semantic_tokens::BRACE,
526 HlPunct::Parenthesis => semantic_tokens::PARENTHESIS,
527 HlPunct::Angle => semantic_tokens::ANGLE,
528 HlPunct::Comma => semantic_tokens::COMMA,
529 HlPunct::Dot => semantic_tokens::DOT,
530 HlPunct::Colon => semantic_tokens::COLON,
531 HlPunct::Semi => semantic_tokens::SEMICOLON,
532 HlPunct::Other => semantic_tokens::PUNCTUATION,
536 for modifier in highlight.mods.iter() {
537 let modifier = match modifier {
538 HlMod::Associated => continue,
539 HlMod::Async => semantic_tokens::ASYNC,
540 HlMod::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
541 HlMod::Callable => semantic_tokens::CALLABLE,
542 HlMod::Consuming => semantic_tokens::CONSUMING,
543 HlMod::ControlFlow => semantic_tokens::CONTROL_FLOW,
544 HlMod::CrateRoot => semantic_tokens::CRATE_ROOT,
545 HlMod::DefaultLibrary => lsp_types::SemanticTokenModifier::DEFAULT_LIBRARY,
546 HlMod::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
547 HlMod::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
548 HlMod::Injected => semantic_tokens::INJECTED,
549 HlMod::IntraDocLink => semantic_tokens::INTRA_DOC_LINK,
550 HlMod::Library => semantic_tokens::LIBRARY,
551 HlMod::Mutable => semantic_tokens::MUTABLE,
552 HlMod::Public => semantic_tokens::PUBLIC,
553 HlMod::Reference => semantic_tokens::REFERENCE,
554 HlMod::Static => lsp_types::SemanticTokenModifier::STATIC,
555 HlMod::Trait => semantic_tokens::TRAIT_MODIFIER,
556 HlMod::Unsafe => semantic_tokens::UNSAFE,
564 pub(crate) fn folding_range(
566 line_index: &LineIndex,
567 line_folding_only: bool,
569 ) -> lsp_types::FoldingRange {
570 let kind = match fold.kind {
571 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
572 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
573 FoldKind::Region => Some(lsp_types::FoldingRangeKind::Region),
579 | FoldKind::WhereClause
580 | FoldKind::ReturnType
581 | FoldKind::Array => None,
584 let range = range(line_index, fold.range);
586 if line_folding_only {
587 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
588 // even if it contains text not in the folding range. To prevent that we exclude
589 // range.end.line from the folding region if there is more text after range.end
591 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
593 .take_while(|it| *it != '\n')
594 .any(|it| !it.is_whitespace());
596 let end_line = if has_more_text_on_end_line {
597 range.end.line.saturating_sub(1)
602 lsp_types::FoldingRange {
603 start_line: range.start.line,
604 start_character: None,
610 lsp_types::FoldingRange {
611 start_line: range.start.line,
612 start_character: Some(range.start.character),
613 end_line: range.end.line,
614 end_character: Some(range.end.character),
620 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
621 snap.file_id_to_url(file_id)
624 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
625 /// This will only happen when processing windows paths.
627 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
628 pub(crate) fn url_from_abs_path(path: &AbsPath) -> lsp_types::Url {
629 let url = lsp_types::Url::from_file_path(path).unwrap();
630 match path.as_ref().components().next() {
631 Some(path::Component::Prefix(prefix))
632 if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
634 // Need to lowercase driver letter
639 let driver_letter_range = {
640 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
644 let start = scheme.len() + ':'.len_utf8();
645 start..(start + drive_letter.len())
648 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
649 // machinery *also* canonicalizes the drive letter. So, just massage the
651 let mut url: String = url.into();
652 url[driver_letter_range].make_ascii_lowercase();
653 lsp_types::Url::parse(&url).unwrap()
656 pub(crate) fn optional_versioned_text_document_identifier(
657 snap: &GlobalStateSnapshot,
659 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
660 let url = url(snap, file_id);
661 let version = snap.url_file_version(&url);
662 lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
665 pub(crate) fn location(
666 snap: &GlobalStateSnapshot,
668 ) -> Result<lsp_types::Location> {
669 let url = url(snap, frange.file_id);
670 let line_index = snap.file_line_index(frange.file_id)?;
671 let range = range(&line_index, frange.range);
672 let loc = lsp_types::Location::new(url, range);
676 /// Perefer using `location_link`, if the client has the cap.
677 pub(crate) fn location_from_nav(
678 snap: &GlobalStateSnapshot,
679 nav: NavigationTarget,
680 ) -> Result<lsp_types::Location> {
681 let url = url(snap, nav.file_id);
682 let line_index = snap.file_line_index(nav.file_id)?;
683 let range = range(&line_index, nav.full_range);
684 let loc = lsp_types::Location::new(url, range);
688 pub(crate) fn location_link(
689 snap: &GlobalStateSnapshot,
690 src: Option<FileRange>,
691 target: NavigationTarget,
692 ) -> Result<lsp_types::LocationLink> {
693 let origin_selection_range = match src {
695 let line_index = snap.file_line_index(src.file_id)?;
696 let range = range(&line_index, src.range);
701 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
702 let res = lsp_types::LocationLink {
703 origin_selection_range,
706 target_selection_range,
712 snap: &GlobalStateSnapshot,
713 target: NavigationTarget,
714 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
715 let line_index = snap.file_line_index(target.file_id)?;
717 let target_uri = url(snap, target.file_id);
718 let target_range = range(&line_index, target.full_range);
719 let target_selection_range =
720 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
721 Ok((target_uri, target_range, target_selection_range))
724 pub(crate) fn goto_definition_response(
725 snap: &GlobalStateSnapshot,
726 src: Option<FileRange>,
727 targets: Vec<NavigationTarget>,
728 ) -> Result<lsp_types::GotoDefinitionResponse> {
729 if snap.config.location_link() {
732 .map(|nav| location_link(snap, src, nav))
733 .collect::<Result<Vec<_>>>()?;
736 let locations = targets
739 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
741 .collect::<Result<Vec<_>>>()?;
746 fn outside_workspace_annotation_id() -> String {
747 String::from("OutsideWorkspace")
750 pub(crate) fn snippet_text_document_edit(
751 snap: &GlobalStateSnapshot,
755 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
756 let text_document = optional_versioned_text_document_identifier(snap, file_id);
757 let line_index = snap.file_line_index(file_id)?;
758 let mut edits: Vec<_> =
759 edit.into_iter().map(|it| snippet_text_edit(&line_index, is_snippet, it)).collect();
761 if snap.analysis.is_library_file(file_id)? && snap.config.change_annotation_support() {
762 for edit in &mut edits {
763 edit.annotation_id = Some(outside_workspace_annotation_id())
766 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
769 pub(crate) fn snippet_text_document_ops(
770 snap: &GlobalStateSnapshot,
771 file_system_edit: FileSystemEdit,
772 ) -> Cancellable<Vec<lsp_ext::SnippetDocumentChangeOperation>> {
773 let mut ops = Vec::new();
774 match file_system_edit {
775 FileSystemEdit::CreateFile { dst, initial_contents } => {
776 let uri = snap.anchored_path(&dst);
777 let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
782 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
783 if !initial_contents.is_empty() {
785 lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
786 let text_edit = lsp_ext::SnippetTextEdit {
787 range: lsp_types::Range::default(),
788 new_text: initial_contents,
789 insert_text_format: Some(lsp_types::InsertTextFormat::PlainText),
793 lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
794 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
797 FileSystemEdit::MoveFile { src, dst } => {
798 let old_uri = snap.file_id_to_url(src);
799 let new_uri = snap.anchored_path(&dst);
800 let mut rename_file =
801 lsp_types::RenameFile { old_uri, new_uri, options: None, annotation_id: None };
802 if snap.analysis.is_library_file(src).ok() == Some(true)
803 && snap.config.change_annotation_support()
805 rename_file.annotation_id = Some(outside_workspace_annotation_id())
807 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(lsp_types::ResourceOp::Rename(
815 pub(crate) fn snippet_workspace_edit(
816 snap: &GlobalStateSnapshot,
817 source_change: SourceChange,
818 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
819 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
821 for op in source_change.file_system_edits {
822 let ops = snippet_text_document_ops(snap, op)?;
823 document_changes.extend_from_slice(&ops);
825 for (file_id, edit) in source_change.source_file_edits {
826 let edit = snippet_text_document_edit(snap, source_change.is_snippet, file_id, edit)?;
827 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
829 let mut workspace_edit = lsp_ext::SnippetWorkspaceEdit {
831 document_changes: Some(document_changes),
832 change_annotations: None,
834 if snap.config.change_annotation_support() {
835 workspace_edit.change_annotations = Some(
837 outside_workspace_annotation_id(),
838 lsp_types::ChangeAnnotation {
839 label: String::from("Edit outside of the workspace"),
840 needs_confirmation: Some(true),
841 description: Some(String::from(
842 "This edit lies outside of the workspace and may affect dependencies",
852 pub(crate) fn workspace_edit(
853 snap: &GlobalStateSnapshot,
854 source_change: SourceChange,
855 ) -> Result<lsp_types::WorkspaceEdit> {
856 assert!(!source_change.is_snippet);
857 snippet_workspace_edit(snap, source_change).map(|it| it.into())
860 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
861 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
862 lsp_types::WorkspaceEdit {
864 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
865 lsp_types::DocumentChanges::Operations(
868 .map(|change| match change {
869 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
870 lsp_types::DocumentChangeOperation::Op(op)
872 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
873 lsp_types::DocumentChangeOperation::Edit(
874 lsp_types::TextDocumentEdit {
875 text_document: edit.text_document,
876 edits: edit.edits.into_iter().map(From::from).collect(),
884 change_annotations: snippet_workspace_edit.change_annotations,
889 impl From<lsp_ext::SnippetTextEdit>
890 for lsp_types::OneOf<lsp_types::TextEdit, lsp_types::AnnotatedTextEdit>
893 lsp_ext::SnippetTextEdit { annotation_id, insert_text_format:_, new_text, range }: lsp_ext::SnippetTextEdit,
895 match annotation_id {
896 Some(annotation_id) => lsp_types::OneOf::Right(lsp_types::AnnotatedTextEdit {
897 text_edit: lsp_types::TextEdit { range, new_text },
900 None => lsp_types::OneOf::Left(lsp_types::TextEdit { range, new_text }),
905 pub(crate) fn call_hierarchy_item(
906 snap: &GlobalStateSnapshot,
907 target: NavigationTarget,
908 ) -> Result<lsp_types::CallHierarchyItem> {
909 let name = target.name.to_string();
910 let detail = target.description.clone();
911 let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::Function);
912 let (uri, range, selection_range) = location_info(snap, target)?;
913 Ok(lsp_types::CallHierarchyItem {
925 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
927 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
928 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
929 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
930 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
931 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
932 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
936 pub(crate) fn code_action(
937 snap: &GlobalStateSnapshot,
939 resolve_data: Option<(usize, lsp_types::CodeActionParams)>,
940 ) -> Result<lsp_ext::CodeAction> {
941 let mut res = lsp_ext::CodeAction {
942 title: assist.label.to_string(),
943 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
944 kind: Some(code_action_kind(assist.id.1)),
949 match (assist.source_change, resolve_data) {
950 (Some(it), _) => res.edit = Some(snippet_workspace_edit(snap, it)?),
951 (None, Some((index, code_action_params))) => {
952 res.data = Some(lsp_ext::CodeActionData {
953 id: format!("{}:{}:{}", assist.id.0, assist.id.1.name(), index),
958 stdx::never!("assist should always be resolved if client can't do lazy resolving")
964 pub(crate) fn runnable(
965 snap: &GlobalStateSnapshot,
967 ) -> Result<lsp_ext::Runnable> {
968 let config = snap.config.runnables();
969 let spec = CargoTargetSpec::for_file(snap, runnable.nav.file_id)?;
970 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
971 let target = spec.as_ref().map(|s| s.target.clone());
972 let (cargo_args, executable_args) =
973 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
974 let label = runnable.label(target);
975 let location = location_link(snap, None, runnable.nav)?;
977 Ok(lsp_ext::Runnable {
979 location: Some(location),
980 kind: lsp_ext::RunnableKind::Cargo,
981 args: lsp_ext::CargoRunnable {
982 workspace_root: workspace_root.map(|it| it.into()),
983 override_cargo: config.override_cargo,
985 cargo_extra_args: config.cargo_extra_args,
992 pub(crate) fn code_lens(
993 acc: &mut Vec<lsp_types::CodeLens>,
994 snap: &GlobalStateSnapshot,
995 annotation: Annotation,
997 let client_commands_config = snap.config.client_commands();
998 match annotation.kind {
999 AnnotationKind::Runnable(run) => {
1000 let line_index = snap.file_line_index(run.nav.file_id)?;
1001 let annotation_range = range(&line_index, annotation.range);
1003 let title = run.title();
1004 let can_debug = match run.kind {
1005 ide::RunnableKind::DocTest { .. } => false,
1006 ide::RunnableKind::TestMod { .. }
1007 | ide::RunnableKind::Test { .. }
1008 | ide::RunnableKind::Bench { .. }
1009 | ide::RunnableKind::Bin => true,
1011 let r = runnable(snap, run)?;
1013 let lens_config = snap.config.lens();
1014 if lens_config.run && client_commands_config.run_single {
1015 let command = command::run_single(&r, &title);
1016 acc.push(lsp_types::CodeLens {
1017 range: annotation_range,
1018 command: Some(command),
1022 if lens_config.debug && can_debug && client_commands_config.debug_single {
1023 let command = command::debug_single(&r);
1024 acc.push(lsp_types::CodeLens {
1025 range: annotation_range,
1026 command: Some(command),
1031 AnnotationKind::HasImpls { position: file_position, data } => {
1032 if !client_commands_config.show_reference {
1035 let line_index = snap.file_line_index(file_position.file_id)?;
1036 let annotation_range = range(&line_index, annotation.range);
1037 let url = url(snap, file_position.file_id);
1039 let position = position(&line_index, file_position.offset);
1041 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1043 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
1045 let goto_params = lsp_types::request::GotoImplementationParams {
1046 text_document_position_params: doc_pos,
1047 work_done_progress_params: Default::default(),
1048 partial_result_params: Default::default(),
1051 let command = data.map(|ranges| {
1052 let locations: Vec<lsp_types::Location> = ranges
1054 .filter_map(|target| {
1057 FileRange { file_id: target.file_id, range: target.full_range },
1063 command::show_references(
1064 implementation_title(locations.len()),
1071 acc.push(lsp_types::CodeLens {
1072 range: annotation_range,
1074 data: Some(to_value(lsp_ext::CodeLensResolveData::Impls(goto_params)).unwrap()),
1077 AnnotationKind::HasReferences { position: file_position, data } => {
1078 if !client_commands_config.show_reference {
1081 let line_index = snap.file_line_index(file_position.file_id)?;
1082 let annotation_range = range(&line_index, annotation.range);
1083 let url = url(snap, file_position.file_id);
1085 let position = position(&line_index, file_position.offset);
1087 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1089 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
1091 let command = data.map(|ranges| {
1092 let locations: Vec<lsp_types::Location> =
1093 ranges.into_iter().filter_map(|range| location(snap, range).ok()).collect();
1095 command::show_references(
1096 reference_title(locations.len()),
1103 acc.push(lsp_types::CodeLens {
1104 range: annotation_range,
1106 data: Some(to_value(lsp_ext::CodeLensResolveData::References(doc_pos)).unwrap()),
1113 pub(crate) mod command {
1114 use ide::{FileRange, NavigationTarget};
1115 use serde_json::to_value;
1118 global_state::GlobalStateSnapshot,
1120 to_proto::{location, location_link},
1123 pub(crate) fn show_references(
1125 uri: &lsp_types::Url,
1126 position: lsp_types::Position,
1127 locations: Vec<lsp_types::Location>,
1128 ) -> lsp_types::Command {
1129 // We cannot use the 'editor.action.showReferences' command directly
1130 // because that command requires vscode types which we convert in the handler
1131 // on the client side.
1133 lsp_types::Command {
1135 command: "rust-analyzer.showReferences".into(),
1136 arguments: Some(vec![
1137 to_value(uri).unwrap(),
1138 to_value(position).unwrap(),
1139 to_value(locations).unwrap(),
1144 pub(crate) fn run_single(runnable: &lsp_ext::Runnable, title: &str) -> lsp_types::Command {
1145 lsp_types::Command {
1146 title: title.to_string(),
1147 command: "rust-analyzer.runSingle".into(),
1148 arguments: Some(vec![to_value(runnable).unwrap()]),
1152 pub(crate) fn debug_single(runnable: &lsp_ext::Runnable) -> lsp_types::Command {
1153 lsp_types::Command {
1154 title: "Debug".into(),
1155 command: "rust-analyzer.debugSingle".into(),
1156 arguments: Some(vec![to_value(runnable).unwrap()]),
1160 pub(crate) fn goto_location(
1161 snap: &GlobalStateSnapshot,
1162 nav: &NavigationTarget,
1163 ) -> Option<lsp_types::Command> {
1164 let value = if snap.config.location_link() {
1165 let link = location_link(snap, None, nav.clone()).ok()?;
1166 to_value(link).ok()?
1168 let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1169 let location = location(snap, range).ok()?;
1170 to_value(location).ok()?
1173 Some(lsp_types::Command {
1174 title: nav.name.to_string(),
1175 command: "rust-analyzer.gotoLocation".into(),
1176 arguments: Some(vec![value]),
1180 pub(crate) fn trigger_parameter_hints() -> lsp_types::Command {
1181 lsp_types::Command {
1182 title: "triggerParameterHints".into(),
1183 command: "editor.action.triggerParameterHints".into(),
1189 pub(crate) fn implementation_title(count: usize) -> String {
1191 "1 implementation".into()
1193 format!("{} implementations", count)
1197 pub(crate) fn reference_title(count: usize) -> String {
1199 "1 reference".into()
1201 format!("{} references", count)
1205 pub(crate) fn markup_content(markup: Markup) -> lsp_types::MarkupContent {
1206 let value = crate::markdown::format_docs(markup.as_str());
1207 lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value }
1210 pub(crate) fn rename_error(err: RenameError) -> crate::LspError {
1211 // This is wrong, but we don't have a better alternative I suppose?
1212 // https://github.com/microsoft/language-server-protocol/issues/1341
1213 invalid_params_error(err.to_string())
1225 fn conv_fold_line_folding_only_fixup() {
1226 let text = r#"mod a;
1238 let (analysis, file_id) = Analysis::from_single_file(text.to_string());
1239 let folds = analysis.folding_ranges(file_id).unwrap();
1240 assert_eq!(folds.len(), 4);
1242 let line_index = LineIndex {
1243 index: Arc::new(ide::LineIndex::new(text)),
1244 endings: LineEndings::Unix,
1245 encoding: OffsetEncoding::Utf16,
1247 let converted: Vec<lsp_types::FoldingRange> =
1248 folds.into_iter().map(|it| folding_range(text, &line_index, true, it)).collect();
1250 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
1251 assert_eq!(converted.len(), expected_lines.len());
1252 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
1253 assert_eq!(folding_range.start_line, *start_line);
1254 assert_eq!(folding_range.start_character, None);
1255 assert_eq!(folding_range.end_line, *end_line);
1256 assert_eq!(folding_range.end_character, None);
1260 // `Url` is not able to parse windows paths on unix machines.
1262 #[cfg(target_os = "windows")]
1263 fn test_lowercase_drive_letter() {
1264 use std::{convert::TryInto, path::Path};
1266 let url = url_from_abs_path(Path::new("C:\\Test").try_into().unwrap());
1267 assert_eq!(url.to_string(), "file:///c:/Test");
1269 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#).try_into().unwrap());
1270 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");