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 | SymbolKind::SelfType => {
59 lsp_types::SymbolKind::TYPE_PARAMETER
61 SymbolKind::Field => lsp_types::SymbolKind::FIELD,
62 SymbolKind::Static => lsp_types::SymbolKind::CONSTANT,
63 SymbolKind::Const => lsp_types::SymbolKind::CONSTANT,
64 SymbolKind::ConstParam => lsp_types::SymbolKind::CONSTANT,
65 SymbolKind::Impl => lsp_types::SymbolKind::OBJECT,
67 | SymbolKind::SelfParam
68 | SymbolKind::LifetimeParam
69 | SymbolKind::ValueParam
70 | SymbolKind::Label => lsp_types::SymbolKind::VARIABLE,
71 SymbolKind::Union => lsp_types::SymbolKind::STRUCT,
75 pub(crate) fn structure_node_kind(kind: StructureNodeKind) -> lsp_types::SymbolKind {
77 StructureNodeKind::SymbolKind(symbol) => symbol_kind(symbol),
78 StructureNodeKind::Region => lsp_types::SymbolKind::NAMESPACE,
82 pub(crate) fn document_highlight_kind(
83 category: ReferenceCategory,
84 ) -> lsp_types::DocumentHighlightKind {
86 ReferenceCategory::Read => lsp_types::DocumentHighlightKind::READ,
87 ReferenceCategory::Write => lsp_types::DocumentHighlightKind::WRITE,
91 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
93 Severity::Error => lsp_types::DiagnosticSeverity::ERROR,
94 Severity::WeakWarning => lsp_types::DiagnosticSeverity::HINT,
98 pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
99 let value = crate::markdown::format_docs(documentation.as_str());
100 let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
101 lsp_types::Documentation::MarkupContent(markup_content)
104 pub(crate) fn completion_item_kind(
105 completion_item_kind: CompletionItemKind,
106 ) -> lsp_types::CompletionItemKind {
107 match completion_item_kind {
108 CompletionItemKind::Binding => lsp_types::CompletionItemKind::VARIABLE,
109 CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::STRUCT,
110 CompletionItemKind::Keyword => lsp_types::CompletionItemKind::KEYWORD,
111 CompletionItemKind::Method => lsp_types::CompletionItemKind::METHOD,
112 CompletionItemKind::Snippet => lsp_types::CompletionItemKind::SNIPPET,
113 CompletionItemKind::UnresolvedReference => lsp_types::CompletionItemKind::REFERENCE,
114 CompletionItemKind::SymbolKind(symbol) => match symbol {
115 SymbolKind::Attribute => lsp_types::CompletionItemKind::FUNCTION,
116 SymbolKind::Const => lsp_types::CompletionItemKind::CONSTANT,
117 SymbolKind::ConstParam => lsp_types::CompletionItemKind::TYPE_PARAMETER,
118 SymbolKind::Derive => lsp_types::CompletionItemKind::FUNCTION,
119 SymbolKind::Enum => lsp_types::CompletionItemKind::ENUM,
120 SymbolKind::Field => lsp_types::CompletionItemKind::FIELD,
121 SymbolKind::Function => lsp_types::CompletionItemKind::FUNCTION,
122 SymbolKind::Impl => lsp_types::CompletionItemKind::TEXT,
123 SymbolKind::Label => lsp_types::CompletionItemKind::VARIABLE,
124 SymbolKind::LifetimeParam => lsp_types::CompletionItemKind::TYPE_PARAMETER,
125 SymbolKind::Local => lsp_types::CompletionItemKind::VARIABLE,
126 SymbolKind::Macro => lsp_types::CompletionItemKind::FUNCTION,
127 SymbolKind::Module => lsp_types::CompletionItemKind::MODULE,
128 SymbolKind::SelfParam => lsp_types::CompletionItemKind::VALUE,
129 SymbolKind::SelfType => lsp_types::CompletionItemKind::TYPE_PARAMETER,
130 SymbolKind::Static => lsp_types::CompletionItemKind::VALUE,
131 SymbolKind::Struct => lsp_types::CompletionItemKind::STRUCT,
132 SymbolKind::Trait => lsp_types::CompletionItemKind::INTERFACE,
133 SymbolKind::TypeAlias => lsp_types::CompletionItemKind::STRUCT,
134 SymbolKind::TypeParam => lsp_types::CompletionItemKind::TYPE_PARAMETER,
135 SymbolKind::Union => lsp_types::CompletionItemKind::STRUCT,
136 SymbolKind::ValueParam => lsp_types::CompletionItemKind::VALUE,
137 SymbolKind::Variant => lsp_types::CompletionItemKind::ENUM_MEMBER,
138 SymbolKind::BuiltinAttr => lsp_types::CompletionItemKind::FUNCTION,
139 SymbolKind::ToolModule => lsp_types::CompletionItemKind::MODULE,
144 pub(crate) fn text_edit(line_index: &LineIndex, indel: Indel) -> lsp_types::TextEdit {
145 let range = range(line_index, indel.delete);
146 let new_text = match line_index.endings {
147 LineEndings::Unix => indel.insert,
148 LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
150 lsp_types::TextEdit { range, new_text }
153 pub(crate) fn completion_text_edit(
154 line_index: &LineIndex,
155 insert_replace_support: Option<lsp_types::Position>,
157 ) -> lsp_types::CompletionTextEdit {
158 let text_edit = text_edit(line_index, indel);
159 match insert_replace_support {
160 Some(cursor_pos) => lsp_types::InsertReplaceEdit {
161 new_text: text_edit.new_text,
162 insert: lsp_types::Range { start: text_edit.range.start, end: cursor_pos },
163 replace: text_edit.range,
166 None => text_edit.into(),
170 pub(crate) fn snippet_text_edit(
171 line_index: &LineIndex,
174 ) -> lsp_ext::SnippetTextEdit {
175 let text_edit = text_edit(line_index, indel);
176 let insert_text_format =
177 if is_snippet { Some(lsp_types::InsertTextFormat::SNIPPET) } else { None };
178 lsp_ext::SnippetTextEdit {
179 range: text_edit.range,
180 new_text: text_edit.new_text,
186 pub(crate) fn text_edit_vec(
187 line_index: &LineIndex,
189 ) -> Vec<lsp_types::TextEdit> {
190 text_edit.into_iter().map(|indel| self::text_edit(line_index, indel)).collect()
193 pub(crate) fn snippet_text_edit_vec(
194 line_index: &LineIndex,
197 ) -> Vec<lsp_ext::SnippetTextEdit> {
200 .map(|indel| self::snippet_text_edit(line_index, is_snippet, indel))
204 pub(crate) fn completion_items(
206 line_index: &LineIndex,
207 tdpp: lsp_types::TextDocumentPositionParams,
208 items: Vec<CompletionItem>,
209 ) -> Vec<lsp_types::CompletionItem> {
210 let max_relevance = items.iter().map(|it| it.relevance().score()).max().unwrap_or_default();
211 let mut res = Vec::with_capacity(items.len());
213 completion_item(&mut res, config, line_index, &tdpp, max_relevance, item)
219 acc: &mut Vec<lsp_types::CompletionItem>,
221 line_index: &LineIndex,
222 tdpp: &lsp_types::TextDocumentPositionParams,
224 item: CompletionItem,
226 let mut additional_text_edits = Vec::new();
228 // LSP does not allow arbitrary edits in completion, so we have to do a
229 // non-trivial mapping here.
231 let mut text_edit = None;
232 let source_range = item.source_range();
233 for indel in item.text_edit().iter() {
234 if indel.delete.contains_range(source_range) {
235 let insert_replace_support = config.insert_replace_support().then(|| tdpp.position);
236 text_edit = Some(if indel.delete == source_range {
237 self::completion_text_edit(line_index, insert_replace_support, indel.clone())
239 assert!(source_range.end() == indel.delete.end());
240 let range1 = TextRange::new(indel.delete.start(), source_range.start());
241 let range2 = source_range;
242 let indel1 = Indel::replace(range1, String::new());
243 let indel2 = Indel::replace(range2, indel.insert.clone());
244 additional_text_edits.push(self::text_edit(line_index, indel1));
245 self::completion_text_edit(line_index, insert_replace_support, indel2)
248 assert!(source_range.intersect(indel.delete).is_none());
249 let text_edit = self::text_edit(line_index, indel.clone());
250 additional_text_edits.push(text_edit);
256 let mut lsp_item = lsp_types::CompletionItem {
257 label: item.label().to_string(),
258 detail: item.detail().map(|it| it.to_string()),
259 filter_text: Some(item.lookup().to_string()),
260 kind: Some(completion_item_kind(item.kind())),
261 text_edit: Some(text_edit),
262 additional_text_edits: Some(additional_text_edits),
263 documentation: item.documentation().map(documentation),
264 deprecated: Some(item.deprecated()),
268 set_score(&mut lsp_item, max_relevance, item.relevance());
270 if item.deprecated() {
271 lsp_item.tags = Some(vec![lsp_types::CompletionItemTag::DEPRECATED])
274 if item.trigger_call_info() && config.client_commands().trigger_parameter_hints {
275 lsp_item.command = Some(command::trigger_parameter_hints());
278 if item.is_snippet() {
279 lsp_item.insert_text_format = Some(lsp_types::InsertTextFormat::SNIPPET);
281 if config.completion().enable_imports_on_the_fly {
282 if let imports @ [_, ..] = item.imports_to_add() {
283 let imports: Vec<_> = imports
285 .filter_map(|import_edit| {
286 let import_path = &import_edit.import.import_path;
287 let import_name = import_path.segments().last()?;
288 Some(lsp_ext::CompletionImport {
289 full_import_path: import_path.to_string(),
290 imported_name: import_name.to_string(),
294 if !imports.is_empty() {
295 let data = lsp_ext::CompletionResolveData { position: tdpp.clone(), imports };
296 lsp_item.data = Some(to_value(data).unwrap());
301 if let Some((mutability, relevance)) = item.ref_match() {
302 let mut lsp_item_with_ref = lsp_item.clone();
303 set_score(&mut lsp_item_with_ref, max_relevance, relevance);
304 lsp_item_with_ref.label =
305 format!("&{}{}", mutability.as_keyword_for_ref(), lsp_item_with_ref.label);
306 if let Some(it) = &mut lsp_item_with_ref.text_edit {
307 let new_text = match it {
308 lsp_types::CompletionTextEdit::Edit(it) => &mut it.new_text,
309 lsp_types::CompletionTextEdit::InsertAndReplace(it) => &mut it.new_text,
311 *new_text = format!("&{}{}", mutability.as_keyword_for_ref(), new_text);
314 acc.push(lsp_item_with_ref);
320 res: &mut lsp_types::CompletionItem,
322 relevance: CompletionRelevance,
324 if relevance.is_relevant() && relevance.score() == max_relevance {
325 res.preselect = Some(true);
327 // The relevance needs to be inverted to come up with a sort score
328 // because the client will sort ascending.
329 let sort_score = relevance.score() ^ 0xFF_FF_FF_FF;
330 // Zero pad the string to ensure values can be properly sorted
331 // by the client. Hex format is used because it is easier to
332 // visually compare very large values, which the sort text
333 // tends to be since it is the opposite of the score.
334 res.sort_text = Some(format!("{:08x}", sort_score));
338 pub(crate) fn signature_help(
342 ) -> lsp_types::SignatureHelp {
343 let (label, parameters) = match (concise, label_offsets) {
345 let params = call_info
347 .map(|label| lsp_types::ParameterInformation {
348 label: lsp_types::ParameterLabel::Simple(label.to_string()),
351 .collect::<Vec<_>>();
353 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
357 let params = call_info
360 .map(|it| [u32::from(it.start()), u32::from(it.end())])
361 .map(|label_offsets| lsp_types::ParameterInformation {
362 label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
365 .collect::<Vec<_>>();
366 (call_info.signature, params)
369 let mut params = Vec::new();
370 let mut label = String::new();
371 let mut first = true;
372 for param in call_info.parameter_labels() {
374 label.push_str(", ");
377 let start = label.len() as u32;
378 label.push_str(param);
379 let end = label.len() as u32;
380 params.push(lsp_types::ParameterInformation {
381 label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
390 let documentation = if concise {
393 call_info.doc.map(|doc| {
394 lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
395 kind: lsp_types::MarkupKind::Markdown,
401 let active_parameter = call_info.active_parameter.map(|it| it as u32);
403 let signature = lsp_types::SignatureInformation {
406 parameters: Some(parameters),
409 lsp_types::SignatureHelp {
410 signatures: vec![signature],
411 active_signature: Some(0),
416 pub(crate) fn inlay_hint(
418 line_index: &LineIndex,
419 inlay_hint: InlayHint,
420 ) -> lsp_ext::InlayHint {
422 label: lsp_ext::InlayHintLabel::String(match inlay_hint.kind {
423 InlayKind::ParameterHint if render_colons => format!("{}:", inlay_hint.label),
424 InlayKind::TypeHint if render_colons => format!(": {}", inlay_hint.label),
425 _ => inlay_hint.label.to_string(),
427 position: match inlay_hint.kind {
428 InlayKind::ParameterHint => position(line_index, inlay_hint.range.start()),
429 InlayKind::TypeHint | InlayKind::ChainingHint => {
430 position(line_index, inlay_hint.range.end())
433 kind: match inlay_hint.kind {
434 InlayKind::ParameterHint => Some(lsp_ext::InlayHintKind::PARAMETER),
435 InlayKind::TypeHint => Some(lsp_ext::InlayHintKind::TYPE),
436 InlayKind::ChainingHint => None,
439 padding_left: Some(match inlay_hint.kind {
440 InlayKind::TypeHint => !render_colons,
441 InlayKind::ParameterHint => false,
442 InlayKind::ChainingHint => true,
444 padding_right: Some(match inlay_hint.kind {
445 InlayKind::TypeHint | InlayKind::ChainingHint => false,
446 InlayKind::ParameterHint => true,
451 static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
453 pub(crate) fn semantic_tokens(
455 line_index: &LineIndex,
456 highlights: Vec<HlRange>,
457 highlight_strings: bool,
458 ) -> lsp_types::SemanticTokens {
459 let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
460 let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
462 for highlight_range in highlights {
463 if highlight_range.highlight.is_empty() {
466 let (ty, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
467 if !highlight_strings && ty == lsp_types::SemanticTokenType::STRING {
470 let token_index = semantic_tokens::type_index(ty);
471 let modifier_bitset = mods.0;
473 for mut text_range in line_index.index.lines(highlight_range.range) {
474 if text[text_range].ends_with('\n') {
476 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
478 let range = range(line_index, text_range);
479 builder.push(range, token_index, modifier_bitset);
486 pub(crate) fn semantic_token_delta(
487 previous: &lsp_types::SemanticTokens,
488 current: &lsp_types::SemanticTokens,
489 ) -> lsp_types::SemanticTokensDelta {
490 let result_id = current.result_id.clone();
491 let edits = semantic_tokens::diff_tokens(&previous.data, ¤t.data);
492 lsp_types::SemanticTokensDelta { result_id, edits }
495 fn semantic_token_type_and_modifiers(
496 highlight: Highlight,
497 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
498 let mut mods = semantic_tokens::ModifierSet::default();
499 let type_ = match highlight.tag {
500 HlTag::Symbol(symbol) => match symbol {
501 SymbolKind::Attribute => semantic_tokens::ATTRIBUTE,
502 SymbolKind::Derive => semantic_tokens::DERIVE,
503 SymbolKind::Module => lsp_types::SemanticTokenType::NAMESPACE,
504 SymbolKind::Impl => semantic_tokens::TYPE_ALIAS,
505 SymbolKind::Field => lsp_types::SemanticTokenType::PROPERTY,
506 SymbolKind::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
507 SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
508 SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
509 SymbolKind::Label => semantic_tokens::LABEL,
510 SymbolKind::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
511 SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
512 SymbolKind::SelfType => semantic_tokens::SELF_TYPE_KEYWORD,
513 SymbolKind::Local => lsp_types::SemanticTokenType::VARIABLE,
514 SymbolKind::Function => {
515 if highlight.mods.contains(HlMod::Associated) {
516 lsp_types::SemanticTokenType::METHOD
518 lsp_types::SemanticTokenType::FUNCTION
521 SymbolKind::Const => {
522 mods |= semantic_tokens::CONSTANT;
523 mods |= lsp_types::SemanticTokenModifier::STATIC;
524 lsp_types::SemanticTokenType::VARIABLE
526 SymbolKind::Static => {
527 mods |= lsp_types::SemanticTokenModifier::STATIC;
528 lsp_types::SemanticTokenType::VARIABLE
530 SymbolKind::Struct => lsp_types::SemanticTokenType::STRUCT,
531 SymbolKind::Enum => lsp_types::SemanticTokenType::ENUM,
532 SymbolKind::Variant => lsp_types::SemanticTokenType::ENUM_MEMBER,
533 SymbolKind::Union => semantic_tokens::UNION,
534 SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
535 SymbolKind::Trait => lsp_types::SemanticTokenType::INTERFACE,
536 SymbolKind::Macro => lsp_types::SemanticTokenType::MACRO,
537 SymbolKind::BuiltinAttr => semantic_tokens::BUILTIN_ATTRIBUTE,
538 SymbolKind::ToolModule => semantic_tokens::TOOL_MODULE,
540 HlTag::AttributeBracket => semantic_tokens::ATTRIBUTE_BRACKET,
541 HlTag::BoolLiteral => semantic_tokens::BOOLEAN,
542 HlTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
543 HlTag::ByteLiteral | HlTag::NumericLiteral => lsp_types::SemanticTokenType::NUMBER,
544 HlTag::CharLiteral => semantic_tokens::CHAR,
545 HlTag::Comment => lsp_types::SemanticTokenType::COMMENT,
546 HlTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
547 HlTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
548 HlTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
549 HlTag::None => semantic_tokens::GENERIC,
550 HlTag::Operator(op) => match op {
551 HlOperator::Bitwise => semantic_tokens::BITWISE,
552 HlOperator::Arithmetic => semantic_tokens::ARITHMETIC,
553 HlOperator::Logical => semantic_tokens::LOGICAL,
554 HlOperator::Comparison => semantic_tokens::COMPARISON,
555 HlOperator::Other => semantic_tokens::OPERATOR,
557 HlTag::StringLiteral => lsp_types::SemanticTokenType::STRING,
558 HlTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
559 HlTag::Punctuation(punct) => match punct {
560 HlPunct::Bracket => semantic_tokens::BRACKET,
561 HlPunct::Brace => semantic_tokens::BRACE,
562 HlPunct::Parenthesis => semantic_tokens::PARENTHESIS,
563 HlPunct::Angle => semantic_tokens::ANGLE,
564 HlPunct::Comma => semantic_tokens::COMMA,
565 HlPunct::Dot => semantic_tokens::DOT,
566 HlPunct::Colon => semantic_tokens::COLON,
567 HlPunct::Semi => semantic_tokens::SEMICOLON,
568 HlPunct::Other => semantic_tokens::PUNCTUATION,
569 HlPunct::MacroBang => semantic_tokens::MACRO_BANG,
573 for modifier in highlight.mods.iter() {
574 let modifier = match modifier {
575 HlMod::Associated => continue,
576 HlMod::Async => semantic_tokens::ASYNC,
577 HlMod::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
578 HlMod::Callable => semantic_tokens::CALLABLE,
579 HlMod::Consuming => semantic_tokens::CONSUMING,
580 HlMod::ControlFlow => semantic_tokens::CONTROL_FLOW,
581 HlMod::CrateRoot => semantic_tokens::CRATE_ROOT,
582 HlMod::DefaultLibrary => lsp_types::SemanticTokenModifier::DEFAULT_LIBRARY,
583 HlMod::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
584 HlMod::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
585 HlMod::Injected => semantic_tokens::INJECTED,
586 HlMod::IntraDocLink => semantic_tokens::INTRA_DOC_LINK,
587 HlMod::Library => semantic_tokens::LIBRARY,
588 HlMod::Mutable => semantic_tokens::MUTABLE,
589 HlMod::Public => semantic_tokens::PUBLIC,
590 HlMod::Reference => semantic_tokens::REFERENCE,
591 HlMod::Static => lsp_types::SemanticTokenModifier::STATIC,
592 HlMod::Trait => semantic_tokens::TRAIT_MODIFIER,
593 HlMod::Unsafe => semantic_tokens::UNSAFE,
601 pub(crate) fn folding_range(
603 line_index: &LineIndex,
604 line_folding_only: bool,
606 ) -> lsp_types::FoldingRange {
607 let kind = match fold.kind {
608 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
609 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
610 FoldKind::Region => Some(lsp_types::FoldingRangeKind::Region),
616 | FoldKind::WhereClause
617 | FoldKind::ReturnType
618 | FoldKind::Array => None,
621 let range = range(line_index, fold.range);
623 if line_folding_only {
624 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
625 // even if it contains text not in the folding range. To prevent that we exclude
626 // range.end.line from the folding region if there is more text after range.end
628 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
630 .take_while(|it| *it != '\n')
631 .any(|it| !it.is_whitespace());
633 let end_line = if has_more_text_on_end_line {
634 range.end.line.saturating_sub(1)
639 lsp_types::FoldingRange {
640 start_line: range.start.line,
641 start_character: None,
647 lsp_types::FoldingRange {
648 start_line: range.start.line,
649 start_character: Some(range.start.character),
650 end_line: range.end.line,
651 end_character: Some(range.end.character),
657 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
658 snap.file_id_to_url(file_id)
661 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
662 /// This will only happen when processing windows paths.
664 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
665 pub(crate) fn url_from_abs_path(path: &AbsPath) -> lsp_types::Url {
666 let url = lsp_types::Url::from_file_path(path).unwrap();
667 match path.as_ref().components().next() {
668 Some(path::Component::Prefix(prefix))
669 if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
671 // Need to lowercase driver letter
676 let driver_letter_range = {
677 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
681 let start = scheme.len() + ':'.len_utf8();
682 start..(start + drive_letter.len())
685 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
686 // machinery *also* canonicalizes the drive letter. So, just massage the
688 let mut url: String = url.into();
689 url[driver_letter_range].make_ascii_lowercase();
690 lsp_types::Url::parse(&url).unwrap()
693 pub(crate) fn optional_versioned_text_document_identifier(
694 snap: &GlobalStateSnapshot,
696 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
697 let url = url(snap, file_id);
698 let version = snap.url_file_version(&url);
699 lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
702 pub(crate) fn location(
703 snap: &GlobalStateSnapshot,
705 ) -> Result<lsp_types::Location> {
706 let url = url(snap, frange.file_id);
707 let line_index = snap.file_line_index(frange.file_id)?;
708 let range = range(&line_index, frange.range);
709 let loc = lsp_types::Location::new(url, range);
713 /// Prefer using `location_link`, if the client has the cap.
714 pub(crate) fn location_from_nav(
715 snap: &GlobalStateSnapshot,
716 nav: NavigationTarget,
717 ) -> Result<lsp_types::Location> {
718 let url = url(snap, nav.file_id);
719 let line_index = snap.file_line_index(nav.file_id)?;
720 let range = range(&line_index, nav.full_range);
721 let loc = lsp_types::Location::new(url, range);
725 pub(crate) fn location_link(
726 snap: &GlobalStateSnapshot,
727 src: Option<FileRange>,
728 target: NavigationTarget,
729 ) -> Result<lsp_types::LocationLink> {
730 let origin_selection_range = match src {
732 let line_index = snap.file_line_index(src.file_id)?;
733 let range = range(&line_index, src.range);
738 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
739 let res = lsp_types::LocationLink {
740 origin_selection_range,
743 target_selection_range,
749 snap: &GlobalStateSnapshot,
750 target: NavigationTarget,
751 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
752 let line_index = snap.file_line_index(target.file_id)?;
754 let target_uri = url(snap, target.file_id);
755 let target_range = range(&line_index, target.full_range);
756 let target_selection_range =
757 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
758 Ok((target_uri, target_range, target_selection_range))
761 pub(crate) fn goto_definition_response(
762 snap: &GlobalStateSnapshot,
763 src: Option<FileRange>,
764 targets: Vec<NavigationTarget>,
765 ) -> Result<lsp_types::GotoDefinitionResponse> {
766 if snap.config.location_link() {
769 .map(|nav| location_link(snap, src, nav))
770 .collect::<Result<Vec<_>>>()?;
773 let locations = targets
776 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
778 .collect::<Result<Vec<_>>>()?;
783 fn outside_workspace_annotation_id() -> String {
784 String::from("OutsideWorkspace")
787 pub(crate) fn snippet_text_document_edit(
788 snap: &GlobalStateSnapshot,
792 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
793 let text_document = optional_versioned_text_document_identifier(snap, file_id);
794 let line_index = snap.file_line_index(file_id)?;
795 let mut edits: Vec<_> =
796 edit.into_iter().map(|it| snippet_text_edit(&line_index, is_snippet, it)).collect();
798 if snap.analysis.is_library_file(file_id)? && snap.config.change_annotation_support() {
799 for edit in &mut edits {
800 edit.annotation_id = Some(outside_workspace_annotation_id())
803 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
806 pub(crate) fn snippet_text_document_ops(
807 snap: &GlobalStateSnapshot,
808 file_system_edit: FileSystemEdit,
809 ) -> Cancellable<Vec<lsp_ext::SnippetDocumentChangeOperation>> {
810 let mut ops = Vec::new();
811 match file_system_edit {
812 FileSystemEdit::CreateFile { dst, initial_contents } => {
813 let uri = snap.anchored_path(&dst);
814 let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
819 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
820 if !initial_contents.is_empty() {
822 lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
823 let text_edit = lsp_ext::SnippetTextEdit {
824 range: lsp_types::Range::default(),
825 new_text: initial_contents,
826 insert_text_format: Some(lsp_types::InsertTextFormat::PLAIN_TEXT),
830 lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
831 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
834 FileSystemEdit::MoveFile { src, dst } => {
835 let old_uri = snap.file_id_to_url(src);
836 let new_uri = snap.anchored_path(&dst);
837 let mut rename_file =
838 lsp_types::RenameFile { old_uri, new_uri, options: None, annotation_id: None };
839 if snap.analysis.is_library_file(src).ok() == Some(true)
840 && snap.config.change_annotation_support()
842 rename_file.annotation_id = Some(outside_workspace_annotation_id())
844 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(lsp_types::ResourceOp::Rename(
852 pub(crate) fn snippet_workspace_edit(
853 snap: &GlobalStateSnapshot,
854 source_change: SourceChange,
855 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
856 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
858 for op in source_change.file_system_edits {
859 let ops = snippet_text_document_ops(snap, op)?;
860 document_changes.extend_from_slice(&ops);
862 for (file_id, edit) in source_change.source_file_edits {
863 let edit = snippet_text_document_edit(snap, source_change.is_snippet, file_id, edit)?;
864 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
866 let mut workspace_edit = lsp_ext::SnippetWorkspaceEdit {
868 document_changes: Some(document_changes),
869 change_annotations: None,
871 if snap.config.change_annotation_support() {
872 workspace_edit.change_annotations = Some(
874 outside_workspace_annotation_id(),
875 lsp_types::ChangeAnnotation {
876 label: String::from("Edit outside of the workspace"),
877 needs_confirmation: Some(true),
878 description: Some(String::from(
879 "This edit lies outside of the workspace and may affect dependencies",
889 pub(crate) fn workspace_edit(
890 snap: &GlobalStateSnapshot,
891 source_change: SourceChange,
892 ) -> Result<lsp_types::WorkspaceEdit> {
893 assert!(!source_change.is_snippet);
894 snippet_workspace_edit(snap, source_change).map(|it| it.into())
897 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
898 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
899 lsp_types::WorkspaceEdit {
901 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
902 lsp_types::DocumentChanges::Operations(
905 .map(|change| match change {
906 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
907 lsp_types::DocumentChangeOperation::Op(op)
909 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
910 lsp_types::DocumentChangeOperation::Edit(
911 lsp_types::TextDocumentEdit {
912 text_document: edit.text_document,
913 edits: edit.edits.into_iter().map(From::from).collect(),
921 change_annotations: snippet_workspace_edit.change_annotations,
926 impl From<lsp_ext::SnippetTextEdit>
927 for lsp_types::OneOf<lsp_types::TextEdit, lsp_types::AnnotatedTextEdit>
930 lsp_ext::SnippetTextEdit { annotation_id, insert_text_format:_, new_text, range }: lsp_ext::SnippetTextEdit,
932 match annotation_id {
933 Some(annotation_id) => lsp_types::OneOf::Right(lsp_types::AnnotatedTextEdit {
934 text_edit: lsp_types::TextEdit { range, new_text },
937 None => lsp_types::OneOf::Left(lsp_types::TextEdit { range, new_text }),
942 pub(crate) fn call_hierarchy_item(
943 snap: &GlobalStateSnapshot,
944 target: NavigationTarget,
945 ) -> Result<lsp_types::CallHierarchyItem> {
946 let name = target.name.to_string();
947 let detail = target.description.clone();
948 let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::FUNCTION);
949 let (uri, range, selection_range) = location_info(snap, target)?;
950 Ok(lsp_types::CallHierarchyItem {
962 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
964 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
965 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
966 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
967 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
968 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
969 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
973 pub(crate) fn code_action(
974 snap: &GlobalStateSnapshot,
976 resolve_data: Option<(usize, lsp_types::CodeActionParams)>,
977 ) -> Result<lsp_ext::CodeAction> {
978 let mut res = lsp_ext::CodeAction {
979 title: assist.label.to_string(),
980 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
981 kind: Some(code_action_kind(assist.id.1)),
986 match (assist.source_change, resolve_data) {
987 (Some(it), _) => res.edit = Some(snippet_workspace_edit(snap, it)?),
988 (None, Some((index, code_action_params))) => {
989 res.data = Some(lsp_ext::CodeActionData {
990 id: format!("{}:{}:{}", assist.id.0, assist.id.1.name(), index),
995 stdx::never!("assist should always be resolved if client can't do lazy resolving")
1001 pub(crate) fn runnable(
1002 snap: &GlobalStateSnapshot,
1004 ) -> Result<lsp_ext::Runnable> {
1005 let config = snap.config.runnables();
1006 let spec = CargoTargetSpec::for_file(snap, runnable.nav.file_id)?;
1007 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
1008 let target = spec.as_ref().map(|s| s.target.clone());
1009 let (cargo_args, executable_args) =
1010 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
1011 let label = runnable.label(target);
1012 let location = location_link(snap, None, runnable.nav)?;
1014 Ok(lsp_ext::Runnable {
1016 location: Some(location),
1017 kind: lsp_ext::RunnableKind::Cargo,
1018 args: lsp_ext::CargoRunnable {
1019 workspace_root: workspace_root.map(|it| it.into()),
1020 override_cargo: config.override_cargo,
1022 cargo_extra_args: config.cargo_extra_args,
1029 pub(crate) fn code_lens(
1030 acc: &mut Vec<lsp_types::CodeLens>,
1031 snap: &GlobalStateSnapshot,
1032 annotation: Annotation,
1034 let client_commands_config = snap.config.client_commands();
1035 match annotation.kind {
1036 AnnotationKind::Runnable(run) => {
1037 let line_index = snap.file_line_index(run.nav.file_id)?;
1038 let annotation_range = range(&line_index, annotation.range);
1040 let title = run.title();
1041 let can_debug = match run.kind {
1042 ide::RunnableKind::DocTest { .. } => false,
1043 ide::RunnableKind::TestMod { .. }
1044 | ide::RunnableKind::Test { .. }
1045 | ide::RunnableKind::Bench { .. }
1046 | ide::RunnableKind::Bin => true,
1048 let r = runnable(snap, run)?;
1050 let lens_config = snap.config.lens();
1051 if lens_config.run && client_commands_config.run_single {
1052 let command = command::run_single(&r, &title);
1053 acc.push(lsp_types::CodeLens {
1054 range: annotation_range,
1055 command: Some(command),
1059 if lens_config.debug && can_debug && client_commands_config.debug_single {
1060 let command = command::debug_single(&r);
1061 acc.push(lsp_types::CodeLens {
1062 range: annotation_range,
1063 command: Some(command),
1068 AnnotationKind::HasImpls { position: file_position, data } => {
1069 if !client_commands_config.show_reference {
1072 let line_index = snap.file_line_index(file_position.file_id)?;
1073 let annotation_range = range(&line_index, annotation.range);
1074 let url = url(snap, file_position.file_id);
1076 let position = position(&line_index, file_position.offset);
1078 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1080 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
1082 let goto_params = lsp_types::request::GotoImplementationParams {
1083 text_document_position_params: doc_pos,
1084 work_done_progress_params: Default::default(),
1085 partial_result_params: Default::default(),
1088 let command = data.map(|ranges| {
1089 let locations: Vec<lsp_types::Location> = ranges
1091 .filter_map(|target| {
1094 FileRange { file_id: target.file_id, range: target.full_range },
1100 command::show_references(
1101 implementation_title(locations.len()),
1108 acc.push(lsp_types::CodeLens {
1109 range: annotation_range,
1111 data: Some(to_value(lsp_ext::CodeLensResolveData::Impls(goto_params)).unwrap()),
1114 AnnotationKind::HasReferences { position: file_position, data } => {
1115 if !client_commands_config.show_reference {
1118 let line_index = snap.file_line_index(file_position.file_id)?;
1119 let annotation_range = range(&line_index, annotation.range);
1120 let url = url(snap, file_position.file_id);
1122 let position = position(&line_index, file_position.offset);
1124 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1126 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
1128 let command = data.map(|ranges| {
1129 let locations: Vec<lsp_types::Location> =
1130 ranges.into_iter().filter_map(|range| location(snap, range).ok()).collect();
1132 command::show_references(
1133 reference_title(locations.len()),
1140 acc.push(lsp_types::CodeLens {
1141 range: annotation_range,
1143 data: Some(to_value(lsp_ext::CodeLensResolveData::References(doc_pos)).unwrap()),
1150 pub(crate) mod command {
1151 use ide::{FileRange, NavigationTarget};
1152 use serde_json::to_value;
1155 global_state::GlobalStateSnapshot,
1157 to_proto::{location, location_link},
1160 pub(crate) fn show_references(
1162 uri: &lsp_types::Url,
1163 position: lsp_types::Position,
1164 locations: Vec<lsp_types::Location>,
1165 ) -> lsp_types::Command {
1166 // We cannot use the 'editor.action.showReferences' command directly
1167 // because that command requires vscode types which we convert in the handler
1168 // on the client side.
1170 lsp_types::Command {
1172 command: "rust-analyzer.showReferences".into(),
1173 arguments: Some(vec![
1174 to_value(uri).unwrap(),
1175 to_value(position).unwrap(),
1176 to_value(locations).unwrap(),
1181 pub(crate) fn run_single(runnable: &lsp_ext::Runnable, title: &str) -> lsp_types::Command {
1182 lsp_types::Command {
1183 title: title.to_string(),
1184 command: "rust-analyzer.runSingle".into(),
1185 arguments: Some(vec![to_value(runnable).unwrap()]),
1189 pub(crate) fn debug_single(runnable: &lsp_ext::Runnable) -> lsp_types::Command {
1190 lsp_types::Command {
1191 title: "Debug".into(),
1192 command: "rust-analyzer.debugSingle".into(),
1193 arguments: Some(vec![to_value(runnable).unwrap()]),
1197 pub(crate) fn goto_location(
1198 snap: &GlobalStateSnapshot,
1199 nav: &NavigationTarget,
1200 ) -> Option<lsp_types::Command> {
1201 let value = if snap.config.location_link() {
1202 let link = location_link(snap, None, nav.clone()).ok()?;
1203 to_value(link).ok()?
1205 let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1206 let location = location(snap, range).ok()?;
1207 to_value(location).ok()?
1210 Some(lsp_types::Command {
1211 title: nav.name.to_string(),
1212 command: "rust-analyzer.gotoLocation".into(),
1213 arguments: Some(vec![value]),
1217 pub(crate) fn trigger_parameter_hints() -> lsp_types::Command {
1218 lsp_types::Command {
1219 title: "triggerParameterHints".into(),
1220 command: "editor.action.triggerParameterHints".into(),
1226 pub(crate) fn implementation_title(count: usize) -> String {
1228 "1 implementation".into()
1230 format!("{} implementations", count)
1234 pub(crate) fn reference_title(count: usize) -> String {
1236 "1 reference".into()
1238 format!("{} references", count)
1242 pub(crate) fn markup_content(
1244 kind: ide::HoverDocFormat,
1245 ) -> lsp_types::MarkupContent {
1246 let kind = match kind {
1247 ide::HoverDocFormat::Markdown => lsp_types::MarkupKind::Markdown,
1248 ide::HoverDocFormat::PlainText => lsp_types::MarkupKind::PlainText,
1250 let value = crate::markdown::format_docs(markup.as_str());
1251 lsp_types::MarkupContent { kind, value }
1254 pub(crate) fn rename_error(err: RenameError) -> crate::LspError {
1255 // This is wrong, but we don't have a better alternative I suppose?
1256 // https://github.com/microsoft/language-server-protocol/issues/1341
1257 invalid_params_error(err.to_string())
1269 fn conv_fold_line_folding_only_fixup() {
1270 let text = r#"mod a;
1282 let (analysis, file_id) = Analysis::from_single_file(text.to_string());
1283 let folds = analysis.folding_ranges(file_id).unwrap();
1284 assert_eq!(folds.len(), 4);
1286 let line_index = LineIndex {
1287 index: Arc::new(ide::LineIndex::new(text)),
1288 endings: LineEndings::Unix,
1289 encoding: OffsetEncoding::Utf16,
1291 let converted: Vec<lsp_types::FoldingRange> =
1292 folds.into_iter().map(|it| folding_range(text, &line_index, true, it)).collect();
1294 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
1295 assert_eq!(converted.len(), expected_lines.len());
1296 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
1297 assert_eq!(folding_range.start_line, *start_line);
1298 assert_eq!(folding_range.start_character, None);
1299 assert_eq!(folding_range.end_line, *end_line);
1300 assert_eq!(folding_range.end_character, None);
1304 // `Url` is not able to parse windows paths on unix machines.
1306 #[cfg(target_os = "windows")]
1307 fn test_lowercase_drive_letter() {
1308 use std::{convert::TryInto, path::Path};
1310 let url = url_from_abs_path(Path::new("C:\\Test").try_into().unwrap());
1311 assert_eq!(url.to_string(), "file:///c:/Test");
1313 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#).try_into().unwrap());
1314 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");