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 | SymbolKind::Attribute => {
54 lsp_types::SymbolKind::FUNCTION
56 SymbolKind::Module | SymbolKind::ToolModule => lsp_types::SymbolKind::MODULE,
57 SymbolKind::TypeAlias | SymbolKind::TypeParam => lsp_types::SymbolKind::TYPE_PARAMETER,
58 SymbolKind::Field => lsp_types::SymbolKind::FIELD,
59 SymbolKind::Static => lsp_types::SymbolKind::CONSTANT,
60 SymbolKind::Const => lsp_types::SymbolKind::CONSTANT,
61 SymbolKind::ConstParam => lsp_types::SymbolKind::CONSTANT,
62 SymbolKind::Impl => lsp_types::SymbolKind::OBJECT,
64 | SymbolKind::SelfParam
65 | SymbolKind::LifetimeParam
66 | SymbolKind::ValueParam
67 | SymbolKind::Label => lsp_types::SymbolKind::VARIABLE,
68 SymbolKind::Union => lsp_types::SymbolKind::STRUCT,
72 pub(crate) fn structure_node_kind(kind: StructureNodeKind) -> lsp_types::SymbolKind {
74 StructureNodeKind::SymbolKind(symbol) => symbol_kind(symbol),
75 StructureNodeKind::Region => lsp_types::SymbolKind::NAMESPACE,
79 pub(crate) fn document_highlight_kind(
80 category: ReferenceCategory,
81 ) -> lsp_types::DocumentHighlightKind {
83 ReferenceCategory::Read => lsp_types::DocumentHighlightKind::READ,
84 ReferenceCategory::Write => lsp_types::DocumentHighlightKind::WRITE,
88 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
90 Severity::Error => lsp_types::DiagnosticSeverity::ERROR,
91 Severity::WeakWarning => lsp_types::DiagnosticSeverity::HINT,
95 pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
96 let value = crate::markdown::format_docs(documentation.as_str());
97 let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
98 lsp_types::Documentation::MarkupContent(markup_content)
101 pub(crate) fn completion_item_kind(
102 completion_item_kind: CompletionItemKind,
103 ) -> lsp_types::CompletionItemKind {
104 match completion_item_kind {
105 CompletionItemKind::Binding => lsp_types::CompletionItemKind::VARIABLE,
106 CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::STRUCT,
107 CompletionItemKind::Keyword => lsp_types::CompletionItemKind::KEYWORD,
108 CompletionItemKind::Method => lsp_types::CompletionItemKind::METHOD,
109 CompletionItemKind::Snippet => lsp_types::CompletionItemKind::SNIPPET,
110 CompletionItemKind::UnresolvedReference => lsp_types::CompletionItemKind::REFERENCE,
111 CompletionItemKind::SymbolKind(symbol) => match symbol {
112 SymbolKind::Attribute => lsp_types::CompletionItemKind::FUNCTION,
113 SymbolKind::Const => lsp_types::CompletionItemKind::CONSTANT,
114 SymbolKind::ConstParam => lsp_types::CompletionItemKind::TYPE_PARAMETER,
115 SymbolKind::Enum => lsp_types::CompletionItemKind::ENUM,
116 SymbolKind::Field => lsp_types::CompletionItemKind::FIELD,
117 SymbolKind::Function => lsp_types::CompletionItemKind::FUNCTION,
118 SymbolKind::Impl => lsp_types::CompletionItemKind::TEXT,
119 SymbolKind::Label => lsp_types::CompletionItemKind::VARIABLE,
120 SymbolKind::LifetimeParam => lsp_types::CompletionItemKind::TYPE_PARAMETER,
121 SymbolKind::Local => lsp_types::CompletionItemKind::VARIABLE,
122 SymbolKind::Macro => lsp_types::CompletionItemKind::FUNCTION,
123 SymbolKind::Module => lsp_types::CompletionItemKind::MODULE,
124 SymbolKind::SelfParam => lsp_types::CompletionItemKind::VALUE,
125 SymbolKind::Static => lsp_types::CompletionItemKind::VALUE,
126 SymbolKind::Struct => lsp_types::CompletionItemKind::STRUCT,
127 SymbolKind::Trait => lsp_types::CompletionItemKind::INTERFACE,
128 SymbolKind::TypeAlias => lsp_types::CompletionItemKind::STRUCT,
129 SymbolKind::TypeParam => lsp_types::CompletionItemKind::TYPE_PARAMETER,
130 SymbolKind::Union => lsp_types::CompletionItemKind::STRUCT,
131 SymbolKind::ValueParam => lsp_types::CompletionItemKind::VALUE,
132 SymbolKind::Variant => lsp_types::CompletionItemKind::ENUM_MEMBER,
133 SymbolKind::BuiltinAttr => lsp_types::CompletionItemKind::FUNCTION,
134 SymbolKind::ToolModule => lsp_types::CompletionItemKind::MODULE,
139 pub(crate) fn text_edit(line_index: &LineIndex, indel: Indel) -> lsp_types::TextEdit {
140 let range = range(line_index, indel.delete);
141 let new_text = match line_index.endings {
142 LineEndings::Unix => indel.insert,
143 LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
145 lsp_types::TextEdit { range, new_text }
148 pub(crate) fn completion_text_edit(
149 line_index: &LineIndex,
150 insert_replace_support: Option<lsp_types::Position>,
152 ) -> lsp_types::CompletionTextEdit {
153 let text_edit = text_edit(line_index, indel);
154 match insert_replace_support {
155 Some(cursor_pos) => lsp_types::InsertReplaceEdit {
156 new_text: text_edit.new_text,
157 insert: lsp_types::Range { start: text_edit.range.start, end: cursor_pos },
158 replace: text_edit.range,
161 None => text_edit.into(),
165 pub(crate) fn snippet_text_edit(
166 line_index: &LineIndex,
169 ) -> lsp_ext::SnippetTextEdit {
170 let text_edit = text_edit(line_index, indel);
171 let insert_text_format =
172 if is_snippet { Some(lsp_types::InsertTextFormat::SNIPPET) } else { None };
173 lsp_ext::SnippetTextEdit {
174 range: text_edit.range,
175 new_text: text_edit.new_text,
181 pub(crate) fn text_edit_vec(
182 line_index: &LineIndex,
184 ) -> Vec<lsp_types::TextEdit> {
185 text_edit.into_iter().map(|indel| self::text_edit(line_index, indel)).collect()
188 pub(crate) fn snippet_text_edit_vec(
189 line_index: &LineIndex,
192 ) -> Vec<lsp_ext::SnippetTextEdit> {
195 .map(|indel| self::snippet_text_edit(line_index, is_snippet, indel))
199 pub(crate) fn completion_items(
201 line_index: &LineIndex,
202 tdpp: lsp_types::TextDocumentPositionParams,
203 items: Vec<CompletionItem>,
204 ) -> Vec<lsp_types::CompletionItem> {
205 let max_relevance = items.iter().map(|it| it.relevance().score()).max().unwrap_or_default();
206 let mut res = Vec::with_capacity(items.len());
208 completion_item(&mut res, config, line_index, &tdpp, max_relevance, item)
214 acc: &mut Vec<lsp_types::CompletionItem>,
216 line_index: &LineIndex,
217 tdpp: &lsp_types::TextDocumentPositionParams,
219 item: CompletionItem,
221 let mut additional_text_edits = Vec::new();
223 // LSP does not allow arbitrary edits in completion, so we have to do a
224 // non-trivial mapping here.
226 let mut text_edit = None;
227 let source_range = item.source_range();
228 for indel in item.text_edit().iter() {
229 if indel.delete.contains_range(source_range) {
230 let insert_replace_support = config.insert_replace_support().then(|| tdpp.position);
231 text_edit = Some(if indel.delete == source_range {
232 self::completion_text_edit(line_index, insert_replace_support, indel.clone())
234 assert!(source_range.end() == indel.delete.end());
235 let range1 = TextRange::new(indel.delete.start(), source_range.start());
236 let range2 = source_range;
237 let indel1 = Indel::replace(range1, String::new());
238 let indel2 = Indel::replace(range2, indel.insert.clone());
239 additional_text_edits.push(self::text_edit(line_index, indel1));
240 self::completion_text_edit(line_index, insert_replace_support, indel2)
243 assert!(source_range.intersect(indel.delete).is_none());
244 let text_edit = self::text_edit(line_index, indel.clone());
245 additional_text_edits.push(text_edit);
251 let mut lsp_item = lsp_types::CompletionItem {
252 label: item.label().to_string(),
253 detail: item.detail().map(|it| it.to_string()),
254 filter_text: Some(item.lookup().to_string()),
255 kind: Some(completion_item_kind(item.kind())),
256 text_edit: Some(text_edit),
257 additional_text_edits: Some(additional_text_edits),
258 documentation: item.documentation().map(documentation),
259 deprecated: Some(item.deprecated()),
263 set_score(&mut lsp_item, max_relevance, item.relevance());
265 if item.deprecated() {
266 lsp_item.tags = Some(vec![lsp_types::CompletionItemTag::DEPRECATED])
269 if item.trigger_call_info() && config.client_commands().trigger_parameter_hints {
270 lsp_item.command = Some(command::trigger_parameter_hints());
273 if item.is_snippet() {
274 lsp_item.insert_text_format = Some(lsp_types::InsertTextFormat::SNIPPET);
276 if config.completion().enable_imports_on_the_fly {
277 if let imports @ [_, ..] = item.imports_to_add() {
278 let imports: Vec<_> = imports
280 .filter_map(|import_edit| {
281 let import_path = &import_edit.import.import_path;
282 let import_name = import_path.segments().last()?;
283 Some(lsp_ext::CompletionImport {
284 full_import_path: import_path.to_string(),
285 imported_name: import_name.to_string(),
289 if !imports.is_empty() {
290 let data = lsp_ext::CompletionResolveData { position: tdpp.clone(), imports };
291 lsp_item.data = Some(to_value(data).unwrap());
296 if let Some((mutability, relevance)) = item.ref_match() {
297 let mut lsp_item_with_ref = lsp_item.clone();
298 set_score(&mut lsp_item_with_ref, max_relevance, relevance);
299 lsp_item_with_ref.label =
300 format!("&{}{}", mutability.as_keyword_for_ref(), lsp_item_with_ref.label);
301 if let Some(it) = &mut lsp_item_with_ref.text_edit {
302 let new_text = match it {
303 lsp_types::CompletionTextEdit::Edit(it) => &mut it.new_text,
304 lsp_types::CompletionTextEdit::InsertAndReplace(it) => &mut it.new_text,
306 *new_text = format!("&{}{}", mutability.as_keyword_for_ref(), new_text);
309 acc.push(lsp_item_with_ref);
315 res: &mut lsp_types::CompletionItem,
317 relevance: CompletionRelevance,
319 if relevance.is_relevant() && relevance.score() == max_relevance {
320 res.preselect = Some(true);
322 // The relevance needs to be inverted to come up with a sort score
323 // because the client will sort ascending.
324 let sort_score = relevance.score() ^ 0xFF_FF_FF_FF;
325 // Zero pad the string to ensure values can be properly sorted
326 // by the client. Hex format is used because it is easier to
327 // visually compare very large values, which the sort text
328 // tends to be since it is the opposite of the score.
329 res.sort_text = Some(format!("{:08x}", sort_score));
333 pub(crate) fn signature_help(
337 ) -> lsp_types::SignatureHelp {
338 let (label, parameters) = match (concise, label_offsets) {
340 let params = call_info
342 .map(|label| lsp_types::ParameterInformation {
343 label: lsp_types::ParameterLabel::Simple(label.to_string()),
346 .collect::<Vec<_>>();
348 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
352 let params = call_info
355 .map(|it| [u32::from(it.start()), u32::from(it.end())])
356 .map(|label_offsets| lsp_types::ParameterInformation {
357 label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
360 .collect::<Vec<_>>();
361 (call_info.signature, params)
364 let mut params = Vec::new();
365 let mut label = String::new();
366 let mut first = true;
367 for param in call_info.parameter_labels() {
369 label.push_str(", ");
372 let start = label.len() as u32;
373 label.push_str(param);
374 let end = label.len() as u32;
375 params.push(lsp_types::ParameterInformation {
376 label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
385 let documentation = if concise {
388 call_info.doc.map(|doc| {
389 lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
390 kind: lsp_types::MarkupKind::Markdown,
396 let active_parameter = call_info.active_parameter.map(|it| it as u32);
398 let signature = lsp_types::SignatureInformation {
401 parameters: Some(parameters),
404 lsp_types::SignatureHelp {
405 signatures: vec![signature],
406 active_signature: Some(0),
411 pub(crate) fn inlay_hint(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
413 label: inlay_hint.label.to_string(),
414 range: range(line_index, inlay_hint.range),
415 kind: match inlay_hint.kind {
416 InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
417 InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
418 InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
423 static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
425 pub(crate) fn semantic_tokens(
427 line_index: &LineIndex,
428 highlights: Vec<HlRange>,
429 highlight_strings: bool,
430 ) -> lsp_types::SemanticTokens {
431 let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
432 let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
434 for highlight_range in highlights {
435 if highlight_range.highlight.is_empty() {
438 let (ty, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
439 if !highlight_strings && ty == lsp_types::SemanticTokenType::STRING {
442 let token_index = semantic_tokens::type_index(ty);
443 let modifier_bitset = mods.0;
445 for mut text_range in line_index.index.lines(highlight_range.range) {
446 if text[text_range].ends_with('\n') {
448 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
450 let range = range(line_index, text_range);
451 builder.push(range, token_index, modifier_bitset);
458 pub(crate) fn semantic_token_delta(
459 previous: &lsp_types::SemanticTokens,
460 current: &lsp_types::SemanticTokens,
461 ) -> lsp_types::SemanticTokensDelta {
462 let result_id = current.result_id.clone();
463 let edits = semantic_tokens::diff_tokens(&previous.data, ¤t.data);
464 lsp_types::SemanticTokensDelta { result_id, edits }
467 fn semantic_token_type_and_modifiers(
468 highlight: Highlight,
469 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
470 let mut mods = semantic_tokens::ModifierSet::default();
471 let type_ = match highlight.tag {
472 HlTag::Symbol(symbol) => match symbol {
473 SymbolKind::Attribute => semantic_tokens::ATTRIBUTE,
474 SymbolKind::Module => lsp_types::SemanticTokenType::NAMESPACE,
475 SymbolKind::Impl => semantic_tokens::TYPE_ALIAS,
476 SymbolKind::Field => lsp_types::SemanticTokenType::PROPERTY,
477 SymbolKind::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
478 SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
479 SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
480 SymbolKind::Label => semantic_tokens::LABEL,
481 SymbolKind::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
482 SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
483 SymbolKind::Local => lsp_types::SemanticTokenType::VARIABLE,
484 SymbolKind::Function => {
485 if highlight.mods.contains(HlMod::Associated) {
486 lsp_types::SemanticTokenType::METHOD
488 lsp_types::SemanticTokenType::FUNCTION
491 SymbolKind::Const => {
492 mods |= semantic_tokens::CONSTANT;
493 mods |= lsp_types::SemanticTokenModifier::STATIC;
494 lsp_types::SemanticTokenType::VARIABLE
496 SymbolKind::Static => {
497 mods |= lsp_types::SemanticTokenModifier::STATIC;
498 lsp_types::SemanticTokenType::VARIABLE
500 SymbolKind::Struct => lsp_types::SemanticTokenType::STRUCT,
501 SymbolKind::Enum => lsp_types::SemanticTokenType::ENUM,
502 SymbolKind::Variant => lsp_types::SemanticTokenType::ENUM_MEMBER,
503 SymbolKind::Union => semantic_tokens::UNION,
504 SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
505 SymbolKind::Trait => lsp_types::SemanticTokenType::INTERFACE,
506 SymbolKind::Macro => lsp_types::SemanticTokenType::MACRO,
507 SymbolKind::BuiltinAttr => semantic_tokens::BUILTIN_ATTRIBUTE,
508 SymbolKind::ToolModule => semantic_tokens::TOOL_MODULE,
510 HlTag::AttributeBracket => semantic_tokens::ATTRIBUTE_BRACKET,
511 HlTag::BoolLiteral => semantic_tokens::BOOLEAN,
512 HlTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
513 HlTag::ByteLiteral | HlTag::NumericLiteral => lsp_types::SemanticTokenType::NUMBER,
514 HlTag::CharLiteral => semantic_tokens::CHAR,
515 HlTag::Comment => lsp_types::SemanticTokenType::COMMENT,
516 HlTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
517 HlTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
518 HlTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
519 HlTag::None => semantic_tokens::GENERIC,
520 HlTag::Operator(op) => match op {
521 HlOperator::Bitwise => semantic_tokens::BITWISE,
522 HlOperator::Arithmetic => semantic_tokens::ARITHMETIC,
523 HlOperator::Logical => semantic_tokens::LOGICAL,
524 HlOperator::Comparison => semantic_tokens::COMPARISON,
525 HlOperator::Other => semantic_tokens::OPERATOR,
527 HlTag::StringLiteral => lsp_types::SemanticTokenType::STRING,
528 HlTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
529 HlTag::Punctuation(punct) => match punct {
530 HlPunct::Bracket => semantic_tokens::BRACKET,
531 HlPunct::Brace => semantic_tokens::BRACE,
532 HlPunct::Parenthesis => semantic_tokens::PARENTHESIS,
533 HlPunct::Angle => semantic_tokens::ANGLE,
534 HlPunct::Comma => semantic_tokens::COMMA,
535 HlPunct::Dot => semantic_tokens::DOT,
536 HlPunct::Colon => semantic_tokens::COLON,
537 HlPunct::Semi => semantic_tokens::SEMICOLON,
538 HlPunct::Other => semantic_tokens::PUNCTUATION,
542 for modifier in highlight.mods.iter() {
543 let modifier = match modifier {
544 HlMod::Associated => continue,
545 HlMod::Async => semantic_tokens::ASYNC,
546 HlMod::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
547 HlMod::Callable => semantic_tokens::CALLABLE,
548 HlMod::Consuming => semantic_tokens::CONSUMING,
549 HlMod::ControlFlow => semantic_tokens::CONTROL_FLOW,
550 HlMod::CrateRoot => semantic_tokens::CRATE_ROOT,
551 HlMod::DefaultLibrary => lsp_types::SemanticTokenModifier::DEFAULT_LIBRARY,
552 HlMod::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
553 HlMod::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
554 HlMod::Injected => semantic_tokens::INJECTED,
555 HlMod::IntraDocLink => semantic_tokens::INTRA_DOC_LINK,
556 HlMod::Library => semantic_tokens::LIBRARY,
557 HlMod::Mutable => semantic_tokens::MUTABLE,
558 HlMod::Public => semantic_tokens::PUBLIC,
559 HlMod::Reference => semantic_tokens::REFERENCE,
560 HlMod::Static => lsp_types::SemanticTokenModifier::STATIC,
561 HlMod::Trait => semantic_tokens::TRAIT_MODIFIER,
562 HlMod::Unsafe => semantic_tokens::UNSAFE,
570 pub(crate) fn folding_range(
572 line_index: &LineIndex,
573 line_folding_only: bool,
575 ) -> lsp_types::FoldingRange {
576 let kind = match fold.kind {
577 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
578 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
579 FoldKind::Region => Some(lsp_types::FoldingRangeKind::Region),
585 | FoldKind::WhereClause
586 | FoldKind::ReturnType
587 | FoldKind::Array => None,
590 let range = range(line_index, fold.range);
592 if line_folding_only {
593 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
594 // even if it contains text not in the folding range. To prevent that we exclude
595 // range.end.line from the folding region if there is more text after range.end
597 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
599 .take_while(|it| *it != '\n')
600 .any(|it| !it.is_whitespace());
602 let end_line = if has_more_text_on_end_line {
603 range.end.line.saturating_sub(1)
608 lsp_types::FoldingRange {
609 start_line: range.start.line,
610 start_character: None,
616 lsp_types::FoldingRange {
617 start_line: range.start.line,
618 start_character: Some(range.start.character),
619 end_line: range.end.line,
620 end_character: Some(range.end.character),
626 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
627 snap.file_id_to_url(file_id)
630 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
631 /// This will only happen when processing windows paths.
633 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
634 pub(crate) fn url_from_abs_path(path: &AbsPath) -> lsp_types::Url {
635 let url = lsp_types::Url::from_file_path(path).unwrap();
636 match path.as_ref().components().next() {
637 Some(path::Component::Prefix(prefix))
638 if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
640 // Need to lowercase driver letter
645 let driver_letter_range = {
646 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
650 let start = scheme.len() + ':'.len_utf8();
651 start..(start + drive_letter.len())
654 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
655 // machinery *also* canonicalizes the drive letter. So, just massage the
657 let mut url: String = url.into();
658 url[driver_letter_range].make_ascii_lowercase();
659 lsp_types::Url::parse(&url).unwrap()
662 pub(crate) fn optional_versioned_text_document_identifier(
663 snap: &GlobalStateSnapshot,
665 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
666 let url = url(snap, file_id);
667 let version = snap.url_file_version(&url);
668 lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
671 pub(crate) fn location(
672 snap: &GlobalStateSnapshot,
674 ) -> Result<lsp_types::Location> {
675 let url = url(snap, frange.file_id);
676 let line_index = snap.file_line_index(frange.file_id)?;
677 let range = range(&line_index, frange.range);
678 let loc = lsp_types::Location::new(url, range);
682 /// Prefer using `location_link`, if the client has the cap.
683 pub(crate) fn location_from_nav(
684 snap: &GlobalStateSnapshot,
685 nav: NavigationTarget,
686 ) -> Result<lsp_types::Location> {
687 let url = url(snap, nav.file_id);
688 let line_index = snap.file_line_index(nav.file_id)?;
689 let range = range(&line_index, nav.full_range);
690 let loc = lsp_types::Location::new(url, range);
694 pub(crate) fn location_link(
695 snap: &GlobalStateSnapshot,
696 src: Option<FileRange>,
697 target: NavigationTarget,
698 ) -> Result<lsp_types::LocationLink> {
699 let origin_selection_range = match src {
701 let line_index = snap.file_line_index(src.file_id)?;
702 let range = range(&line_index, src.range);
707 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
708 let res = lsp_types::LocationLink {
709 origin_selection_range,
712 target_selection_range,
718 snap: &GlobalStateSnapshot,
719 target: NavigationTarget,
720 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
721 let line_index = snap.file_line_index(target.file_id)?;
723 let target_uri = url(snap, target.file_id);
724 let target_range = range(&line_index, target.full_range);
725 let target_selection_range =
726 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
727 Ok((target_uri, target_range, target_selection_range))
730 pub(crate) fn goto_definition_response(
731 snap: &GlobalStateSnapshot,
732 src: Option<FileRange>,
733 targets: Vec<NavigationTarget>,
734 ) -> Result<lsp_types::GotoDefinitionResponse> {
735 if snap.config.location_link() {
738 .map(|nav| location_link(snap, src, nav))
739 .collect::<Result<Vec<_>>>()?;
742 let locations = targets
745 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
747 .collect::<Result<Vec<_>>>()?;
752 fn outside_workspace_annotation_id() -> String {
753 String::from("OutsideWorkspace")
756 pub(crate) fn snippet_text_document_edit(
757 snap: &GlobalStateSnapshot,
761 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
762 let text_document = optional_versioned_text_document_identifier(snap, file_id);
763 let line_index = snap.file_line_index(file_id)?;
764 let mut edits: Vec<_> =
765 edit.into_iter().map(|it| snippet_text_edit(&line_index, is_snippet, it)).collect();
767 if snap.analysis.is_library_file(file_id)? && snap.config.change_annotation_support() {
768 for edit in &mut edits {
769 edit.annotation_id = Some(outside_workspace_annotation_id())
772 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
775 pub(crate) fn snippet_text_document_ops(
776 snap: &GlobalStateSnapshot,
777 file_system_edit: FileSystemEdit,
778 ) -> Cancellable<Vec<lsp_ext::SnippetDocumentChangeOperation>> {
779 let mut ops = Vec::new();
780 match file_system_edit {
781 FileSystemEdit::CreateFile { dst, initial_contents } => {
782 let uri = snap.anchored_path(&dst);
783 let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
788 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
789 if !initial_contents.is_empty() {
791 lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
792 let text_edit = lsp_ext::SnippetTextEdit {
793 range: lsp_types::Range::default(),
794 new_text: initial_contents,
795 insert_text_format: Some(lsp_types::InsertTextFormat::PLAIN_TEXT),
799 lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
800 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
803 FileSystemEdit::MoveFile { src, dst } => {
804 let old_uri = snap.file_id_to_url(src);
805 let new_uri = snap.anchored_path(&dst);
806 let mut rename_file =
807 lsp_types::RenameFile { old_uri, new_uri, options: None, annotation_id: None };
808 if snap.analysis.is_library_file(src).ok() == Some(true)
809 && snap.config.change_annotation_support()
811 rename_file.annotation_id = Some(outside_workspace_annotation_id())
813 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(lsp_types::ResourceOp::Rename(
821 pub(crate) fn snippet_workspace_edit(
822 snap: &GlobalStateSnapshot,
823 source_change: SourceChange,
824 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
825 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
827 for op in source_change.file_system_edits {
828 let ops = snippet_text_document_ops(snap, op)?;
829 document_changes.extend_from_slice(&ops);
831 for (file_id, edit) in source_change.source_file_edits {
832 let edit = snippet_text_document_edit(snap, source_change.is_snippet, file_id, edit)?;
833 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
835 let mut workspace_edit = lsp_ext::SnippetWorkspaceEdit {
837 document_changes: Some(document_changes),
838 change_annotations: None,
840 if snap.config.change_annotation_support() {
841 workspace_edit.change_annotations = Some(
843 outside_workspace_annotation_id(),
844 lsp_types::ChangeAnnotation {
845 label: String::from("Edit outside of the workspace"),
846 needs_confirmation: Some(true),
847 description: Some(String::from(
848 "This edit lies outside of the workspace and may affect dependencies",
858 pub(crate) fn workspace_edit(
859 snap: &GlobalStateSnapshot,
860 source_change: SourceChange,
861 ) -> Result<lsp_types::WorkspaceEdit> {
862 assert!(!source_change.is_snippet);
863 snippet_workspace_edit(snap, source_change).map(|it| it.into())
866 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
867 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
868 lsp_types::WorkspaceEdit {
870 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
871 lsp_types::DocumentChanges::Operations(
874 .map(|change| match change {
875 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
876 lsp_types::DocumentChangeOperation::Op(op)
878 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
879 lsp_types::DocumentChangeOperation::Edit(
880 lsp_types::TextDocumentEdit {
881 text_document: edit.text_document,
882 edits: edit.edits.into_iter().map(From::from).collect(),
890 change_annotations: snippet_workspace_edit.change_annotations,
895 impl From<lsp_ext::SnippetTextEdit>
896 for lsp_types::OneOf<lsp_types::TextEdit, lsp_types::AnnotatedTextEdit>
899 lsp_ext::SnippetTextEdit { annotation_id, insert_text_format:_, new_text, range }: lsp_ext::SnippetTextEdit,
901 match annotation_id {
902 Some(annotation_id) => lsp_types::OneOf::Right(lsp_types::AnnotatedTextEdit {
903 text_edit: lsp_types::TextEdit { range, new_text },
906 None => lsp_types::OneOf::Left(lsp_types::TextEdit { range, new_text }),
911 pub(crate) fn call_hierarchy_item(
912 snap: &GlobalStateSnapshot,
913 target: NavigationTarget,
914 ) -> Result<lsp_types::CallHierarchyItem> {
915 let name = target.name.to_string();
916 let detail = target.description.clone();
917 let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::FUNCTION);
918 let (uri, range, selection_range) = location_info(snap, target)?;
919 Ok(lsp_types::CallHierarchyItem {
931 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
933 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
934 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
935 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
936 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
937 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
938 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
942 pub(crate) fn code_action(
943 snap: &GlobalStateSnapshot,
945 resolve_data: Option<(usize, lsp_types::CodeActionParams)>,
946 ) -> Result<lsp_ext::CodeAction> {
947 let mut res = lsp_ext::CodeAction {
948 title: assist.label.to_string(),
949 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
950 kind: Some(code_action_kind(assist.id.1)),
955 match (assist.source_change, resolve_data) {
956 (Some(it), _) => res.edit = Some(snippet_workspace_edit(snap, it)?),
957 (None, Some((index, code_action_params))) => {
958 res.data = Some(lsp_ext::CodeActionData {
959 id: format!("{}:{}:{}", assist.id.0, assist.id.1.name(), index),
964 stdx::never!("assist should always be resolved if client can't do lazy resolving")
970 pub(crate) fn runnable(
971 snap: &GlobalStateSnapshot,
973 ) -> Result<lsp_ext::Runnable> {
974 let config = snap.config.runnables();
975 let spec = CargoTargetSpec::for_file(snap, runnable.nav.file_id)?;
976 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
977 let target = spec.as_ref().map(|s| s.target.clone());
978 let (cargo_args, executable_args) =
979 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
980 let label = runnable.label(target);
981 let location = location_link(snap, None, runnable.nav)?;
983 Ok(lsp_ext::Runnable {
985 location: Some(location),
986 kind: lsp_ext::RunnableKind::Cargo,
987 args: lsp_ext::CargoRunnable {
988 workspace_root: workspace_root.map(|it| it.into()),
989 override_cargo: config.override_cargo,
991 cargo_extra_args: config.cargo_extra_args,
998 pub(crate) fn code_lens(
999 acc: &mut Vec<lsp_types::CodeLens>,
1000 snap: &GlobalStateSnapshot,
1001 annotation: Annotation,
1003 let client_commands_config = snap.config.client_commands();
1004 match annotation.kind {
1005 AnnotationKind::Runnable(run) => {
1006 let line_index = snap.file_line_index(run.nav.file_id)?;
1007 let annotation_range = range(&line_index, annotation.range);
1009 let title = run.title();
1010 let can_debug = match run.kind {
1011 ide::RunnableKind::DocTest { .. } => false,
1012 ide::RunnableKind::TestMod { .. }
1013 | ide::RunnableKind::Test { .. }
1014 | ide::RunnableKind::Bench { .. }
1015 | ide::RunnableKind::Bin => true,
1017 let r = runnable(snap, run)?;
1019 let lens_config = snap.config.lens();
1020 if lens_config.run && client_commands_config.run_single {
1021 let command = command::run_single(&r, &title);
1022 acc.push(lsp_types::CodeLens {
1023 range: annotation_range,
1024 command: Some(command),
1028 if lens_config.debug && can_debug && client_commands_config.debug_single {
1029 let command = command::debug_single(&r);
1030 acc.push(lsp_types::CodeLens {
1031 range: annotation_range,
1032 command: Some(command),
1037 AnnotationKind::HasImpls { position: file_position, data } => {
1038 if !client_commands_config.show_reference {
1041 let line_index = snap.file_line_index(file_position.file_id)?;
1042 let annotation_range = range(&line_index, annotation.range);
1043 let url = url(snap, file_position.file_id);
1045 let position = position(&line_index, file_position.offset);
1047 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1049 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
1051 let goto_params = lsp_types::request::GotoImplementationParams {
1052 text_document_position_params: doc_pos,
1053 work_done_progress_params: Default::default(),
1054 partial_result_params: Default::default(),
1057 let command = data.map(|ranges| {
1058 let locations: Vec<lsp_types::Location> = ranges
1060 .filter_map(|target| {
1063 FileRange { file_id: target.file_id, range: target.full_range },
1069 command::show_references(
1070 implementation_title(locations.len()),
1077 acc.push(lsp_types::CodeLens {
1078 range: annotation_range,
1080 data: Some(to_value(lsp_ext::CodeLensResolveData::Impls(goto_params)).unwrap()),
1083 AnnotationKind::HasReferences { position: file_position, data } => {
1084 if !client_commands_config.show_reference {
1087 let line_index = snap.file_line_index(file_position.file_id)?;
1088 let annotation_range = range(&line_index, annotation.range);
1089 let url = url(snap, file_position.file_id);
1091 let position = position(&line_index, file_position.offset);
1093 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1095 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
1097 let command = data.map(|ranges| {
1098 let locations: Vec<lsp_types::Location> =
1099 ranges.into_iter().filter_map(|range| location(snap, range).ok()).collect();
1101 command::show_references(
1102 reference_title(locations.len()),
1109 acc.push(lsp_types::CodeLens {
1110 range: annotation_range,
1112 data: Some(to_value(lsp_ext::CodeLensResolveData::References(doc_pos)).unwrap()),
1119 pub(crate) mod command {
1120 use ide::{FileRange, NavigationTarget};
1121 use serde_json::to_value;
1124 global_state::GlobalStateSnapshot,
1126 to_proto::{location, location_link},
1129 pub(crate) fn show_references(
1131 uri: &lsp_types::Url,
1132 position: lsp_types::Position,
1133 locations: Vec<lsp_types::Location>,
1134 ) -> lsp_types::Command {
1135 // We cannot use the 'editor.action.showReferences' command directly
1136 // because that command requires vscode types which we convert in the handler
1137 // on the client side.
1139 lsp_types::Command {
1141 command: "rust-analyzer.showReferences".into(),
1142 arguments: Some(vec![
1143 to_value(uri).unwrap(),
1144 to_value(position).unwrap(),
1145 to_value(locations).unwrap(),
1150 pub(crate) fn run_single(runnable: &lsp_ext::Runnable, title: &str) -> lsp_types::Command {
1151 lsp_types::Command {
1152 title: title.to_string(),
1153 command: "rust-analyzer.runSingle".into(),
1154 arguments: Some(vec![to_value(runnable).unwrap()]),
1158 pub(crate) fn debug_single(runnable: &lsp_ext::Runnable) -> lsp_types::Command {
1159 lsp_types::Command {
1160 title: "Debug".into(),
1161 command: "rust-analyzer.debugSingle".into(),
1162 arguments: Some(vec![to_value(runnable).unwrap()]),
1166 pub(crate) fn goto_location(
1167 snap: &GlobalStateSnapshot,
1168 nav: &NavigationTarget,
1169 ) -> Option<lsp_types::Command> {
1170 let value = if snap.config.location_link() {
1171 let link = location_link(snap, None, nav.clone()).ok()?;
1172 to_value(link).ok()?
1174 let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1175 let location = location(snap, range).ok()?;
1176 to_value(location).ok()?
1179 Some(lsp_types::Command {
1180 title: nav.name.to_string(),
1181 command: "rust-analyzer.gotoLocation".into(),
1182 arguments: Some(vec![value]),
1186 pub(crate) fn trigger_parameter_hints() -> lsp_types::Command {
1187 lsp_types::Command {
1188 title: "triggerParameterHints".into(),
1189 command: "editor.action.triggerParameterHints".into(),
1195 pub(crate) fn implementation_title(count: usize) -> String {
1197 "1 implementation".into()
1199 format!("{} implementations", count)
1203 pub(crate) fn reference_title(count: usize) -> String {
1205 "1 reference".into()
1207 format!("{} references", count)
1211 pub(crate) fn markup_content(
1213 kind: ide::HoverDocFormat,
1214 ) -> lsp_types::MarkupContent {
1215 let kind = match kind {
1216 ide::HoverDocFormat::Markdown => lsp_types::MarkupKind::Markdown,
1217 ide::HoverDocFormat::PlainText => lsp_types::MarkupKind::PlainText,
1219 let value = crate::markdown::format_docs(markup.as_str());
1220 lsp_types::MarkupContent { kind, value }
1223 pub(crate) fn rename_error(err: RenameError) -> crate::LspError {
1224 // This is wrong, but we don't have a better alternative I suppose?
1225 // https://github.com/microsoft/language-server-protocol/issues/1341
1226 invalid_params_error(err.to_string())
1238 fn conv_fold_line_folding_only_fixup() {
1239 let text = r#"mod a;
1251 let (analysis, file_id) = Analysis::from_single_file(text.to_string());
1252 let folds = analysis.folding_ranges(file_id).unwrap();
1253 assert_eq!(folds.len(), 4);
1255 let line_index = LineIndex {
1256 index: Arc::new(ide::LineIndex::new(text)),
1257 endings: LineEndings::Unix,
1258 encoding: OffsetEncoding::Utf16,
1260 let converted: Vec<lsp_types::FoldingRange> =
1261 folds.into_iter().map(|it| folding_range(text, &line_index, true, it)).collect();
1263 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
1264 assert_eq!(converted.len(), expected_lines.len());
1265 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
1266 assert_eq!(folding_range.start_line, *start_line);
1267 assert_eq!(folding_range.start_character, None);
1268 assert_eq!(folding_range.end_line, *end_line);
1269 assert_eq!(folding_range.end_character, None);
1273 // `Url` is not able to parse windows paths on unix machines.
1275 #[cfg(target_os = "windows")]
1276 fn test_lowercase_drive_letter() {
1277 use std::{convert::TryInto, path::Path};
1279 let url = url_from_abs_path(Path::new("C:\\Test").try_into().unwrap());
1280 assert_eq!(url.to_string(), "file:///c:/Test");
1282 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#).try_into().unwrap());
1283 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");