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::ENUM_MEMBER,
52 SymbolKind::Trait => lsp_types::SymbolKind::INTERFACE,
53 SymbolKind::Macro | SymbolKind::BuiltinAttr => lsp_types::SymbolKind::FUNCTION,
54 SymbolKind::Module | SymbolKind::ToolModule => lsp_types::SymbolKind::MODULE,
55 SymbolKind::TypeAlias | SymbolKind::TypeParam => lsp_types::SymbolKind::TYPE_PARAMETER,
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::ENUM_MEMBER,
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::TYPE_PARAMETER,
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::TYPE_PARAMETER,
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::TYPE_PARAMETER,
128 SymbolKind::Union => lsp_types::CompletionItemKind::STRUCT,
129 SymbolKind::ValueParam => lsp_types::CompletionItemKind::VALUE,
130 SymbolKind::Variant => lsp_types::CompletionItemKind::ENUM_MEMBER,
131 SymbolKind::BuiltinAttr => lsp_types::CompletionItemKind::FUNCTION,
132 SymbolKind::ToolModule => lsp_types::CompletionItemKind::MODULE,
137 pub(crate) fn text_edit(line_index: &LineIndex, indel: Indel) -> lsp_types::TextEdit {
138 let range = range(line_index, indel.delete);
139 let new_text = match line_index.endings {
140 LineEndings::Unix => indel.insert,
141 LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
143 lsp_types::TextEdit { range, new_text }
146 pub(crate) fn completion_text_edit(
147 line_index: &LineIndex,
148 insert_replace_support: Option<lsp_types::Position>,
150 ) -> lsp_types::CompletionTextEdit {
151 let text_edit = text_edit(line_index, indel);
152 match insert_replace_support {
153 Some(cursor_pos) => lsp_types::InsertReplaceEdit {
154 new_text: text_edit.new_text,
155 insert: lsp_types::Range { start: text_edit.range.start, end: cursor_pos },
156 replace: text_edit.range,
159 None => text_edit.into(),
163 pub(crate) fn snippet_text_edit(
164 line_index: &LineIndex,
167 ) -> lsp_ext::SnippetTextEdit {
168 let text_edit = text_edit(line_index, indel);
169 let insert_text_format =
170 if is_snippet { Some(lsp_types::InsertTextFormat::SNIPPET) } else { None };
171 lsp_ext::SnippetTextEdit {
172 range: text_edit.range,
173 new_text: text_edit.new_text,
179 pub(crate) fn text_edit_vec(
180 line_index: &LineIndex,
182 ) -> Vec<lsp_types::TextEdit> {
183 text_edit.into_iter().map(|indel| self::text_edit(line_index, indel)).collect()
186 pub(crate) fn snippet_text_edit_vec(
187 line_index: &LineIndex,
190 ) -> Vec<lsp_ext::SnippetTextEdit> {
193 .map(|indel| self::snippet_text_edit(line_index, is_snippet, indel))
197 pub(crate) fn completion_items(
199 line_index: &LineIndex,
200 tdpp: lsp_types::TextDocumentPositionParams,
201 items: Vec<CompletionItem>,
202 ) -> Vec<lsp_types::CompletionItem> {
203 let max_relevance = items.iter().map(|it| it.relevance().score()).max().unwrap_or_default();
204 let mut res = Vec::with_capacity(items.len());
206 completion_item(&mut res, config, line_index, &tdpp, max_relevance, item)
212 acc: &mut Vec<lsp_types::CompletionItem>,
214 line_index: &LineIndex,
215 tdpp: &lsp_types::TextDocumentPositionParams,
217 item: CompletionItem,
219 let mut additional_text_edits = Vec::new();
221 // LSP does not allow arbitrary edits in completion, so we have to do a
222 // non-trivial mapping here.
224 let mut text_edit = None;
225 let source_range = item.source_range();
226 for indel in item.text_edit().iter() {
227 if indel.delete.contains_range(source_range) {
228 let insert_replace_support = config.insert_replace_support().then(|| tdpp.position);
229 text_edit = Some(if indel.delete == source_range {
230 self::completion_text_edit(line_index, insert_replace_support, indel.clone())
232 assert!(source_range.end() == indel.delete.end());
233 let range1 = TextRange::new(indel.delete.start(), source_range.start());
234 let range2 = source_range;
235 let indel1 = Indel::replace(range1, String::new());
236 let indel2 = Indel::replace(range2, indel.insert.clone());
237 additional_text_edits.push(self::text_edit(line_index, indel1));
238 self::completion_text_edit(line_index, insert_replace_support, indel2)
241 assert!(source_range.intersect(indel.delete).is_none());
242 let text_edit = self::text_edit(line_index, indel.clone());
243 additional_text_edits.push(text_edit);
249 let mut lsp_item = lsp_types::CompletionItem {
250 label: item.label().to_string(),
251 detail: item.detail().map(|it| it.to_string()),
252 filter_text: Some(item.lookup().to_string()),
253 kind: Some(completion_item_kind(item.kind())),
254 text_edit: Some(text_edit),
255 additional_text_edits: Some(additional_text_edits),
256 documentation: item.documentation().map(documentation),
257 deprecated: Some(item.deprecated()),
261 set_score(&mut lsp_item, max_relevance, item.relevance());
263 if item.deprecated() {
264 lsp_item.tags = Some(vec![lsp_types::CompletionItemTag::DEPRECATED])
267 if item.trigger_call_info() && config.client_commands().trigger_parameter_hints {
268 lsp_item.command = Some(command::trigger_parameter_hints());
271 if item.is_snippet() {
272 lsp_item.insert_text_format = Some(lsp_types::InsertTextFormat::SNIPPET);
274 if config.completion().enable_imports_on_the_fly {
275 if let imports @ [_, ..] = item.imports_to_add() {
276 let imports: Vec<_> = imports
278 .filter_map(|import_edit| {
279 let import_path = &import_edit.import.import_path;
280 let import_name = import_path.segments().last()?;
281 Some(lsp_ext::CompletionImport {
282 full_import_path: import_path.to_string(),
283 imported_name: import_name.to_string(),
287 if !imports.is_empty() {
288 let data = lsp_ext::CompletionResolveData { position: tdpp.clone(), imports };
289 lsp_item.data = Some(to_value(data).unwrap());
294 if let Some((mutability, relevance)) = item.ref_match() {
295 let mut lsp_item_with_ref = lsp_item.clone();
296 set_score(&mut lsp_item_with_ref, max_relevance, relevance);
297 lsp_item_with_ref.label =
298 format!("&{}{}", mutability.as_keyword_for_ref(), lsp_item_with_ref.label);
299 if let Some(it) = &mut lsp_item_with_ref.text_edit {
300 let new_text = match it {
301 lsp_types::CompletionTextEdit::Edit(it) => &mut it.new_text,
302 lsp_types::CompletionTextEdit::InsertAndReplace(it) => &mut it.new_text,
304 *new_text = format!("&{}{}", mutability.as_keyword_for_ref(), new_text);
307 acc.push(lsp_item_with_ref);
313 res: &mut lsp_types::CompletionItem,
315 relevance: CompletionRelevance,
317 if relevance.is_relevant() && relevance.score() == max_relevance {
318 res.preselect = Some(true);
320 // The relevance needs to be inverted to come up with a sort score
321 // because the client will sort ascending.
322 let sort_score = relevance.score() ^ 0xFF_FF_FF_FF;
323 // Zero pad the string to ensure values can be properly sorted
324 // by the client. Hex format is used because it is easier to
325 // visually compare very large values, which the sort text
326 // tends to be since it is the opposite of the score.
327 res.sort_text = Some(format!("{:08x}", sort_score));
331 pub(crate) fn signature_help(
335 ) -> lsp_types::SignatureHelp {
336 let (label, parameters) = match (concise, label_offsets) {
338 let params = call_info
340 .map(|label| lsp_types::ParameterInformation {
341 label: lsp_types::ParameterLabel::Simple(label.to_string()),
344 .collect::<Vec<_>>();
346 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
350 let params = call_info
353 .map(|it| [u32::from(it.start()), u32::from(it.end())])
354 .map(|label_offsets| lsp_types::ParameterInformation {
355 label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
358 .collect::<Vec<_>>();
359 (call_info.signature, params)
362 let mut params = Vec::new();
363 let mut label = String::new();
364 let mut first = true;
365 for param in call_info.parameter_labels() {
367 label.push_str(", ");
370 let start = label.len() as u32;
371 label.push_str(param);
372 let end = label.len() as u32;
373 params.push(lsp_types::ParameterInformation {
374 label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
383 let documentation = if concise {
386 call_info.doc.map(|doc| {
387 lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
388 kind: lsp_types::MarkupKind::Markdown,
394 let active_parameter = call_info.active_parameter.map(|it| it as u32);
396 let signature = lsp_types::SignatureInformation {
399 parameters: Some(parameters),
402 lsp_types::SignatureHelp {
403 signatures: vec![signature],
404 active_signature: Some(0),
409 pub(crate) fn inlay_hint(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
411 label: inlay_hint.label.to_string(),
412 range: range(line_index, inlay_hint.range),
413 kind: match inlay_hint.kind {
414 InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
415 InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
416 InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
421 static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
423 pub(crate) fn semantic_tokens(
425 line_index: &LineIndex,
426 highlights: Vec<HlRange>,
427 highlight_strings: bool,
428 ) -> lsp_types::SemanticTokens {
429 let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
430 let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
432 for highlight_range in highlights {
433 if highlight_range.highlight.is_empty() {
436 let (ty, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
437 if !highlight_strings && ty == lsp_types::SemanticTokenType::STRING {
440 let token_index = semantic_tokens::type_index(ty);
441 let modifier_bitset = mods.0;
443 for mut text_range in line_index.index.lines(highlight_range.range) {
444 if text[text_range].ends_with('\n') {
446 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
448 let range = range(line_index, text_range);
449 builder.push(range, token_index, modifier_bitset);
456 pub(crate) fn semantic_token_delta(
457 previous: &lsp_types::SemanticTokens,
458 current: &lsp_types::SemanticTokens,
459 ) -> lsp_types::SemanticTokensDelta {
460 let result_id = current.result_id.clone();
461 let edits = semantic_tokens::diff_tokens(&previous.data, ¤t.data);
462 lsp_types::SemanticTokensDelta { result_id, edits }
465 fn semantic_token_type_and_modifiers(
466 highlight: Highlight,
467 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
468 let mut mods = semantic_tokens::ModifierSet::default();
469 let type_ = match highlight.tag {
470 HlTag::Symbol(symbol) => match symbol {
471 SymbolKind::Module => lsp_types::SemanticTokenType::NAMESPACE,
472 SymbolKind::Impl => semantic_tokens::TYPE_ALIAS,
473 SymbolKind::Field => lsp_types::SemanticTokenType::PROPERTY,
474 SymbolKind::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
475 SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
476 SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
477 SymbolKind::Label => semantic_tokens::LABEL,
478 SymbolKind::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
479 SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
480 SymbolKind::Local => lsp_types::SemanticTokenType::VARIABLE,
481 SymbolKind::Function => {
482 if highlight.mods.contains(HlMod::Associated) {
483 lsp_types::SemanticTokenType::METHOD
485 lsp_types::SemanticTokenType::FUNCTION
488 SymbolKind::Const => {
489 mods |= semantic_tokens::CONSTANT;
490 mods |= lsp_types::SemanticTokenModifier::STATIC;
491 lsp_types::SemanticTokenType::VARIABLE
493 SymbolKind::Static => {
494 mods |= lsp_types::SemanticTokenModifier::STATIC;
495 lsp_types::SemanticTokenType::VARIABLE
497 SymbolKind::Struct => lsp_types::SemanticTokenType::STRUCT,
498 SymbolKind::Enum => lsp_types::SemanticTokenType::ENUM,
499 SymbolKind::Variant => lsp_types::SemanticTokenType::ENUM_MEMBER,
500 SymbolKind::Union => semantic_tokens::UNION,
501 SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
502 SymbolKind::Trait => lsp_types::SemanticTokenType::INTERFACE,
503 SymbolKind::Macro => lsp_types::SemanticTokenType::MACRO,
504 SymbolKind::BuiltinAttr => semantic_tokens::BUILTIN_ATTRIBUTE,
505 SymbolKind::ToolModule => semantic_tokens::TOOL_MODULE,
507 HlTag::Attribute => semantic_tokens::ATTRIBUTE,
508 HlTag::BoolLiteral => semantic_tokens::BOOLEAN,
509 HlTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
510 HlTag::ByteLiteral | HlTag::NumericLiteral => lsp_types::SemanticTokenType::NUMBER,
511 HlTag::CharLiteral => semantic_tokens::CHAR,
512 HlTag::Comment => lsp_types::SemanticTokenType::COMMENT,
513 HlTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
514 HlTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
515 HlTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
516 HlTag::None => semantic_tokens::GENERIC,
517 HlTag::Operator(op) => match op {
518 HlOperator::Bitwise => semantic_tokens::BITWISE,
519 HlOperator::Arithmetic => semantic_tokens::ARITHMETIC,
520 HlOperator::Logical => semantic_tokens::LOGICAL,
521 HlOperator::Comparison => semantic_tokens::COMPARISON,
522 HlOperator::Other => semantic_tokens::OPERATOR,
524 HlTag::StringLiteral => lsp_types::SemanticTokenType::STRING,
525 HlTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
526 HlTag::Punctuation(punct) => match punct {
527 HlPunct::Bracket => semantic_tokens::BRACKET,
528 HlPunct::Brace => semantic_tokens::BRACE,
529 HlPunct::Parenthesis => semantic_tokens::PARENTHESIS,
530 HlPunct::Angle => semantic_tokens::ANGLE,
531 HlPunct::Comma => semantic_tokens::COMMA,
532 HlPunct::Dot => semantic_tokens::DOT,
533 HlPunct::Colon => semantic_tokens::COLON,
534 HlPunct::Semi => semantic_tokens::SEMICOLON,
535 HlPunct::Other => semantic_tokens::PUNCTUATION,
539 for modifier in highlight.mods.iter() {
540 let modifier = match modifier {
541 HlMod::Associated => continue,
542 HlMod::Async => semantic_tokens::ASYNC,
543 HlMod::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
544 HlMod::Callable => semantic_tokens::CALLABLE,
545 HlMod::Consuming => semantic_tokens::CONSUMING,
546 HlMod::ControlFlow => semantic_tokens::CONTROL_FLOW,
547 HlMod::CrateRoot => semantic_tokens::CRATE_ROOT,
548 HlMod::DefaultLibrary => lsp_types::SemanticTokenModifier::DEFAULT_LIBRARY,
549 HlMod::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
550 HlMod::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
551 HlMod::Injected => semantic_tokens::INJECTED,
552 HlMod::IntraDocLink => semantic_tokens::INTRA_DOC_LINK,
553 HlMod::Library => semantic_tokens::LIBRARY,
554 HlMod::Mutable => semantic_tokens::MUTABLE,
555 HlMod::Public => semantic_tokens::PUBLIC,
556 HlMod::Reference => semantic_tokens::REFERENCE,
557 HlMod::Static => lsp_types::SemanticTokenModifier::STATIC,
558 HlMod::Trait => semantic_tokens::TRAIT_MODIFIER,
559 HlMod::Unsafe => semantic_tokens::UNSAFE,
567 pub(crate) fn folding_range(
569 line_index: &LineIndex,
570 line_folding_only: bool,
572 ) -> lsp_types::FoldingRange {
573 let kind = match fold.kind {
574 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
575 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
576 FoldKind::Region => Some(lsp_types::FoldingRangeKind::Region),
582 | FoldKind::WhereClause
583 | FoldKind::ReturnType
584 | FoldKind::Array => None,
587 let range = range(line_index, fold.range);
589 if line_folding_only {
590 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
591 // even if it contains text not in the folding range. To prevent that we exclude
592 // range.end.line from the folding region if there is more text after range.end
594 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
596 .take_while(|it| *it != '\n')
597 .any(|it| !it.is_whitespace());
599 let end_line = if has_more_text_on_end_line {
600 range.end.line.saturating_sub(1)
605 lsp_types::FoldingRange {
606 start_line: range.start.line,
607 start_character: None,
613 lsp_types::FoldingRange {
614 start_line: range.start.line,
615 start_character: Some(range.start.character),
616 end_line: range.end.line,
617 end_character: Some(range.end.character),
623 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
624 snap.file_id_to_url(file_id)
627 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
628 /// This will only happen when processing windows paths.
630 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
631 pub(crate) fn url_from_abs_path(path: &AbsPath) -> lsp_types::Url {
632 let url = lsp_types::Url::from_file_path(path).unwrap();
633 match path.as_ref().components().next() {
634 Some(path::Component::Prefix(prefix))
635 if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
637 // Need to lowercase driver letter
642 let driver_letter_range = {
643 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
647 let start = scheme.len() + ':'.len_utf8();
648 start..(start + drive_letter.len())
651 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
652 // machinery *also* canonicalizes the drive letter. So, just massage the
654 let mut url: String = url.into();
655 url[driver_letter_range].make_ascii_lowercase();
656 lsp_types::Url::parse(&url).unwrap()
659 pub(crate) fn optional_versioned_text_document_identifier(
660 snap: &GlobalStateSnapshot,
662 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
663 let url = url(snap, file_id);
664 let version = snap.url_file_version(&url);
665 lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
668 pub(crate) fn location(
669 snap: &GlobalStateSnapshot,
671 ) -> Result<lsp_types::Location> {
672 let url = url(snap, frange.file_id);
673 let line_index = snap.file_line_index(frange.file_id)?;
674 let range = range(&line_index, frange.range);
675 let loc = lsp_types::Location::new(url, range);
679 /// Prefer using `location_link`, if the client has the cap.
680 pub(crate) fn location_from_nav(
681 snap: &GlobalStateSnapshot,
682 nav: NavigationTarget,
683 ) -> Result<lsp_types::Location> {
684 let url = url(snap, nav.file_id);
685 let line_index = snap.file_line_index(nav.file_id)?;
686 let range = range(&line_index, nav.full_range);
687 let loc = lsp_types::Location::new(url, range);
691 pub(crate) fn location_link(
692 snap: &GlobalStateSnapshot,
693 src: Option<FileRange>,
694 target: NavigationTarget,
695 ) -> Result<lsp_types::LocationLink> {
696 let origin_selection_range = match src {
698 let line_index = snap.file_line_index(src.file_id)?;
699 let range = range(&line_index, src.range);
704 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
705 let res = lsp_types::LocationLink {
706 origin_selection_range,
709 target_selection_range,
715 snap: &GlobalStateSnapshot,
716 target: NavigationTarget,
717 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
718 let line_index = snap.file_line_index(target.file_id)?;
720 let target_uri = url(snap, target.file_id);
721 let target_range = range(&line_index, target.full_range);
722 let target_selection_range =
723 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
724 Ok((target_uri, target_range, target_selection_range))
727 pub(crate) fn goto_definition_response(
728 snap: &GlobalStateSnapshot,
729 src: Option<FileRange>,
730 targets: Vec<NavigationTarget>,
731 ) -> Result<lsp_types::GotoDefinitionResponse> {
732 if snap.config.location_link() {
735 .map(|nav| location_link(snap, src, nav))
736 .collect::<Result<Vec<_>>>()?;
739 let locations = targets
742 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
744 .collect::<Result<Vec<_>>>()?;
749 fn outside_workspace_annotation_id() -> String {
750 String::from("OutsideWorkspace")
753 pub(crate) fn snippet_text_document_edit(
754 snap: &GlobalStateSnapshot,
758 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
759 let text_document = optional_versioned_text_document_identifier(snap, file_id);
760 let line_index = snap.file_line_index(file_id)?;
761 let mut edits: Vec<_> =
762 edit.into_iter().map(|it| snippet_text_edit(&line_index, is_snippet, it)).collect();
764 if snap.analysis.is_library_file(file_id)? && snap.config.change_annotation_support() {
765 for edit in &mut edits {
766 edit.annotation_id = Some(outside_workspace_annotation_id())
769 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
772 pub(crate) fn snippet_text_document_ops(
773 snap: &GlobalStateSnapshot,
774 file_system_edit: FileSystemEdit,
775 ) -> Cancellable<Vec<lsp_ext::SnippetDocumentChangeOperation>> {
776 let mut ops = Vec::new();
777 match file_system_edit {
778 FileSystemEdit::CreateFile { dst, initial_contents } => {
779 let uri = snap.anchored_path(&dst);
780 let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
785 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
786 if !initial_contents.is_empty() {
788 lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
789 let text_edit = lsp_ext::SnippetTextEdit {
790 range: lsp_types::Range::default(),
791 new_text: initial_contents,
792 insert_text_format: Some(lsp_types::InsertTextFormat::PLAIN_TEXT),
796 lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
797 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
800 FileSystemEdit::MoveFile { src, dst } => {
801 let old_uri = snap.file_id_to_url(src);
802 let new_uri = snap.anchored_path(&dst);
803 let mut rename_file =
804 lsp_types::RenameFile { old_uri, new_uri, options: None, annotation_id: None };
805 if snap.analysis.is_library_file(src).ok() == Some(true)
806 && snap.config.change_annotation_support()
808 rename_file.annotation_id = Some(outside_workspace_annotation_id())
810 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(lsp_types::ResourceOp::Rename(
818 pub(crate) fn snippet_workspace_edit(
819 snap: &GlobalStateSnapshot,
820 source_change: SourceChange,
821 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
822 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
824 for op in source_change.file_system_edits {
825 let ops = snippet_text_document_ops(snap, op)?;
826 document_changes.extend_from_slice(&ops);
828 for (file_id, edit) in source_change.source_file_edits {
829 let edit = snippet_text_document_edit(snap, source_change.is_snippet, file_id, edit)?;
830 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
832 let mut workspace_edit = lsp_ext::SnippetWorkspaceEdit {
834 document_changes: Some(document_changes),
835 change_annotations: None,
837 if snap.config.change_annotation_support() {
838 workspace_edit.change_annotations = Some(
840 outside_workspace_annotation_id(),
841 lsp_types::ChangeAnnotation {
842 label: String::from("Edit outside of the workspace"),
843 needs_confirmation: Some(true),
844 description: Some(String::from(
845 "This edit lies outside of the workspace and may affect dependencies",
855 pub(crate) fn workspace_edit(
856 snap: &GlobalStateSnapshot,
857 source_change: SourceChange,
858 ) -> Result<lsp_types::WorkspaceEdit> {
859 assert!(!source_change.is_snippet);
860 snippet_workspace_edit(snap, source_change).map(|it| it.into())
863 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
864 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
865 lsp_types::WorkspaceEdit {
867 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
868 lsp_types::DocumentChanges::Operations(
871 .map(|change| match change {
872 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
873 lsp_types::DocumentChangeOperation::Op(op)
875 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
876 lsp_types::DocumentChangeOperation::Edit(
877 lsp_types::TextDocumentEdit {
878 text_document: edit.text_document,
879 edits: edit.edits.into_iter().map(From::from).collect(),
887 change_annotations: snippet_workspace_edit.change_annotations,
892 impl From<lsp_ext::SnippetTextEdit>
893 for lsp_types::OneOf<lsp_types::TextEdit, lsp_types::AnnotatedTextEdit>
896 lsp_ext::SnippetTextEdit { annotation_id, insert_text_format:_, new_text, range }: lsp_ext::SnippetTextEdit,
898 match annotation_id {
899 Some(annotation_id) => lsp_types::OneOf::Right(lsp_types::AnnotatedTextEdit {
900 text_edit: lsp_types::TextEdit { range, new_text },
903 None => lsp_types::OneOf::Left(lsp_types::TextEdit { range, new_text }),
908 pub(crate) fn call_hierarchy_item(
909 snap: &GlobalStateSnapshot,
910 target: NavigationTarget,
911 ) -> Result<lsp_types::CallHierarchyItem> {
912 let name = target.name.to_string();
913 let detail = target.description.clone();
914 let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::FUNCTION);
915 let (uri, range, selection_range) = location_info(snap, target)?;
916 Ok(lsp_types::CallHierarchyItem {
928 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
930 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
931 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
932 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
933 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
934 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
935 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
939 pub(crate) fn code_action(
940 snap: &GlobalStateSnapshot,
942 resolve_data: Option<(usize, lsp_types::CodeActionParams)>,
943 ) -> Result<lsp_ext::CodeAction> {
944 let mut res = lsp_ext::CodeAction {
945 title: assist.label.to_string(),
946 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
947 kind: Some(code_action_kind(assist.id.1)),
952 match (assist.source_change, resolve_data) {
953 (Some(it), _) => res.edit = Some(snippet_workspace_edit(snap, it)?),
954 (None, Some((index, code_action_params))) => {
955 res.data = Some(lsp_ext::CodeActionData {
956 id: format!("{}:{}:{}", assist.id.0, assist.id.1.name(), index),
961 stdx::never!("assist should always be resolved if client can't do lazy resolving")
967 pub(crate) fn runnable(
968 snap: &GlobalStateSnapshot,
970 ) -> Result<lsp_ext::Runnable> {
971 let config = snap.config.runnables();
972 let spec = CargoTargetSpec::for_file(snap, runnable.nav.file_id)?;
973 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
974 let target = spec.as_ref().map(|s| s.target.clone());
975 let (cargo_args, executable_args) =
976 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
977 let label = runnable.label(target);
978 let location = location_link(snap, None, runnable.nav)?;
980 Ok(lsp_ext::Runnable {
982 location: Some(location),
983 kind: lsp_ext::RunnableKind::Cargo,
984 args: lsp_ext::CargoRunnable {
985 workspace_root: workspace_root.map(|it| it.into()),
986 override_cargo: config.override_cargo,
988 cargo_extra_args: config.cargo_extra_args,
995 pub(crate) fn code_lens(
996 acc: &mut Vec<lsp_types::CodeLens>,
997 snap: &GlobalStateSnapshot,
998 annotation: Annotation,
1000 let client_commands_config = snap.config.client_commands();
1001 match annotation.kind {
1002 AnnotationKind::Runnable(run) => {
1003 let line_index = snap.file_line_index(run.nav.file_id)?;
1004 let annotation_range = range(&line_index, annotation.range);
1006 let title = run.title();
1007 let can_debug = match run.kind {
1008 ide::RunnableKind::DocTest { .. } => false,
1009 ide::RunnableKind::TestMod { .. }
1010 | ide::RunnableKind::Test { .. }
1011 | ide::RunnableKind::Bench { .. }
1012 | ide::RunnableKind::Bin => true,
1014 let r = runnable(snap, run)?;
1016 let lens_config = snap.config.lens();
1017 if lens_config.run && client_commands_config.run_single {
1018 let command = command::run_single(&r, &title);
1019 acc.push(lsp_types::CodeLens {
1020 range: annotation_range,
1021 command: Some(command),
1025 if lens_config.debug && can_debug && client_commands_config.debug_single {
1026 let command = command::debug_single(&r);
1027 acc.push(lsp_types::CodeLens {
1028 range: annotation_range,
1029 command: Some(command),
1034 AnnotationKind::HasImpls { position: file_position, data } => {
1035 if !client_commands_config.show_reference {
1038 let line_index = snap.file_line_index(file_position.file_id)?;
1039 let annotation_range = range(&line_index, annotation.range);
1040 let url = url(snap, file_position.file_id);
1042 let position = position(&line_index, file_position.offset);
1044 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1046 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
1048 let goto_params = lsp_types::request::GotoImplementationParams {
1049 text_document_position_params: doc_pos,
1050 work_done_progress_params: Default::default(),
1051 partial_result_params: Default::default(),
1054 let command = data.map(|ranges| {
1055 let locations: Vec<lsp_types::Location> = ranges
1057 .filter_map(|target| {
1060 FileRange { file_id: target.file_id, range: target.full_range },
1066 command::show_references(
1067 implementation_title(locations.len()),
1074 acc.push(lsp_types::CodeLens {
1075 range: annotation_range,
1077 data: Some(to_value(lsp_ext::CodeLensResolveData::Impls(goto_params)).unwrap()),
1080 AnnotationKind::HasReferences { position: file_position, data } => {
1081 if !client_commands_config.show_reference {
1084 let line_index = snap.file_line_index(file_position.file_id)?;
1085 let annotation_range = range(&line_index, annotation.range);
1086 let url = url(snap, file_position.file_id);
1088 let position = position(&line_index, file_position.offset);
1090 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1092 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
1094 let command = data.map(|ranges| {
1095 let locations: Vec<lsp_types::Location> =
1096 ranges.into_iter().filter_map(|range| location(snap, range).ok()).collect();
1098 command::show_references(
1099 reference_title(locations.len()),
1106 acc.push(lsp_types::CodeLens {
1107 range: annotation_range,
1109 data: Some(to_value(lsp_ext::CodeLensResolveData::References(doc_pos)).unwrap()),
1116 pub(crate) mod command {
1117 use ide::{FileRange, NavigationTarget};
1118 use serde_json::to_value;
1121 global_state::GlobalStateSnapshot,
1123 to_proto::{location, location_link},
1126 pub(crate) fn show_references(
1128 uri: &lsp_types::Url,
1129 position: lsp_types::Position,
1130 locations: Vec<lsp_types::Location>,
1131 ) -> lsp_types::Command {
1132 // We cannot use the 'editor.action.showReferences' command directly
1133 // because that command requires vscode types which we convert in the handler
1134 // on the client side.
1136 lsp_types::Command {
1138 command: "rust-analyzer.showReferences".into(),
1139 arguments: Some(vec![
1140 to_value(uri).unwrap(),
1141 to_value(position).unwrap(),
1142 to_value(locations).unwrap(),
1147 pub(crate) fn run_single(runnable: &lsp_ext::Runnable, title: &str) -> lsp_types::Command {
1148 lsp_types::Command {
1149 title: title.to_string(),
1150 command: "rust-analyzer.runSingle".into(),
1151 arguments: Some(vec![to_value(runnable).unwrap()]),
1155 pub(crate) fn debug_single(runnable: &lsp_ext::Runnable) -> lsp_types::Command {
1156 lsp_types::Command {
1157 title: "Debug".into(),
1158 command: "rust-analyzer.debugSingle".into(),
1159 arguments: Some(vec![to_value(runnable).unwrap()]),
1163 pub(crate) fn goto_location(
1164 snap: &GlobalStateSnapshot,
1165 nav: &NavigationTarget,
1166 ) -> Option<lsp_types::Command> {
1167 let value = if snap.config.location_link() {
1168 let link = location_link(snap, None, nav.clone()).ok()?;
1169 to_value(link).ok()?
1171 let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1172 let location = location(snap, range).ok()?;
1173 to_value(location).ok()?
1176 Some(lsp_types::Command {
1177 title: nav.name.to_string(),
1178 command: "rust-analyzer.gotoLocation".into(),
1179 arguments: Some(vec![value]),
1183 pub(crate) fn trigger_parameter_hints() -> lsp_types::Command {
1184 lsp_types::Command {
1185 title: "triggerParameterHints".into(),
1186 command: "editor.action.triggerParameterHints".into(),
1192 pub(crate) fn implementation_title(count: usize) -> String {
1194 "1 implementation".into()
1196 format!("{} implementations", count)
1200 pub(crate) fn reference_title(count: usize) -> String {
1202 "1 reference".into()
1204 format!("{} references", count)
1208 pub(crate) fn markup_content(
1210 kind: ide::HoverDocFormat,
1211 ) -> lsp_types::MarkupContent {
1212 let kind = match kind {
1213 ide::HoverDocFormat::Markdown => lsp_types::MarkupKind::Markdown,
1214 ide::HoverDocFormat::PlainText => lsp_types::MarkupKind::PlainText,
1216 let value = crate::markdown::format_docs(markup.as_str());
1217 lsp_types::MarkupContent { kind, value }
1220 pub(crate) fn rename_error(err: RenameError) -> crate::LspError {
1221 // This is wrong, but we don't have a better alternative I suppose?
1222 // https://github.com/microsoft/language-server-protocol/issues/1341
1223 invalid_params_error(err.to_string())
1235 fn conv_fold_line_folding_only_fixup() {
1236 let text = r#"mod a;
1248 let (analysis, file_id) = Analysis::from_single_file(text.to_string());
1249 let folds = analysis.folding_ranges(file_id).unwrap();
1250 assert_eq!(folds.len(), 4);
1252 let line_index = LineIndex {
1253 index: Arc::new(ide::LineIndex::new(text)),
1254 endings: LineEndings::Unix,
1255 encoding: OffsetEncoding::Utf16,
1257 let converted: Vec<lsp_types::FoldingRange> =
1258 folds.into_iter().map(|it| folding_range(text, &line_index, true, it)).collect();
1260 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
1261 assert_eq!(converted.len(), expected_lines.len());
1262 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
1263 assert_eq!(folding_range.start_line, *start_line);
1264 assert_eq!(folding_range.start_character, None);
1265 assert_eq!(folding_range.end_line, *end_line);
1266 assert_eq!(folding_range.end_character, None);
1270 // `Url` is not able to parse windows paths on unix machines.
1272 #[cfg(target_os = "windows")]
1273 fn test_lowercase_drive_letter() {
1274 use std::{convert::TryInto, path::Path};
1276 let url = url_from_abs_path(Path::new("C:\\Test").try_into().unwrap());
1277 assert_eq!(url.to_string(), "file:///c:/Test");
1279 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#).try_into().unwrap());
1280 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");