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,
54 | SymbolKind::BuiltinAttr
55 | SymbolKind::Attribute
56 | SymbolKind::Derive => lsp_types::SymbolKind::FUNCTION,
57 SymbolKind::Module | SymbolKind::ToolModule => lsp_types::SymbolKind::MODULE,
58 SymbolKind::TypeAlias | SymbolKind::TypeParam => lsp_types::SymbolKind::TYPE_PARAMETER,
59 SymbolKind::Field => lsp_types::SymbolKind::FIELD,
60 SymbolKind::Static => lsp_types::SymbolKind::CONSTANT,
61 SymbolKind::Const => lsp_types::SymbolKind::CONSTANT,
62 SymbolKind::ConstParam => lsp_types::SymbolKind::CONSTANT,
63 SymbolKind::Impl => lsp_types::SymbolKind::OBJECT,
65 | SymbolKind::SelfParam
66 | SymbolKind::LifetimeParam
67 | SymbolKind::ValueParam
68 | SymbolKind::Label => lsp_types::SymbolKind::VARIABLE,
69 SymbolKind::Union => lsp_types::SymbolKind::STRUCT,
73 pub(crate) fn structure_node_kind(kind: StructureNodeKind) -> lsp_types::SymbolKind {
75 StructureNodeKind::SymbolKind(symbol) => symbol_kind(symbol),
76 StructureNodeKind::Region => lsp_types::SymbolKind::NAMESPACE,
80 pub(crate) fn document_highlight_kind(
81 category: ReferenceCategory,
82 ) -> lsp_types::DocumentHighlightKind {
84 ReferenceCategory::Read => lsp_types::DocumentHighlightKind::READ,
85 ReferenceCategory::Write => lsp_types::DocumentHighlightKind::WRITE,
89 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
91 Severity::Error => lsp_types::DiagnosticSeverity::ERROR,
92 Severity::WeakWarning => lsp_types::DiagnosticSeverity::HINT,
96 pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
97 let value = crate::markdown::format_docs(documentation.as_str());
98 let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
99 lsp_types::Documentation::MarkupContent(markup_content)
102 pub(crate) fn completion_item_kind(
103 completion_item_kind: CompletionItemKind,
104 ) -> lsp_types::CompletionItemKind {
105 match completion_item_kind {
106 CompletionItemKind::Binding => lsp_types::CompletionItemKind::VARIABLE,
107 CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::STRUCT,
108 CompletionItemKind::Keyword => lsp_types::CompletionItemKind::KEYWORD,
109 CompletionItemKind::Method => lsp_types::CompletionItemKind::METHOD,
110 CompletionItemKind::Snippet => lsp_types::CompletionItemKind::SNIPPET,
111 CompletionItemKind::UnresolvedReference => lsp_types::CompletionItemKind::REFERENCE,
112 CompletionItemKind::SymbolKind(symbol) => match symbol {
113 SymbolKind::Attribute => lsp_types::CompletionItemKind::FUNCTION,
114 SymbolKind::Const => lsp_types::CompletionItemKind::CONSTANT,
115 SymbolKind::ConstParam => lsp_types::CompletionItemKind::TYPE_PARAMETER,
116 SymbolKind::Derive => lsp_types::CompletionItemKind::FUNCTION,
117 SymbolKind::Enum => lsp_types::CompletionItemKind::ENUM,
118 SymbolKind::Field => lsp_types::CompletionItemKind::FIELD,
119 SymbolKind::Function => lsp_types::CompletionItemKind::FUNCTION,
120 SymbolKind::Impl => lsp_types::CompletionItemKind::TEXT,
121 SymbolKind::Label => lsp_types::CompletionItemKind::VARIABLE,
122 SymbolKind::LifetimeParam => lsp_types::CompletionItemKind::TYPE_PARAMETER,
123 SymbolKind::Local => lsp_types::CompletionItemKind::VARIABLE,
124 SymbolKind::Macro => lsp_types::CompletionItemKind::FUNCTION,
125 SymbolKind::Module => lsp_types::CompletionItemKind::MODULE,
126 SymbolKind::SelfParam => lsp_types::CompletionItemKind::VALUE,
127 SymbolKind::Static => lsp_types::CompletionItemKind::VALUE,
128 SymbolKind::Struct => lsp_types::CompletionItemKind::STRUCT,
129 SymbolKind::Trait => lsp_types::CompletionItemKind::INTERFACE,
130 SymbolKind::TypeAlias => lsp_types::CompletionItemKind::STRUCT,
131 SymbolKind::TypeParam => lsp_types::CompletionItemKind::TYPE_PARAMETER,
132 SymbolKind::Union => lsp_types::CompletionItemKind::STRUCT,
133 SymbolKind::ValueParam => lsp_types::CompletionItemKind::VALUE,
134 SymbolKind::Variant => lsp_types::CompletionItemKind::ENUM_MEMBER,
135 SymbolKind::BuiltinAttr => lsp_types::CompletionItemKind::FUNCTION,
136 SymbolKind::ToolModule => lsp_types::CompletionItemKind::MODULE,
141 pub(crate) fn text_edit(line_index: &LineIndex, indel: Indel) -> lsp_types::TextEdit {
142 let range = range(line_index, indel.delete);
143 let new_text = match line_index.endings {
144 LineEndings::Unix => indel.insert,
145 LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
147 lsp_types::TextEdit { range, new_text }
150 pub(crate) fn completion_text_edit(
151 line_index: &LineIndex,
152 insert_replace_support: Option<lsp_types::Position>,
154 ) -> lsp_types::CompletionTextEdit {
155 let text_edit = text_edit(line_index, indel);
156 match insert_replace_support {
157 Some(cursor_pos) => lsp_types::InsertReplaceEdit {
158 new_text: text_edit.new_text,
159 insert: lsp_types::Range { start: text_edit.range.start, end: cursor_pos },
160 replace: text_edit.range,
163 None => text_edit.into(),
167 pub(crate) fn snippet_text_edit(
168 line_index: &LineIndex,
171 ) -> lsp_ext::SnippetTextEdit {
172 let text_edit = text_edit(line_index, indel);
173 let insert_text_format =
174 if is_snippet { Some(lsp_types::InsertTextFormat::SNIPPET) } else { None };
175 lsp_ext::SnippetTextEdit {
176 range: text_edit.range,
177 new_text: text_edit.new_text,
183 pub(crate) fn text_edit_vec(
184 line_index: &LineIndex,
186 ) -> Vec<lsp_types::TextEdit> {
187 text_edit.into_iter().map(|indel| self::text_edit(line_index, indel)).collect()
190 pub(crate) fn snippet_text_edit_vec(
191 line_index: &LineIndex,
194 ) -> Vec<lsp_ext::SnippetTextEdit> {
197 .map(|indel| self::snippet_text_edit(line_index, is_snippet, indel))
201 pub(crate) fn completion_items(
203 line_index: &LineIndex,
204 tdpp: lsp_types::TextDocumentPositionParams,
205 items: Vec<CompletionItem>,
206 ) -> Vec<lsp_types::CompletionItem> {
207 let max_relevance = items.iter().map(|it| it.relevance().score()).max().unwrap_or_default();
208 let mut res = Vec::with_capacity(items.len());
210 completion_item(&mut res, config, line_index, &tdpp, max_relevance, item)
216 acc: &mut Vec<lsp_types::CompletionItem>,
218 line_index: &LineIndex,
219 tdpp: &lsp_types::TextDocumentPositionParams,
221 item: CompletionItem,
223 let mut additional_text_edits = Vec::new();
225 // LSP does not allow arbitrary edits in completion, so we have to do a
226 // non-trivial mapping here.
228 let mut text_edit = None;
229 let source_range = item.source_range();
230 for indel in item.text_edit().iter() {
231 if indel.delete.contains_range(source_range) {
232 let insert_replace_support = config.insert_replace_support().then(|| tdpp.position);
233 text_edit = Some(if indel.delete == source_range {
234 self::completion_text_edit(line_index, insert_replace_support, indel.clone())
236 assert!(source_range.end() == indel.delete.end());
237 let range1 = TextRange::new(indel.delete.start(), source_range.start());
238 let range2 = source_range;
239 let indel1 = Indel::replace(range1, String::new());
240 let indel2 = Indel::replace(range2, indel.insert.clone());
241 additional_text_edits.push(self::text_edit(line_index, indel1));
242 self::completion_text_edit(line_index, insert_replace_support, indel2)
245 assert!(source_range.intersect(indel.delete).is_none());
246 let text_edit = self::text_edit(line_index, indel.clone());
247 additional_text_edits.push(text_edit);
253 let mut lsp_item = lsp_types::CompletionItem {
254 label: item.label().to_string(),
255 detail: item.detail().map(|it| it.to_string()),
256 filter_text: Some(item.lookup().to_string()),
257 kind: Some(completion_item_kind(item.kind())),
258 text_edit: Some(text_edit),
259 additional_text_edits: Some(additional_text_edits),
260 documentation: item.documentation().map(documentation),
261 deprecated: Some(item.deprecated()),
265 set_score(&mut lsp_item, max_relevance, item.relevance());
267 if item.deprecated() {
268 lsp_item.tags = Some(vec![lsp_types::CompletionItemTag::DEPRECATED])
271 if item.trigger_call_info() && config.client_commands().trigger_parameter_hints {
272 lsp_item.command = Some(command::trigger_parameter_hints());
275 if item.is_snippet() {
276 lsp_item.insert_text_format = Some(lsp_types::InsertTextFormat::SNIPPET);
278 if config.completion().enable_imports_on_the_fly {
279 if let imports @ [_, ..] = item.imports_to_add() {
280 let imports: Vec<_> = imports
282 .filter_map(|import_edit| {
283 let import_path = &import_edit.import.import_path;
284 let import_name = import_path.segments().last()?;
285 Some(lsp_ext::CompletionImport {
286 full_import_path: import_path.to_string(),
287 imported_name: import_name.to_string(),
291 if !imports.is_empty() {
292 let data = lsp_ext::CompletionResolveData { position: tdpp.clone(), imports };
293 lsp_item.data = Some(to_value(data).unwrap());
298 if let Some((mutability, relevance)) = item.ref_match() {
299 let mut lsp_item_with_ref = lsp_item.clone();
300 set_score(&mut lsp_item_with_ref, max_relevance, relevance);
301 lsp_item_with_ref.label =
302 format!("&{}{}", mutability.as_keyword_for_ref(), lsp_item_with_ref.label);
303 if let Some(it) = &mut lsp_item_with_ref.text_edit {
304 let new_text = match it {
305 lsp_types::CompletionTextEdit::Edit(it) => &mut it.new_text,
306 lsp_types::CompletionTextEdit::InsertAndReplace(it) => &mut it.new_text,
308 *new_text = format!("&{}{}", mutability.as_keyword_for_ref(), new_text);
311 acc.push(lsp_item_with_ref);
317 res: &mut lsp_types::CompletionItem,
319 relevance: CompletionRelevance,
321 if relevance.is_relevant() && relevance.score() == max_relevance {
322 res.preselect = Some(true);
324 // The relevance needs to be inverted to come up with a sort score
325 // because the client will sort ascending.
326 let sort_score = relevance.score() ^ 0xFF_FF_FF_FF;
327 // Zero pad the string to ensure values can be properly sorted
328 // by the client. Hex format is used because it is easier to
329 // visually compare very large values, which the sort text
330 // tends to be since it is the opposite of the score.
331 res.sort_text = Some(format!("{:08x}", sort_score));
335 pub(crate) fn signature_help(
339 ) -> lsp_types::SignatureHelp {
340 let (label, parameters) = match (concise, label_offsets) {
342 let params = call_info
344 .map(|label| lsp_types::ParameterInformation {
345 label: lsp_types::ParameterLabel::Simple(label.to_string()),
348 .collect::<Vec<_>>();
350 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
354 let params = call_info
357 .map(|it| [u32::from(it.start()), u32::from(it.end())])
358 .map(|label_offsets| lsp_types::ParameterInformation {
359 label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
362 .collect::<Vec<_>>();
363 (call_info.signature, params)
366 let mut params = Vec::new();
367 let mut label = String::new();
368 let mut first = true;
369 for param in call_info.parameter_labels() {
371 label.push_str(", ");
374 let start = label.len() as u32;
375 label.push_str(param);
376 let end = label.len() as u32;
377 params.push(lsp_types::ParameterInformation {
378 label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
387 let documentation = if concise {
390 call_info.doc.map(|doc| {
391 lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
392 kind: lsp_types::MarkupKind::Markdown,
398 let active_parameter = call_info.active_parameter.map(|it| it as u32);
400 let signature = lsp_types::SignatureInformation {
403 parameters: Some(parameters),
406 lsp_types::SignatureHelp {
407 signatures: vec![signature],
408 active_signature: Some(0),
413 pub(crate) fn inlay_hint(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
415 label: inlay_hint.label.to_string(),
416 range: range(line_index, inlay_hint.range),
417 kind: match inlay_hint.kind {
418 InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
419 InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
420 InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
425 static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
427 pub(crate) fn semantic_tokens(
429 line_index: &LineIndex,
430 highlights: Vec<HlRange>,
431 highlight_strings: bool,
432 ) -> lsp_types::SemanticTokens {
433 let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
434 let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
436 for highlight_range in highlights {
437 if highlight_range.highlight.is_empty() {
440 let (ty, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
441 if !highlight_strings && ty == lsp_types::SemanticTokenType::STRING {
444 let token_index = semantic_tokens::type_index(ty);
445 let modifier_bitset = mods.0;
447 for mut text_range in line_index.index.lines(highlight_range.range) {
448 if text[text_range].ends_with('\n') {
450 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
452 let range = range(line_index, text_range);
453 builder.push(range, token_index, modifier_bitset);
460 pub(crate) fn semantic_token_delta(
461 previous: &lsp_types::SemanticTokens,
462 current: &lsp_types::SemanticTokens,
463 ) -> lsp_types::SemanticTokensDelta {
464 let result_id = current.result_id.clone();
465 let edits = semantic_tokens::diff_tokens(&previous.data, ¤t.data);
466 lsp_types::SemanticTokensDelta { result_id, edits }
469 fn semantic_token_type_and_modifiers(
470 highlight: Highlight,
471 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
472 let mut mods = semantic_tokens::ModifierSet::default();
473 let type_ = match highlight.tag {
474 HlTag::Symbol(symbol) => match symbol {
475 SymbolKind::Attribute => semantic_tokens::ATTRIBUTE,
476 SymbolKind::Derive => semantic_tokens::DERIVE,
477 SymbolKind::Module => lsp_types::SemanticTokenType::NAMESPACE,
478 SymbolKind::Impl => semantic_tokens::TYPE_ALIAS,
479 SymbolKind::Field => lsp_types::SemanticTokenType::PROPERTY,
480 SymbolKind::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
481 SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
482 SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
483 SymbolKind::Label => semantic_tokens::LABEL,
484 SymbolKind::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
485 SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
486 SymbolKind::Local => lsp_types::SemanticTokenType::VARIABLE,
487 SymbolKind::Function => {
488 if highlight.mods.contains(HlMod::Associated) {
489 lsp_types::SemanticTokenType::METHOD
491 lsp_types::SemanticTokenType::FUNCTION
494 SymbolKind::Const => {
495 mods |= semantic_tokens::CONSTANT;
496 mods |= lsp_types::SemanticTokenModifier::STATIC;
497 lsp_types::SemanticTokenType::VARIABLE
499 SymbolKind::Static => {
500 mods |= lsp_types::SemanticTokenModifier::STATIC;
501 lsp_types::SemanticTokenType::VARIABLE
503 SymbolKind::Struct => lsp_types::SemanticTokenType::STRUCT,
504 SymbolKind::Enum => lsp_types::SemanticTokenType::ENUM,
505 SymbolKind::Variant => lsp_types::SemanticTokenType::ENUM_MEMBER,
506 SymbolKind::Union => semantic_tokens::UNION,
507 SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
508 SymbolKind::Trait => lsp_types::SemanticTokenType::INTERFACE,
509 SymbolKind::Macro => lsp_types::SemanticTokenType::MACRO,
510 SymbolKind::BuiltinAttr => semantic_tokens::BUILTIN_ATTRIBUTE,
511 SymbolKind::ToolModule => semantic_tokens::TOOL_MODULE,
513 HlTag::AttributeBracket => semantic_tokens::ATTRIBUTE_BRACKET,
514 HlTag::BoolLiteral => semantic_tokens::BOOLEAN,
515 HlTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
516 HlTag::ByteLiteral | HlTag::NumericLiteral => lsp_types::SemanticTokenType::NUMBER,
517 HlTag::CharLiteral => semantic_tokens::CHAR,
518 HlTag::Comment => lsp_types::SemanticTokenType::COMMENT,
519 HlTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
520 HlTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
521 HlTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
522 HlTag::None => semantic_tokens::GENERIC,
523 HlTag::Operator(op) => match op {
524 HlOperator::Bitwise => semantic_tokens::BITWISE,
525 HlOperator::Arithmetic => semantic_tokens::ARITHMETIC,
526 HlOperator::Logical => semantic_tokens::LOGICAL,
527 HlOperator::Comparison => semantic_tokens::COMPARISON,
528 HlOperator::Other => semantic_tokens::OPERATOR,
530 HlTag::StringLiteral => lsp_types::SemanticTokenType::STRING,
531 HlTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
532 HlTag::Punctuation(punct) => match punct {
533 HlPunct::Bracket => semantic_tokens::BRACKET,
534 HlPunct::Brace => semantic_tokens::BRACE,
535 HlPunct::Parenthesis => semantic_tokens::PARENTHESIS,
536 HlPunct::Angle => semantic_tokens::ANGLE,
537 HlPunct::Comma => semantic_tokens::COMMA,
538 HlPunct::Dot => semantic_tokens::DOT,
539 HlPunct::Colon => semantic_tokens::COLON,
540 HlPunct::Semi => semantic_tokens::SEMICOLON,
541 HlPunct::Other => semantic_tokens::PUNCTUATION,
545 for modifier in highlight.mods.iter() {
546 let modifier = match modifier {
547 HlMod::Associated => continue,
548 HlMod::Async => semantic_tokens::ASYNC,
549 HlMod::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
550 HlMod::Callable => semantic_tokens::CALLABLE,
551 HlMod::Consuming => semantic_tokens::CONSUMING,
552 HlMod::ControlFlow => semantic_tokens::CONTROL_FLOW,
553 HlMod::CrateRoot => semantic_tokens::CRATE_ROOT,
554 HlMod::DefaultLibrary => lsp_types::SemanticTokenModifier::DEFAULT_LIBRARY,
555 HlMod::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
556 HlMod::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
557 HlMod::Injected => semantic_tokens::INJECTED,
558 HlMod::IntraDocLink => semantic_tokens::INTRA_DOC_LINK,
559 HlMod::Library => semantic_tokens::LIBRARY,
560 HlMod::Mutable => semantic_tokens::MUTABLE,
561 HlMod::Public => semantic_tokens::PUBLIC,
562 HlMod::Reference => semantic_tokens::REFERENCE,
563 HlMod::Static => lsp_types::SemanticTokenModifier::STATIC,
564 HlMod::Trait => semantic_tokens::TRAIT_MODIFIER,
565 HlMod::Unsafe => semantic_tokens::UNSAFE,
573 pub(crate) fn folding_range(
575 line_index: &LineIndex,
576 line_folding_only: bool,
578 ) -> lsp_types::FoldingRange {
579 let kind = match fold.kind {
580 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
581 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
582 FoldKind::Region => Some(lsp_types::FoldingRangeKind::Region),
588 | FoldKind::WhereClause
589 | FoldKind::ReturnType
590 | FoldKind::Array => None,
593 let range = range(line_index, fold.range);
595 if line_folding_only {
596 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
597 // even if it contains text not in the folding range. To prevent that we exclude
598 // range.end.line from the folding region if there is more text after range.end
600 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
602 .take_while(|it| *it != '\n')
603 .any(|it| !it.is_whitespace());
605 let end_line = if has_more_text_on_end_line {
606 range.end.line.saturating_sub(1)
611 lsp_types::FoldingRange {
612 start_line: range.start.line,
613 start_character: None,
619 lsp_types::FoldingRange {
620 start_line: range.start.line,
621 start_character: Some(range.start.character),
622 end_line: range.end.line,
623 end_character: Some(range.end.character),
629 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
630 snap.file_id_to_url(file_id)
633 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
634 /// This will only happen when processing windows paths.
636 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
637 pub(crate) fn url_from_abs_path(path: &AbsPath) -> lsp_types::Url {
638 let url = lsp_types::Url::from_file_path(path).unwrap();
639 match path.as_ref().components().next() {
640 Some(path::Component::Prefix(prefix))
641 if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
643 // Need to lowercase driver letter
648 let driver_letter_range = {
649 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
653 let start = scheme.len() + ':'.len_utf8();
654 start..(start + drive_letter.len())
657 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
658 // machinery *also* canonicalizes the drive letter. So, just massage the
660 let mut url: String = url.into();
661 url[driver_letter_range].make_ascii_lowercase();
662 lsp_types::Url::parse(&url).unwrap()
665 pub(crate) fn optional_versioned_text_document_identifier(
666 snap: &GlobalStateSnapshot,
668 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
669 let url = url(snap, file_id);
670 let version = snap.url_file_version(&url);
671 lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
674 pub(crate) fn location(
675 snap: &GlobalStateSnapshot,
677 ) -> Result<lsp_types::Location> {
678 let url = url(snap, frange.file_id);
679 let line_index = snap.file_line_index(frange.file_id)?;
680 let range = range(&line_index, frange.range);
681 let loc = lsp_types::Location::new(url, range);
685 /// Prefer using `location_link`, if the client has the cap.
686 pub(crate) fn location_from_nav(
687 snap: &GlobalStateSnapshot,
688 nav: NavigationTarget,
689 ) -> Result<lsp_types::Location> {
690 let url = url(snap, nav.file_id);
691 let line_index = snap.file_line_index(nav.file_id)?;
692 let range = range(&line_index, nav.full_range);
693 let loc = lsp_types::Location::new(url, range);
697 pub(crate) fn location_link(
698 snap: &GlobalStateSnapshot,
699 src: Option<FileRange>,
700 target: NavigationTarget,
701 ) -> Result<lsp_types::LocationLink> {
702 let origin_selection_range = match src {
704 let line_index = snap.file_line_index(src.file_id)?;
705 let range = range(&line_index, src.range);
710 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
711 let res = lsp_types::LocationLink {
712 origin_selection_range,
715 target_selection_range,
721 snap: &GlobalStateSnapshot,
722 target: NavigationTarget,
723 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
724 let line_index = snap.file_line_index(target.file_id)?;
726 let target_uri = url(snap, target.file_id);
727 let target_range = range(&line_index, target.full_range);
728 let target_selection_range =
729 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
730 Ok((target_uri, target_range, target_selection_range))
733 pub(crate) fn goto_definition_response(
734 snap: &GlobalStateSnapshot,
735 src: Option<FileRange>,
736 targets: Vec<NavigationTarget>,
737 ) -> Result<lsp_types::GotoDefinitionResponse> {
738 if snap.config.location_link() {
741 .map(|nav| location_link(snap, src, nav))
742 .collect::<Result<Vec<_>>>()?;
745 let locations = targets
748 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
750 .collect::<Result<Vec<_>>>()?;
755 fn outside_workspace_annotation_id() -> String {
756 String::from("OutsideWorkspace")
759 pub(crate) fn snippet_text_document_edit(
760 snap: &GlobalStateSnapshot,
764 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
765 let text_document = optional_versioned_text_document_identifier(snap, file_id);
766 let line_index = snap.file_line_index(file_id)?;
767 let mut edits: Vec<_> =
768 edit.into_iter().map(|it| snippet_text_edit(&line_index, is_snippet, it)).collect();
770 if snap.analysis.is_library_file(file_id)? && snap.config.change_annotation_support() {
771 for edit in &mut edits {
772 edit.annotation_id = Some(outside_workspace_annotation_id())
775 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
778 pub(crate) fn snippet_text_document_ops(
779 snap: &GlobalStateSnapshot,
780 file_system_edit: FileSystemEdit,
781 ) -> Cancellable<Vec<lsp_ext::SnippetDocumentChangeOperation>> {
782 let mut ops = Vec::new();
783 match file_system_edit {
784 FileSystemEdit::CreateFile { dst, initial_contents } => {
785 let uri = snap.anchored_path(&dst);
786 let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
791 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
792 if !initial_contents.is_empty() {
794 lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
795 let text_edit = lsp_ext::SnippetTextEdit {
796 range: lsp_types::Range::default(),
797 new_text: initial_contents,
798 insert_text_format: Some(lsp_types::InsertTextFormat::PLAIN_TEXT),
802 lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
803 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
806 FileSystemEdit::MoveFile { src, dst } => {
807 let old_uri = snap.file_id_to_url(src);
808 let new_uri = snap.anchored_path(&dst);
809 let mut rename_file =
810 lsp_types::RenameFile { old_uri, new_uri, options: None, annotation_id: None };
811 if snap.analysis.is_library_file(src).ok() == Some(true)
812 && snap.config.change_annotation_support()
814 rename_file.annotation_id = Some(outside_workspace_annotation_id())
816 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(lsp_types::ResourceOp::Rename(
824 pub(crate) fn snippet_workspace_edit(
825 snap: &GlobalStateSnapshot,
826 source_change: SourceChange,
827 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
828 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
830 for op in source_change.file_system_edits {
831 let ops = snippet_text_document_ops(snap, op)?;
832 document_changes.extend_from_slice(&ops);
834 for (file_id, edit) in source_change.source_file_edits {
835 let edit = snippet_text_document_edit(snap, source_change.is_snippet, file_id, edit)?;
836 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
838 let mut workspace_edit = lsp_ext::SnippetWorkspaceEdit {
840 document_changes: Some(document_changes),
841 change_annotations: None,
843 if snap.config.change_annotation_support() {
844 workspace_edit.change_annotations = Some(
846 outside_workspace_annotation_id(),
847 lsp_types::ChangeAnnotation {
848 label: String::from("Edit outside of the workspace"),
849 needs_confirmation: Some(true),
850 description: Some(String::from(
851 "This edit lies outside of the workspace and may affect dependencies",
861 pub(crate) fn workspace_edit(
862 snap: &GlobalStateSnapshot,
863 source_change: SourceChange,
864 ) -> Result<lsp_types::WorkspaceEdit> {
865 assert!(!source_change.is_snippet);
866 snippet_workspace_edit(snap, source_change).map(|it| it.into())
869 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
870 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
871 lsp_types::WorkspaceEdit {
873 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
874 lsp_types::DocumentChanges::Operations(
877 .map(|change| match change {
878 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
879 lsp_types::DocumentChangeOperation::Op(op)
881 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
882 lsp_types::DocumentChangeOperation::Edit(
883 lsp_types::TextDocumentEdit {
884 text_document: edit.text_document,
885 edits: edit.edits.into_iter().map(From::from).collect(),
893 change_annotations: snippet_workspace_edit.change_annotations,
898 impl From<lsp_ext::SnippetTextEdit>
899 for lsp_types::OneOf<lsp_types::TextEdit, lsp_types::AnnotatedTextEdit>
902 lsp_ext::SnippetTextEdit { annotation_id, insert_text_format:_, new_text, range }: lsp_ext::SnippetTextEdit,
904 match annotation_id {
905 Some(annotation_id) => lsp_types::OneOf::Right(lsp_types::AnnotatedTextEdit {
906 text_edit: lsp_types::TextEdit { range, new_text },
909 None => lsp_types::OneOf::Left(lsp_types::TextEdit { range, new_text }),
914 pub(crate) fn call_hierarchy_item(
915 snap: &GlobalStateSnapshot,
916 target: NavigationTarget,
917 ) -> Result<lsp_types::CallHierarchyItem> {
918 let name = target.name.to_string();
919 let detail = target.description.clone();
920 let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::FUNCTION);
921 let (uri, range, selection_range) = location_info(snap, target)?;
922 Ok(lsp_types::CallHierarchyItem {
934 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
936 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
937 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
938 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
939 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
940 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
941 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
945 pub(crate) fn code_action(
946 snap: &GlobalStateSnapshot,
948 resolve_data: Option<(usize, lsp_types::CodeActionParams)>,
949 ) -> Result<lsp_ext::CodeAction> {
950 let mut res = lsp_ext::CodeAction {
951 title: assist.label.to_string(),
952 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
953 kind: Some(code_action_kind(assist.id.1)),
958 match (assist.source_change, resolve_data) {
959 (Some(it), _) => res.edit = Some(snippet_workspace_edit(snap, it)?),
960 (None, Some((index, code_action_params))) => {
961 res.data = Some(lsp_ext::CodeActionData {
962 id: format!("{}:{}:{}", assist.id.0, assist.id.1.name(), index),
967 stdx::never!("assist should always be resolved if client can't do lazy resolving")
973 pub(crate) fn runnable(
974 snap: &GlobalStateSnapshot,
976 ) -> Result<lsp_ext::Runnable> {
977 let config = snap.config.runnables();
978 let spec = CargoTargetSpec::for_file(snap, runnable.nav.file_id)?;
979 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
980 let target = spec.as_ref().map(|s| s.target.clone());
981 let (cargo_args, executable_args) =
982 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
983 let label = runnable.label(target);
984 let location = location_link(snap, None, runnable.nav)?;
986 Ok(lsp_ext::Runnable {
988 location: Some(location),
989 kind: lsp_ext::RunnableKind::Cargo,
990 args: lsp_ext::CargoRunnable {
991 workspace_root: workspace_root.map(|it| it.into()),
992 override_cargo: config.override_cargo,
994 cargo_extra_args: config.cargo_extra_args,
1001 pub(crate) fn code_lens(
1002 acc: &mut Vec<lsp_types::CodeLens>,
1003 snap: &GlobalStateSnapshot,
1004 annotation: Annotation,
1006 let client_commands_config = snap.config.client_commands();
1007 match annotation.kind {
1008 AnnotationKind::Runnable(run) => {
1009 let line_index = snap.file_line_index(run.nav.file_id)?;
1010 let annotation_range = range(&line_index, annotation.range);
1012 let title = run.title();
1013 let can_debug = match run.kind {
1014 ide::RunnableKind::DocTest { .. } => false,
1015 ide::RunnableKind::TestMod { .. }
1016 | ide::RunnableKind::Test { .. }
1017 | ide::RunnableKind::Bench { .. }
1018 | ide::RunnableKind::Bin => true,
1020 let r = runnable(snap, run)?;
1022 let lens_config = snap.config.lens();
1023 if lens_config.run && client_commands_config.run_single {
1024 let command = command::run_single(&r, &title);
1025 acc.push(lsp_types::CodeLens {
1026 range: annotation_range,
1027 command: Some(command),
1031 if lens_config.debug && can_debug && client_commands_config.debug_single {
1032 let command = command::debug_single(&r);
1033 acc.push(lsp_types::CodeLens {
1034 range: annotation_range,
1035 command: Some(command),
1040 AnnotationKind::HasImpls { position: file_position, data } => {
1041 if !client_commands_config.show_reference {
1044 let line_index = snap.file_line_index(file_position.file_id)?;
1045 let annotation_range = range(&line_index, annotation.range);
1046 let url = url(snap, file_position.file_id);
1048 let position = position(&line_index, file_position.offset);
1050 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1052 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
1054 let goto_params = lsp_types::request::GotoImplementationParams {
1055 text_document_position_params: doc_pos,
1056 work_done_progress_params: Default::default(),
1057 partial_result_params: Default::default(),
1060 let command = data.map(|ranges| {
1061 let locations: Vec<lsp_types::Location> = ranges
1063 .filter_map(|target| {
1066 FileRange { file_id: target.file_id, range: target.full_range },
1072 command::show_references(
1073 implementation_title(locations.len()),
1080 acc.push(lsp_types::CodeLens {
1081 range: annotation_range,
1083 data: Some(to_value(lsp_ext::CodeLensResolveData::Impls(goto_params)).unwrap()),
1086 AnnotationKind::HasReferences { position: file_position, data } => {
1087 if !client_commands_config.show_reference {
1090 let line_index = snap.file_line_index(file_position.file_id)?;
1091 let annotation_range = range(&line_index, annotation.range);
1092 let url = url(snap, file_position.file_id);
1094 let position = position(&line_index, file_position.offset);
1096 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1098 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
1100 let command = data.map(|ranges| {
1101 let locations: Vec<lsp_types::Location> =
1102 ranges.into_iter().filter_map(|range| location(snap, range).ok()).collect();
1104 command::show_references(
1105 reference_title(locations.len()),
1112 acc.push(lsp_types::CodeLens {
1113 range: annotation_range,
1115 data: Some(to_value(lsp_ext::CodeLensResolveData::References(doc_pos)).unwrap()),
1122 pub(crate) mod command {
1123 use ide::{FileRange, NavigationTarget};
1124 use serde_json::to_value;
1127 global_state::GlobalStateSnapshot,
1129 to_proto::{location, location_link},
1132 pub(crate) fn show_references(
1134 uri: &lsp_types::Url,
1135 position: lsp_types::Position,
1136 locations: Vec<lsp_types::Location>,
1137 ) -> lsp_types::Command {
1138 // We cannot use the 'editor.action.showReferences' command directly
1139 // because that command requires vscode types which we convert in the handler
1140 // on the client side.
1142 lsp_types::Command {
1144 command: "rust-analyzer.showReferences".into(),
1145 arguments: Some(vec![
1146 to_value(uri).unwrap(),
1147 to_value(position).unwrap(),
1148 to_value(locations).unwrap(),
1153 pub(crate) fn run_single(runnable: &lsp_ext::Runnable, title: &str) -> lsp_types::Command {
1154 lsp_types::Command {
1155 title: title.to_string(),
1156 command: "rust-analyzer.runSingle".into(),
1157 arguments: Some(vec![to_value(runnable).unwrap()]),
1161 pub(crate) fn debug_single(runnable: &lsp_ext::Runnable) -> lsp_types::Command {
1162 lsp_types::Command {
1163 title: "Debug".into(),
1164 command: "rust-analyzer.debugSingle".into(),
1165 arguments: Some(vec![to_value(runnable).unwrap()]),
1169 pub(crate) fn goto_location(
1170 snap: &GlobalStateSnapshot,
1171 nav: &NavigationTarget,
1172 ) -> Option<lsp_types::Command> {
1173 let value = if snap.config.location_link() {
1174 let link = location_link(snap, None, nav.clone()).ok()?;
1175 to_value(link).ok()?
1177 let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1178 let location = location(snap, range).ok()?;
1179 to_value(location).ok()?
1182 Some(lsp_types::Command {
1183 title: nav.name.to_string(),
1184 command: "rust-analyzer.gotoLocation".into(),
1185 arguments: Some(vec![value]),
1189 pub(crate) fn trigger_parameter_hints() -> lsp_types::Command {
1190 lsp_types::Command {
1191 title: "triggerParameterHints".into(),
1192 command: "editor.action.triggerParameterHints".into(),
1198 pub(crate) fn implementation_title(count: usize) -> String {
1200 "1 implementation".into()
1202 format!("{} implementations", count)
1206 pub(crate) fn reference_title(count: usize) -> String {
1208 "1 reference".into()
1210 format!("{} references", count)
1214 pub(crate) fn markup_content(
1216 kind: ide::HoverDocFormat,
1217 ) -> lsp_types::MarkupContent {
1218 let kind = match kind {
1219 ide::HoverDocFormat::Markdown => lsp_types::MarkupKind::Markdown,
1220 ide::HoverDocFormat::PlainText => lsp_types::MarkupKind::PlainText,
1222 let value = crate::markdown::format_docs(markup.as_str());
1223 lsp_types::MarkupContent { kind, value }
1226 pub(crate) fn rename_error(err: RenameError) -> crate::LspError {
1227 // This is wrong, but we don't have a better alternative I suppose?
1228 // https://github.com/microsoft/language-server-protocol/issues/1341
1229 invalid_params_error(err.to_string())
1241 fn conv_fold_line_folding_only_fixup() {
1242 let text = r#"mod a;
1254 let (analysis, file_id) = Analysis::from_single_file(text.to_string());
1255 let folds = analysis.folding_ranges(file_id).unwrap();
1256 assert_eq!(folds.len(), 4);
1258 let line_index = LineIndex {
1259 index: Arc::new(ide::LineIndex::new(text)),
1260 endings: LineEndings::Unix,
1261 encoding: OffsetEncoding::Utf16,
1263 let converted: Vec<lsp_types::FoldingRange> =
1264 folds.into_iter().map(|it| folding_range(text, &line_index, true, it)).collect();
1266 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
1267 assert_eq!(converted.len(), expected_lines.len());
1268 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
1269 assert_eq!(folding_range.start_line, *start_line);
1270 assert_eq!(folding_range.start_character, None);
1271 assert_eq!(folding_range.end_line, *end_line);
1272 assert_eq!(folding_range.end_character, None);
1276 // `Url` is not able to parse windows paths on unix machines.
1278 #[cfg(target_os = "windows")]
1279 fn test_lowercase_drive_letter() {
1280 use std::{convert::TryInto, path::Path};
1282 let url = url_from_abs_path(Path::new("C:\\Test").try_into().unwrap());
1283 assert_eq!(url.to_string(), "file:///c:/Test");
1285 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#).try_into().unwrap());
1286 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");