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,
542 HlPunct::MacroBang => semantic_tokens::MACRO_BANG,
546 for modifier in highlight.mods.iter() {
547 let modifier = match modifier {
548 HlMod::Associated => continue,
549 HlMod::Async => semantic_tokens::ASYNC,
550 HlMod::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
551 HlMod::Callable => semantic_tokens::CALLABLE,
552 HlMod::Consuming => semantic_tokens::CONSUMING,
553 HlMod::ControlFlow => semantic_tokens::CONTROL_FLOW,
554 HlMod::CrateRoot => semantic_tokens::CRATE_ROOT,
555 HlMod::DefaultLibrary => lsp_types::SemanticTokenModifier::DEFAULT_LIBRARY,
556 HlMod::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
557 HlMod::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
558 HlMod::Injected => semantic_tokens::INJECTED,
559 HlMod::IntraDocLink => semantic_tokens::INTRA_DOC_LINK,
560 HlMod::Library => semantic_tokens::LIBRARY,
561 HlMod::Mutable => semantic_tokens::MUTABLE,
562 HlMod::Public => semantic_tokens::PUBLIC,
563 HlMod::Reference => semantic_tokens::REFERENCE,
564 HlMod::Static => lsp_types::SemanticTokenModifier::STATIC,
565 HlMod::Trait => semantic_tokens::TRAIT_MODIFIER,
566 HlMod::Unsafe => semantic_tokens::UNSAFE,
574 pub(crate) fn folding_range(
576 line_index: &LineIndex,
577 line_folding_only: bool,
579 ) -> lsp_types::FoldingRange {
580 let kind = match fold.kind {
581 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
582 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
583 FoldKind::Region => Some(lsp_types::FoldingRangeKind::Region),
589 | FoldKind::WhereClause
590 | FoldKind::ReturnType
591 | FoldKind::Array => None,
594 let range = range(line_index, fold.range);
596 if line_folding_only {
597 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
598 // even if it contains text not in the folding range. To prevent that we exclude
599 // range.end.line from the folding region if there is more text after range.end
601 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
603 .take_while(|it| *it != '\n')
604 .any(|it| !it.is_whitespace());
606 let end_line = if has_more_text_on_end_line {
607 range.end.line.saturating_sub(1)
612 lsp_types::FoldingRange {
613 start_line: range.start.line,
614 start_character: None,
620 lsp_types::FoldingRange {
621 start_line: range.start.line,
622 start_character: Some(range.start.character),
623 end_line: range.end.line,
624 end_character: Some(range.end.character),
630 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
631 snap.file_id_to_url(file_id)
634 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
635 /// This will only happen when processing windows paths.
637 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
638 pub(crate) fn url_from_abs_path(path: &AbsPath) -> lsp_types::Url {
639 let url = lsp_types::Url::from_file_path(path).unwrap();
640 match path.as_ref().components().next() {
641 Some(path::Component::Prefix(prefix))
642 if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
644 // Need to lowercase driver letter
649 let driver_letter_range = {
650 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
654 let start = scheme.len() + ':'.len_utf8();
655 start..(start + drive_letter.len())
658 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
659 // machinery *also* canonicalizes the drive letter. So, just massage the
661 let mut url: String = url.into();
662 url[driver_letter_range].make_ascii_lowercase();
663 lsp_types::Url::parse(&url).unwrap()
666 pub(crate) fn optional_versioned_text_document_identifier(
667 snap: &GlobalStateSnapshot,
669 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
670 let url = url(snap, file_id);
671 let version = snap.url_file_version(&url);
672 lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
675 pub(crate) fn location(
676 snap: &GlobalStateSnapshot,
678 ) -> Result<lsp_types::Location> {
679 let url = url(snap, frange.file_id);
680 let line_index = snap.file_line_index(frange.file_id)?;
681 let range = range(&line_index, frange.range);
682 let loc = lsp_types::Location::new(url, range);
686 /// Prefer using `location_link`, if the client has the cap.
687 pub(crate) fn location_from_nav(
688 snap: &GlobalStateSnapshot,
689 nav: NavigationTarget,
690 ) -> Result<lsp_types::Location> {
691 let url = url(snap, nav.file_id);
692 let line_index = snap.file_line_index(nav.file_id)?;
693 let range = range(&line_index, nav.full_range);
694 let loc = lsp_types::Location::new(url, range);
698 pub(crate) fn location_link(
699 snap: &GlobalStateSnapshot,
700 src: Option<FileRange>,
701 target: NavigationTarget,
702 ) -> Result<lsp_types::LocationLink> {
703 let origin_selection_range = match src {
705 let line_index = snap.file_line_index(src.file_id)?;
706 let range = range(&line_index, src.range);
711 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
712 let res = lsp_types::LocationLink {
713 origin_selection_range,
716 target_selection_range,
722 snap: &GlobalStateSnapshot,
723 target: NavigationTarget,
724 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
725 let line_index = snap.file_line_index(target.file_id)?;
727 let target_uri = url(snap, target.file_id);
728 let target_range = range(&line_index, target.full_range);
729 let target_selection_range =
730 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
731 Ok((target_uri, target_range, target_selection_range))
734 pub(crate) fn goto_definition_response(
735 snap: &GlobalStateSnapshot,
736 src: Option<FileRange>,
737 targets: Vec<NavigationTarget>,
738 ) -> Result<lsp_types::GotoDefinitionResponse> {
739 if snap.config.location_link() {
742 .map(|nav| location_link(snap, src, nav))
743 .collect::<Result<Vec<_>>>()?;
746 let locations = targets
749 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
751 .collect::<Result<Vec<_>>>()?;
756 fn outside_workspace_annotation_id() -> String {
757 String::from("OutsideWorkspace")
760 pub(crate) fn snippet_text_document_edit(
761 snap: &GlobalStateSnapshot,
765 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
766 let text_document = optional_versioned_text_document_identifier(snap, file_id);
767 let line_index = snap.file_line_index(file_id)?;
768 let mut edits: Vec<_> =
769 edit.into_iter().map(|it| snippet_text_edit(&line_index, is_snippet, it)).collect();
771 if snap.analysis.is_library_file(file_id)? && snap.config.change_annotation_support() {
772 for edit in &mut edits {
773 edit.annotation_id = Some(outside_workspace_annotation_id())
776 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
779 pub(crate) fn snippet_text_document_ops(
780 snap: &GlobalStateSnapshot,
781 file_system_edit: FileSystemEdit,
782 ) -> Cancellable<Vec<lsp_ext::SnippetDocumentChangeOperation>> {
783 let mut ops = Vec::new();
784 match file_system_edit {
785 FileSystemEdit::CreateFile { dst, initial_contents } => {
786 let uri = snap.anchored_path(&dst);
787 let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
792 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
793 if !initial_contents.is_empty() {
795 lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
796 let text_edit = lsp_ext::SnippetTextEdit {
797 range: lsp_types::Range::default(),
798 new_text: initial_contents,
799 insert_text_format: Some(lsp_types::InsertTextFormat::PLAIN_TEXT),
803 lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
804 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
807 FileSystemEdit::MoveFile { src, dst } => {
808 let old_uri = snap.file_id_to_url(src);
809 let new_uri = snap.anchored_path(&dst);
810 let mut rename_file =
811 lsp_types::RenameFile { old_uri, new_uri, options: None, annotation_id: None };
812 if snap.analysis.is_library_file(src).ok() == Some(true)
813 && snap.config.change_annotation_support()
815 rename_file.annotation_id = Some(outside_workspace_annotation_id())
817 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(lsp_types::ResourceOp::Rename(
825 pub(crate) fn snippet_workspace_edit(
826 snap: &GlobalStateSnapshot,
827 source_change: SourceChange,
828 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
829 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
831 for op in source_change.file_system_edits {
832 let ops = snippet_text_document_ops(snap, op)?;
833 document_changes.extend_from_slice(&ops);
835 for (file_id, edit) in source_change.source_file_edits {
836 let edit = snippet_text_document_edit(snap, source_change.is_snippet, file_id, edit)?;
837 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
839 let mut workspace_edit = lsp_ext::SnippetWorkspaceEdit {
841 document_changes: Some(document_changes),
842 change_annotations: None,
844 if snap.config.change_annotation_support() {
845 workspace_edit.change_annotations = Some(
847 outside_workspace_annotation_id(),
848 lsp_types::ChangeAnnotation {
849 label: String::from("Edit outside of the workspace"),
850 needs_confirmation: Some(true),
851 description: Some(String::from(
852 "This edit lies outside of the workspace and may affect dependencies",
862 pub(crate) fn workspace_edit(
863 snap: &GlobalStateSnapshot,
864 source_change: SourceChange,
865 ) -> Result<lsp_types::WorkspaceEdit> {
866 assert!(!source_change.is_snippet);
867 snippet_workspace_edit(snap, source_change).map(|it| it.into())
870 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
871 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
872 lsp_types::WorkspaceEdit {
874 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
875 lsp_types::DocumentChanges::Operations(
878 .map(|change| match change {
879 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
880 lsp_types::DocumentChangeOperation::Op(op)
882 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
883 lsp_types::DocumentChangeOperation::Edit(
884 lsp_types::TextDocumentEdit {
885 text_document: edit.text_document,
886 edits: edit.edits.into_iter().map(From::from).collect(),
894 change_annotations: snippet_workspace_edit.change_annotations,
899 impl From<lsp_ext::SnippetTextEdit>
900 for lsp_types::OneOf<lsp_types::TextEdit, lsp_types::AnnotatedTextEdit>
903 lsp_ext::SnippetTextEdit { annotation_id, insert_text_format:_, new_text, range }: lsp_ext::SnippetTextEdit,
905 match annotation_id {
906 Some(annotation_id) => lsp_types::OneOf::Right(lsp_types::AnnotatedTextEdit {
907 text_edit: lsp_types::TextEdit { range, new_text },
910 None => lsp_types::OneOf::Left(lsp_types::TextEdit { range, new_text }),
915 pub(crate) fn call_hierarchy_item(
916 snap: &GlobalStateSnapshot,
917 target: NavigationTarget,
918 ) -> Result<lsp_types::CallHierarchyItem> {
919 let name = target.name.to_string();
920 let detail = target.description.clone();
921 let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::FUNCTION);
922 let (uri, range, selection_range) = location_info(snap, target)?;
923 Ok(lsp_types::CallHierarchyItem {
935 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
937 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
938 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
939 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
940 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
941 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
942 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
946 pub(crate) fn code_action(
947 snap: &GlobalStateSnapshot,
949 resolve_data: Option<(usize, lsp_types::CodeActionParams)>,
950 ) -> Result<lsp_ext::CodeAction> {
951 let mut res = lsp_ext::CodeAction {
952 title: assist.label.to_string(),
953 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
954 kind: Some(code_action_kind(assist.id.1)),
959 match (assist.source_change, resolve_data) {
960 (Some(it), _) => res.edit = Some(snippet_workspace_edit(snap, it)?),
961 (None, Some((index, code_action_params))) => {
962 res.data = Some(lsp_ext::CodeActionData {
963 id: format!("{}:{}:{}", assist.id.0, assist.id.1.name(), index),
968 stdx::never!("assist should always be resolved if client can't do lazy resolving")
974 pub(crate) fn runnable(
975 snap: &GlobalStateSnapshot,
977 ) -> Result<lsp_ext::Runnable> {
978 let config = snap.config.runnables();
979 let spec = CargoTargetSpec::for_file(snap, runnable.nav.file_id)?;
980 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
981 let target = spec.as_ref().map(|s| s.target.clone());
982 let (cargo_args, executable_args) =
983 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
984 let label = runnable.label(target);
985 let location = location_link(snap, None, runnable.nav)?;
987 Ok(lsp_ext::Runnable {
989 location: Some(location),
990 kind: lsp_ext::RunnableKind::Cargo,
991 args: lsp_ext::CargoRunnable {
992 workspace_root: workspace_root.map(|it| it.into()),
993 override_cargo: config.override_cargo,
995 cargo_extra_args: config.cargo_extra_args,
1002 pub(crate) fn code_lens(
1003 acc: &mut Vec<lsp_types::CodeLens>,
1004 snap: &GlobalStateSnapshot,
1005 annotation: Annotation,
1007 let client_commands_config = snap.config.client_commands();
1008 match annotation.kind {
1009 AnnotationKind::Runnable(run) => {
1010 let line_index = snap.file_line_index(run.nav.file_id)?;
1011 let annotation_range = range(&line_index, annotation.range);
1013 let title = run.title();
1014 let can_debug = match run.kind {
1015 ide::RunnableKind::DocTest { .. } => false,
1016 ide::RunnableKind::TestMod { .. }
1017 | ide::RunnableKind::Test { .. }
1018 | ide::RunnableKind::Bench { .. }
1019 | ide::RunnableKind::Bin => true,
1021 let r = runnable(snap, run)?;
1023 let lens_config = snap.config.lens();
1024 if lens_config.run && client_commands_config.run_single {
1025 let command = command::run_single(&r, &title);
1026 acc.push(lsp_types::CodeLens {
1027 range: annotation_range,
1028 command: Some(command),
1032 if lens_config.debug && can_debug && client_commands_config.debug_single {
1033 let command = command::debug_single(&r);
1034 acc.push(lsp_types::CodeLens {
1035 range: annotation_range,
1036 command: Some(command),
1041 AnnotationKind::HasImpls { position: file_position, data } => {
1042 if !client_commands_config.show_reference {
1045 let line_index = snap.file_line_index(file_position.file_id)?;
1046 let annotation_range = range(&line_index, annotation.range);
1047 let url = url(snap, file_position.file_id);
1049 let position = position(&line_index, file_position.offset);
1051 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1053 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
1055 let goto_params = lsp_types::request::GotoImplementationParams {
1056 text_document_position_params: doc_pos,
1057 work_done_progress_params: Default::default(),
1058 partial_result_params: Default::default(),
1061 let command = data.map(|ranges| {
1062 let locations: Vec<lsp_types::Location> = ranges
1064 .filter_map(|target| {
1067 FileRange { file_id: target.file_id, range: target.full_range },
1073 command::show_references(
1074 implementation_title(locations.len()),
1081 acc.push(lsp_types::CodeLens {
1082 range: annotation_range,
1084 data: Some(to_value(lsp_ext::CodeLensResolveData::Impls(goto_params)).unwrap()),
1087 AnnotationKind::HasReferences { position: file_position, data } => {
1088 if !client_commands_config.show_reference {
1091 let line_index = snap.file_line_index(file_position.file_id)?;
1092 let annotation_range = range(&line_index, annotation.range);
1093 let url = url(snap, file_position.file_id);
1095 let position = position(&line_index, file_position.offset);
1097 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1099 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
1101 let command = data.map(|ranges| {
1102 let locations: Vec<lsp_types::Location> =
1103 ranges.into_iter().filter_map(|range| location(snap, range).ok()).collect();
1105 command::show_references(
1106 reference_title(locations.len()),
1113 acc.push(lsp_types::CodeLens {
1114 range: annotation_range,
1116 data: Some(to_value(lsp_ext::CodeLensResolveData::References(doc_pos)).unwrap()),
1123 pub(crate) mod command {
1124 use ide::{FileRange, NavigationTarget};
1125 use serde_json::to_value;
1128 global_state::GlobalStateSnapshot,
1130 to_proto::{location, location_link},
1133 pub(crate) fn show_references(
1135 uri: &lsp_types::Url,
1136 position: lsp_types::Position,
1137 locations: Vec<lsp_types::Location>,
1138 ) -> lsp_types::Command {
1139 // We cannot use the 'editor.action.showReferences' command directly
1140 // because that command requires vscode types which we convert in the handler
1141 // on the client side.
1143 lsp_types::Command {
1145 command: "rust-analyzer.showReferences".into(),
1146 arguments: Some(vec![
1147 to_value(uri).unwrap(),
1148 to_value(position).unwrap(),
1149 to_value(locations).unwrap(),
1154 pub(crate) fn run_single(runnable: &lsp_ext::Runnable, title: &str) -> lsp_types::Command {
1155 lsp_types::Command {
1156 title: title.to_string(),
1157 command: "rust-analyzer.runSingle".into(),
1158 arguments: Some(vec![to_value(runnable).unwrap()]),
1162 pub(crate) fn debug_single(runnable: &lsp_ext::Runnable) -> lsp_types::Command {
1163 lsp_types::Command {
1164 title: "Debug".into(),
1165 command: "rust-analyzer.debugSingle".into(),
1166 arguments: Some(vec![to_value(runnable).unwrap()]),
1170 pub(crate) fn goto_location(
1171 snap: &GlobalStateSnapshot,
1172 nav: &NavigationTarget,
1173 ) -> Option<lsp_types::Command> {
1174 let value = if snap.config.location_link() {
1175 let link = location_link(snap, None, nav.clone()).ok()?;
1176 to_value(link).ok()?
1178 let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1179 let location = location(snap, range).ok()?;
1180 to_value(location).ok()?
1183 Some(lsp_types::Command {
1184 title: nav.name.to_string(),
1185 command: "rust-analyzer.gotoLocation".into(),
1186 arguments: Some(vec![value]),
1190 pub(crate) fn trigger_parameter_hints() -> lsp_types::Command {
1191 lsp_types::Command {
1192 title: "triggerParameterHints".into(),
1193 command: "editor.action.triggerParameterHints".into(),
1199 pub(crate) fn implementation_title(count: usize) -> String {
1201 "1 implementation".into()
1203 format!("{} implementations", count)
1207 pub(crate) fn reference_title(count: usize) -> String {
1209 "1 reference".into()
1211 format!("{} references", count)
1215 pub(crate) fn markup_content(
1217 kind: ide::HoverDocFormat,
1218 ) -> lsp_types::MarkupContent {
1219 let kind = match kind {
1220 ide::HoverDocFormat::Markdown => lsp_types::MarkupKind::Markdown,
1221 ide::HoverDocFormat::PlainText => lsp_types::MarkupKind::PlainText,
1223 let value = crate::markdown::format_docs(markup.as_str());
1224 lsp_types::MarkupContent { kind, value }
1227 pub(crate) fn rename_error(err: RenameError) -> crate::LspError {
1228 // This is wrong, but we don't have a better alternative I suppose?
1229 // https://github.com/microsoft/language-server-protocol/issues/1341
1230 invalid_params_error(err.to_string())
1242 fn conv_fold_line_folding_only_fixup() {
1243 let text = r#"mod a;
1255 let (analysis, file_id) = Analysis::from_single_file(text.to_string());
1256 let folds = analysis.folding_ranges(file_id).unwrap();
1257 assert_eq!(folds.len(), 4);
1259 let line_index = LineIndex {
1260 index: Arc::new(ide::LineIndex::new(text)),
1261 endings: LineEndings::Unix,
1262 encoding: OffsetEncoding::Utf16,
1264 let converted: Vec<lsp_types::FoldingRange> =
1265 folds.into_iter().map(|it| folding_range(text, &line_index, true, it)).collect();
1267 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
1268 assert_eq!(converted.len(), expected_lines.len());
1269 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
1270 assert_eq!(folding_range.start_line, *start_line);
1271 assert_eq!(folding_range.start_character, None);
1272 assert_eq!(folding_range.end_line, *end_line);
1273 assert_eq!(folding_range.end_character, None);
1277 // `Url` is not able to parse windows paths on unix machines.
1279 #[cfg(target_os = "windows")]
1280 fn test_lowercase_drive_letter() {
1281 use std::{convert::TryInto, path::Path};
1283 let url = url_from_abs_path(Path::new("C:\\Test").try_into().unwrap());
1284 assert_eq!(url.to_string(), "file:///c:/Test");
1286 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#).try_into().unwrap());
1287 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");