1 //! Conversion of rust-analyzer specific types to lsp_types equivalents.
5 sync::atomic::{AtomicU32, Ordering},
9 Annotation, AnnotationKind, Assist, AssistKind, Cancellable, CompletionItem,
10 CompletionItemKind, CompletionRelevance, Documentation, FileId, FileRange, FileSystemEdit,
11 Fold, FoldKind, Highlight, HlMod, HlOperator, HlPunct, HlRange, HlTag, Indel, InlayHint,
12 InlayHintLabel, InlayKind, Markup, NavigationTarget, ReferenceCategory, RenameError, Runnable,
13 Severity, SignatureHelp, SourceChange, StructureNodeKind, SymbolKind, TextEdit, TextRange,
16 use itertools::Itertools;
17 use serde_json::to_value;
21 cargo_target_spec::CargoTargetSpec,
22 config::{CallInfoConfig, Config},
23 global_state::GlobalStateSnapshot,
24 line_index::{LineEndings, LineIndex, OffsetEncoding},
26 lsp_utils::invalid_params_error,
27 semantic_tokens, Result,
30 pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position {
31 let line_col = line_index.index.line_col(offset);
32 match line_index.encoding {
33 OffsetEncoding::Utf8 => lsp_types::Position::new(line_col.line, line_col.col),
34 OffsetEncoding::Utf16 => {
35 let line_col = line_index.index.to_utf16(line_col);
36 lsp_types::Position::new(line_col.line, line_col.col)
41 pub(crate) fn range(line_index: &LineIndex, range: TextRange) -> lsp_types::Range {
42 let start = position(line_index, range.start());
43 let end = position(line_index, range.end());
44 lsp_types::Range::new(start, end)
47 pub(crate) fn symbol_kind(symbol_kind: SymbolKind) -> lsp_types::SymbolKind {
49 SymbolKind::Function => lsp_types::SymbolKind::FUNCTION,
50 SymbolKind::Struct => lsp_types::SymbolKind::STRUCT,
51 SymbolKind::Enum => lsp_types::SymbolKind::ENUM,
52 SymbolKind::Variant => lsp_types::SymbolKind::ENUM_MEMBER,
53 SymbolKind::Trait => lsp_types::SymbolKind::INTERFACE,
55 | SymbolKind::BuiltinAttr
56 | SymbolKind::Attribute
58 | SymbolKind::DeriveHelper => lsp_types::SymbolKind::FUNCTION,
59 SymbolKind::Module | SymbolKind::ToolModule => lsp_types::SymbolKind::MODULE,
60 SymbolKind::TypeAlias | SymbolKind::TypeParam | SymbolKind::SelfType => {
61 lsp_types::SymbolKind::TYPE_PARAMETER
63 SymbolKind::Field => lsp_types::SymbolKind::FIELD,
64 SymbolKind::Static => lsp_types::SymbolKind::CONSTANT,
65 SymbolKind::Const => lsp_types::SymbolKind::CONSTANT,
66 SymbolKind::ConstParam => lsp_types::SymbolKind::CONSTANT,
67 SymbolKind::Impl => lsp_types::SymbolKind::OBJECT,
69 | SymbolKind::SelfParam
70 | SymbolKind::LifetimeParam
71 | SymbolKind::ValueParam
72 | SymbolKind::Label => lsp_types::SymbolKind::VARIABLE,
73 SymbolKind::Union => lsp_types::SymbolKind::STRUCT,
77 pub(crate) fn structure_node_kind(kind: StructureNodeKind) -> lsp_types::SymbolKind {
79 StructureNodeKind::SymbolKind(symbol) => symbol_kind(symbol),
80 StructureNodeKind::Region => lsp_types::SymbolKind::NAMESPACE,
84 pub(crate) fn document_highlight_kind(
85 category: ReferenceCategory,
86 ) -> Option<lsp_types::DocumentHighlightKind> {
88 ReferenceCategory::Read => Some(lsp_types::DocumentHighlightKind::READ),
89 ReferenceCategory::Write => Some(lsp_types::DocumentHighlightKind::WRITE),
90 ReferenceCategory::Import => None,
94 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
96 Severity::Error => lsp_types::DiagnosticSeverity::ERROR,
97 Severity::WeakWarning => lsp_types::DiagnosticSeverity::HINT,
101 pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
102 let value = crate::markdown::format_docs(documentation.as_str());
103 let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
104 lsp_types::Documentation::MarkupContent(markup_content)
107 pub(crate) fn completion_item_kind(
108 completion_item_kind: CompletionItemKind,
109 ) -> lsp_types::CompletionItemKind {
110 match completion_item_kind {
111 CompletionItemKind::Binding => lsp_types::CompletionItemKind::VARIABLE,
112 CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::STRUCT,
113 CompletionItemKind::InferredType => lsp_types::CompletionItemKind::SNIPPET,
114 CompletionItemKind::Keyword => lsp_types::CompletionItemKind::KEYWORD,
115 CompletionItemKind::Method => lsp_types::CompletionItemKind::METHOD,
116 CompletionItemKind::Snippet => lsp_types::CompletionItemKind::SNIPPET,
117 CompletionItemKind::UnresolvedReference => lsp_types::CompletionItemKind::REFERENCE,
118 CompletionItemKind::SymbolKind(symbol) => match symbol {
119 SymbolKind::Attribute => lsp_types::CompletionItemKind::FUNCTION,
120 SymbolKind::Const => lsp_types::CompletionItemKind::CONSTANT,
121 SymbolKind::ConstParam => lsp_types::CompletionItemKind::TYPE_PARAMETER,
122 SymbolKind::Derive => lsp_types::CompletionItemKind::FUNCTION,
123 SymbolKind::DeriveHelper => lsp_types::CompletionItemKind::FUNCTION,
124 SymbolKind::Enum => lsp_types::CompletionItemKind::ENUM,
125 SymbolKind::Field => lsp_types::CompletionItemKind::FIELD,
126 SymbolKind::Function => lsp_types::CompletionItemKind::FUNCTION,
127 SymbolKind::Impl => lsp_types::CompletionItemKind::TEXT,
128 SymbolKind::Label => lsp_types::CompletionItemKind::VARIABLE,
129 SymbolKind::LifetimeParam => lsp_types::CompletionItemKind::TYPE_PARAMETER,
130 SymbolKind::Local => lsp_types::CompletionItemKind::VARIABLE,
131 SymbolKind::Macro => lsp_types::CompletionItemKind::FUNCTION,
132 SymbolKind::Module => lsp_types::CompletionItemKind::MODULE,
133 SymbolKind::SelfParam => lsp_types::CompletionItemKind::VALUE,
134 SymbolKind::SelfType => lsp_types::CompletionItemKind::TYPE_PARAMETER,
135 SymbolKind::Static => lsp_types::CompletionItemKind::VALUE,
136 SymbolKind::Struct => lsp_types::CompletionItemKind::STRUCT,
137 SymbolKind::Trait => lsp_types::CompletionItemKind::INTERFACE,
138 SymbolKind::TypeAlias => lsp_types::CompletionItemKind::STRUCT,
139 SymbolKind::TypeParam => lsp_types::CompletionItemKind::TYPE_PARAMETER,
140 SymbolKind::Union => lsp_types::CompletionItemKind::STRUCT,
141 SymbolKind::ValueParam => lsp_types::CompletionItemKind::VALUE,
142 SymbolKind::Variant => lsp_types::CompletionItemKind::ENUM_MEMBER,
143 SymbolKind::BuiltinAttr => lsp_types::CompletionItemKind::FUNCTION,
144 SymbolKind::ToolModule => lsp_types::CompletionItemKind::MODULE,
149 pub(crate) fn text_edit(line_index: &LineIndex, indel: Indel) -> lsp_types::TextEdit {
150 let range = range(line_index, indel.delete);
151 let new_text = match line_index.endings {
152 LineEndings::Unix => indel.insert,
153 LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
155 lsp_types::TextEdit { range, new_text }
158 pub(crate) fn completion_text_edit(
159 line_index: &LineIndex,
160 insert_replace_support: Option<lsp_types::Position>,
162 ) -> lsp_types::CompletionTextEdit {
163 let text_edit = text_edit(line_index, indel);
164 match insert_replace_support {
165 Some(cursor_pos) => lsp_types::InsertReplaceEdit {
166 new_text: text_edit.new_text,
167 insert: lsp_types::Range { start: text_edit.range.start, end: cursor_pos },
168 replace: text_edit.range,
171 None => text_edit.into(),
175 pub(crate) fn snippet_text_edit(
176 line_index: &LineIndex,
179 ) -> lsp_ext::SnippetTextEdit {
180 let text_edit = text_edit(line_index, indel);
181 let insert_text_format =
182 if is_snippet { Some(lsp_types::InsertTextFormat::SNIPPET) } else { None };
183 lsp_ext::SnippetTextEdit {
184 range: text_edit.range,
185 new_text: text_edit.new_text,
191 pub(crate) fn text_edit_vec(
192 line_index: &LineIndex,
194 ) -> Vec<lsp_types::TextEdit> {
195 text_edit.into_iter().map(|indel| self::text_edit(line_index, indel)).collect()
198 pub(crate) fn snippet_text_edit_vec(
199 line_index: &LineIndex,
202 ) -> Vec<lsp_ext::SnippetTextEdit> {
205 .map(|indel| self::snippet_text_edit(line_index, is_snippet, indel))
209 pub(crate) fn completion_items(
211 line_index: &LineIndex,
212 tdpp: lsp_types::TextDocumentPositionParams,
213 items: Vec<CompletionItem>,
214 ) -> Vec<lsp_types::CompletionItem> {
215 let max_relevance = items.iter().map(|it| it.relevance().score()).max().unwrap_or_default();
216 let mut res = Vec::with_capacity(items.len());
218 completion_item(&mut res, config, line_index, &tdpp, max_relevance, item)
224 acc: &mut Vec<lsp_types::CompletionItem>,
226 line_index: &LineIndex,
227 tdpp: &lsp_types::TextDocumentPositionParams,
229 item: CompletionItem,
231 let insert_replace_support = config.insert_replace_support().then(|| tdpp.position);
232 let mut additional_text_edits = Vec::new();
234 // LSP does not allow arbitrary edits in completion, so we have to do a
235 // non-trivial mapping here.
237 let mut text_edit = None;
238 let source_range = item.source_range();
239 for indel in item.text_edit().iter() {
240 if indel.delete.contains_range(source_range) {
241 text_edit = Some(if indel.delete == source_range {
242 self::completion_text_edit(line_index, insert_replace_support, indel.clone())
244 assert!(source_range.end() == indel.delete.end());
245 let range1 = TextRange::new(indel.delete.start(), source_range.start());
246 let range2 = source_range;
247 let indel1 = Indel::replace(range1, String::new());
248 let indel2 = Indel::replace(range2, indel.insert.clone());
249 additional_text_edits.push(self::text_edit(line_index, indel1));
250 self::completion_text_edit(line_index, insert_replace_support, indel2)
253 assert!(source_range.intersect(indel.delete).is_none());
254 let text_edit = self::text_edit(line_index, indel.clone());
255 additional_text_edits.push(text_edit);
261 let insert_text_format = item.is_snippet().then(|| lsp_types::InsertTextFormat::SNIPPET);
262 let tags = item.deprecated().then(|| vec![lsp_types::CompletionItemTag::DEPRECATED]);
263 let command = if item.trigger_call_info() && config.client_commands().trigger_parameter_hints {
264 Some(command::trigger_parameter_hints())
269 let mut lsp_item = lsp_types::CompletionItem {
270 label: item.label().to_string(),
271 detail: item.detail().map(|it| it.to_string()),
272 filter_text: Some(item.lookup().to_string()),
273 kind: Some(completion_item_kind(item.kind())),
274 text_edit: Some(text_edit),
275 additional_text_edits: Some(additional_text_edits),
276 documentation: item.documentation().map(documentation),
277 deprecated: Some(item.deprecated()),
284 if config.completion_label_details_support() {
285 lsp_item.label_details = Some(lsp_types::CompletionItemLabelDetails {
287 description: lsp_item.detail.clone(),
291 set_score(&mut lsp_item, max_relevance, item.relevance());
293 if config.completion().enable_imports_on_the_fly {
294 if let imports @ [_, ..] = item.imports_to_add() {
295 let imports: Vec<_> = imports
297 .filter_map(|import_edit| {
298 let import_path = &import_edit.import_path;
299 let import_name = import_path.segments().last()?;
300 Some(lsp_ext::CompletionImport {
301 full_import_path: import_path.to_string(),
302 imported_name: import_name.to_string(),
306 if !imports.is_empty() {
307 let data = lsp_ext::CompletionResolveData { position: tdpp.clone(), imports };
308 lsp_item.data = Some(to_value(data).unwrap());
313 if let Some((mutability, offset, relevance)) = item.ref_match() {
314 let mut lsp_item_with_ref = lsp_item.clone();
315 set_score(&mut lsp_item_with_ref, max_relevance, relevance);
316 lsp_item_with_ref.label =
317 format!("&{}{}", mutability.as_keyword_for_ref(), lsp_item_with_ref.label);
318 lsp_item_with_ref.additional_text_edits.get_or_insert_with(Default::default).push(
321 Indel::insert(offset, format!("&{}", mutability.as_keyword_for_ref())),
325 acc.push(lsp_item_with_ref);
331 res: &mut lsp_types::CompletionItem,
333 relevance: CompletionRelevance,
335 if relevance.is_relevant() && relevance.score() == max_relevance {
336 res.preselect = Some(true);
338 // The relevance needs to be inverted to come up with a sort score
339 // because the client will sort ascending.
340 let sort_score = relevance.score() ^ 0xFF_FF_FF_FF;
341 // Zero pad the string to ensure values can be properly sorted
342 // by the client. Hex format is used because it is easier to
343 // visually compare very large values, which the sort text
344 // tends to be since it is the opposite of the score.
345 res.sort_text = Some(format!("{:08x}", sort_score));
349 pub(crate) fn signature_help(
350 call_info: SignatureHelp,
351 config: CallInfoConfig,
353 ) -> lsp_types::SignatureHelp {
354 let (label, parameters) = match (config.params_only, label_offsets) {
355 (concise, false) => {
356 let params = call_info
358 .map(|label| lsp_types::ParameterInformation {
359 label: lsp_types::ParameterLabel::Simple(label.to_string()),
362 .collect::<Vec<_>>();
364 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
368 let params = call_info
372 let start = call_info.signature[..it.start().into()].chars().count() as u32;
373 let end = call_info.signature[..it.end().into()].chars().count() as u32;
376 .map(|label_offsets| lsp_types::ParameterInformation {
377 label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
380 .collect::<Vec<_>>();
381 (call_info.signature, params)
384 let mut params = Vec::new();
385 let mut label = String::new();
386 let mut first = true;
387 for param in call_info.parameter_labels() {
389 label.push_str(", ");
392 let start = label.chars().count() as u32;
393 label.push_str(param);
394 let end = label.chars().count() as u32;
395 params.push(lsp_types::ParameterInformation {
396 label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
405 let documentation = call_info.doc.filter(|_| config.docs).map(|doc| {
406 lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
407 kind: lsp_types::MarkupKind::Markdown,
412 let active_parameter = call_info.active_parameter.map(|it| it as u32);
414 let signature = lsp_types::SignatureInformation {
417 parameters: Some(parameters),
420 lsp_types::SignatureHelp {
421 signatures: vec![signature],
422 active_signature: Some(0),
427 pub(crate) fn inlay_hint(
428 snap: &GlobalStateSnapshot,
429 line_index: &LineIndex,
431 mut inlay_hint: InlayHint,
432 ) -> Result<lsp_types::InlayHint> {
433 match inlay_hint.kind {
434 InlayKind::ParameterHint if render_colons => inlay_hint.label.append_str(":"),
435 InlayKind::TypeHint if render_colons => inlay_hint.label.prepend_str(": "),
436 InlayKind::ClosureReturnTypeHint => inlay_hint.label.prepend_str(" -> "),
440 Ok(lsp_types::InlayHint {
441 position: match inlay_hint.kind {
442 // before annotated thing
443 InlayKind::ParameterHint
444 | InlayKind::ImplicitReborrowHint
445 | InlayKind::BindingModeHint => position(line_index, inlay_hint.range.start()),
446 // after annotated thing
447 InlayKind::ClosureReturnTypeHint
448 | InlayKind::TypeHint
449 | InlayKind::ChainingHint
450 | InlayKind::GenericParamListHint
451 | InlayKind::LifetimeHint
452 | InlayKind::ClosingBraceHint => position(line_index, inlay_hint.range.end()),
454 padding_left: Some(match inlay_hint.kind {
455 InlayKind::TypeHint => !render_colons,
456 InlayKind::ChainingHint | InlayKind::ClosingBraceHint => true,
457 InlayKind::BindingModeHint
458 | InlayKind::ClosureReturnTypeHint
459 | InlayKind::GenericParamListHint
460 | InlayKind::ImplicitReborrowHint
461 | InlayKind::LifetimeHint
462 | InlayKind::ParameterHint => false,
464 padding_right: Some(match inlay_hint.kind {
465 InlayKind::ChainingHint
466 | InlayKind::ClosureReturnTypeHint
467 | InlayKind::GenericParamListHint
468 | InlayKind::ImplicitReborrowHint
469 | InlayKind::TypeHint
470 | InlayKind::ClosingBraceHint => false,
471 InlayKind::BindingModeHint => inlay_hint.label.as_simple_str() != Some("&"),
472 InlayKind::ParameterHint | InlayKind::LifetimeHint => true,
474 kind: match inlay_hint.kind {
475 InlayKind::ParameterHint => Some(lsp_types::InlayHintKind::PARAMETER),
476 InlayKind::ClosureReturnTypeHint | InlayKind::TypeHint | InlayKind::ChainingHint => {
477 Some(lsp_types::InlayHintKind::TYPE)
479 InlayKind::BindingModeHint
480 | InlayKind::GenericParamListHint
481 | InlayKind::LifetimeHint
482 | InlayKind::ImplicitReborrowHint
483 | InlayKind::ClosingBraceHint => None,
486 data: (|| match inlay_hint.tooltip {
487 Some(ide::InlayTooltip::HoverOffset(file_id, offset)) => {
488 let uri = url(snap, file_id);
489 let line_index = snap.file_line_index(file_id).ok()?;
491 let text_document = lsp_types::TextDocumentIdentifier { uri };
492 to_value(lsp_ext::InlayHintResolveData {
494 position: lsp_ext::PositionOrRange::Position(position(&line_index, offset)),
498 Some(ide::InlayTooltip::HoverRanged(file_id, text_range)) => {
499 let uri = url(snap, file_id);
500 let text_document = lsp_types::TextDocumentIdentifier { uri };
501 let line_index = snap.file_line_index(file_id).ok()?;
502 to_value(lsp_ext::InlayHintResolveData {
504 position: lsp_ext::PositionOrRange::Range(range(&line_index, text_range)),
510 tooltip: Some(match inlay_hint.tooltip {
511 Some(ide::InlayTooltip::String(s)) => lsp_types::InlayHintTooltip::String(s),
512 _ => lsp_types::InlayHintTooltip::String(inlay_hint.label.to_string()),
514 label: inlay_hint_label(snap, inlay_hint.label)?,
519 snap: &GlobalStateSnapshot,
520 label: InlayHintLabel,
521 ) -> Result<lsp_types::InlayHintLabel> {
522 Ok(match label.as_simple_str() {
523 Some(s) => lsp_types::InlayHintLabel::String(s.into()),
524 None => lsp_types::InlayHintLabel::LabelParts(
529 Ok(lsp_types::InlayHintLabelPart {
534 .map(|range| location(snap, range))
539 .collect::<Result<Vec<_>>>()?,
544 static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
546 pub(crate) fn semantic_tokens(
548 line_index: &LineIndex,
549 highlights: Vec<HlRange>,
550 ) -> lsp_types::SemanticTokens {
551 let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
552 let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
554 for highlight_range in highlights {
555 if highlight_range.highlight.is_empty() {
559 let (ty, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
560 let token_index = semantic_tokens::type_index(ty);
561 let modifier_bitset = mods.0;
563 for mut text_range in line_index.index.lines(highlight_range.range) {
564 if text[text_range].ends_with('\n') {
566 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
568 let range = range(line_index, text_range);
569 builder.push(range, token_index, modifier_bitset);
576 pub(crate) fn semantic_token_delta(
577 previous: &lsp_types::SemanticTokens,
578 current: &lsp_types::SemanticTokens,
579 ) -> lsp_types::SemanticTokensDelta {
580 let result_id = current.result_id.clone();
581 let edits = semantic_tokens::diff_tokens(&previous.data, ¤t.data);
582 lsp_types::SemanticTokensDelta { result_id, edits }
585 fn semantic_token_type_and_modifiers(
586 highlight: Highlight,
587 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
588 let mut mods = semantic_tokens::ModifierSet::default();
589 let type_ = match highlight.tag {
590 HlTag::Symbol(symbol) => match symbol {
591 SymbolKind::Attribute => semantic_tokens::DECORATOR,
592 SymbolKind::Derive => semantic_tokens::DERIVE,
593 SymbolKind::DeriveHelper => semantic_tokens::DERIVE_HELPER,
594 SymbolKind::Module => semantic_tokens::NAMESPACE,
595 SymbolKind::Impl => semantic_tokens::TYPE_ALIAS,
596 SymbolKind::Field => semantic_tokens::PROPERTY,
597 SymbolKind::TypeParam => semantic_tokens::TYPE_PARAMETER,
598 SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
599 SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
600 SymbolKind::Label => semantic_tokens::LABEL,
601 SymbolKind::ValueParam => semantic_tokens::PARAMETER,
602 SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
603 SymbolKind::SelfType => semantic_tokens::SELF_TYPE_KEYWORD,
604 SymbolKind::Local => semantic_tokens::VARIABLE,
605 SymbolKind::Function => {
606 if highlight.mods.contains(HlMod::Associated) {
607 semantic_tokens::METHOD
609 semantic_tokens::FUNCTION
612 SymbolKind::Const => {
613 mods |= semantic_tokens::CONSTANT;
614 mods |= semantic_tokens::STATIC;
615 semantic_tokens::VARIABLE
617 SymbolKind::Static => {
618 mods |= semantic_tokens::STATIC;
619 semantic_tokens::VARIABLE
621 SymbolKind::Struct => semantic_tokens::STRUCT,
622 SymbolKind::Enum => semantic_tokens::ENUM,
623 SymbolKind::Variant => semantic_tokens::ENUM_MEMBER,
624 SymbolKind::Union => semantic_tokens::UNION,
625 SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
626 SymbolKind::Trait => semantic_tokens::INTERFACE,
627 SymbolKind::Macro => semantic_tokens::MACRO,
628 SymbolKind::BuiltinAttr => semantic_tokens::BUILTIN_ATTRIBUTE,
629 SymbolKind::ToolModule => semantic_tokens::TOOL_MODULE,
631 HlTag::AttributeBracket => semantic_tokens::ATTRIBUTE_BRACKET,
632 HlTag::BoolLiteral => semantic_tokens::BOOLEAN,
633 HlTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
634 HlTag::ByteLiteral | HlTag::NumericLiteral => semantic_tokens::NUMBER,
635 HlTag::CharLiteral => semantic_tokens::CHAR,
636 HlTag::Comment => semantic_tokens::COMMENT,
637 HlTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
638 HlTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
639 HlTag::Keyword => semantic_tokens::KEYWORD,
640 HlTag::None => semantic_tokens::GENERIC,
641 HlTag::Operator(op) => match op {
642 HlOperator::Bitwise => semantic_tokens::BITWISE,
643 HlOperator::Arithmetic => semantic_tokens::ARITHMETIC,
644 HlOperator::Logical => semantic_tokens::LOGICAL,
645 HlOperator::Comparison => semantic_tokens::COMPARISON,
646 HlOperator::Other => semantic_tokens::OPERATOR,
648 HlTag::StringLiteral => semantic_tokens::STRING,
649 HlTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
650 HlTag::Punctuation(punct) => match punct {
651 HlPunct::Bracket => semantic_tokens::BRACKET,
652 HlPunct::Brace => semantic_tokens::BRACE,
653 HlPunct::Parenthesis => semantic_tokens::PARENTHESIS,
654 HlPunct::Angle => semantic_tokens::ANGLE,
655 HlPunct::Comma => semantic_tokens::COMMA,
656 HlPunct::Dot => semantic_tokens::DOT,
657 HlPunct::Colon => semantic_tokens::COLON,
658 HlPunct::Semi => semantic_tokens::SEMICOLON,
659 HlPunct::Other => semantic_tokens::PUNCTUATION,
660 HlPunct::MacroBang => semantic_tokens::MACRO_BANG,
664 for modifier in highlight.mods.iter() {
665 let modifier = match modifier {
666 HlMod::Associated => continue,
667 HlMod::Async => semantic_tokens::ASYNC,
668 HlMod::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
669 HlMod::Callable => semantic_tokens::CALLABLE,
670 HlMod::Consuming => semantic_tokens::CONSUMING,
671 HlMod::ControlFlow => semantic_tokens::CONTROL_FLOW,
672 HlMod::CrateRoot => semantic_tokens::CRATE_ROOT,
673 HlMod::DefaultLibrary => semantic_tokens::DEFAULT_LIBRARY,
674 HlMod::Definition => semantic_tokens::DECLARATION,
675 HlMod::Documentation => semantic_tokens::DOCUMENTATION,
676 HlMod::Injected => semantic_tokens::INJECTED,
677 HlMod::IntraDocLink => semantic_tokens::INTRA_DOC_LINK,
678 HlMod::Library => semantic_tokens::LIBRARY,
679 HlMod::Mutable => semantic_tokens::MUTABLE,
680 HlMod::Public => semantic_tokens::PUBLIC,
681 HlMod::Reference => semantic_tokens::REFERENCE,
682 HlMod::Static => semantic_tokens::STATIC,
683 HlMod::Trait => semantic_tokens::TRAIT_MODIFIER,
684 HlMod::Unsafe => semantic_tokens::UNSAFE,
692 pub(crate) fn folding_range(
694 line_index: &LineIndex,
695 line_folding_only: bool,
697 ) -> lsp_types::FoldingRange {
698 let kind = match fold.kind {
699 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
700 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
701 FoldKind::Region => Some(lsp_types::FoldingRangeKind::Region),
707 | FoldKind::WhereClause
708 | FoldKind::ReturnType
710 | FoldKind::MatchArm => None,
713 let range = range(line_index, fold.range);
715 if line_folding_only {
716 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
717 // even if it contains text not in the folding range. To prevent that we exclude
718 // range.end.line from the folding region if there is more text after range.end
720 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
722 .take_while(|it| *it != '\n')
723 .any(|it| !it.is_whitespace());
725 let end_line = if has_more_text_on_end_line {
726 range.end.line.saturating_sub(1)
731 lsp_types::FoldingRange {
732 start_line: range.start.line,
733 start_character: None,
739 lsp_types::FoldingRange {
740 start_line: range.start.line,
741 start_character: Some(range.start.character),
742 end_line: range.end.line,
743 end_character: Some(range.end.character),
749 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
750 snap.file_id_to_url(file_id)
753 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
754 /// This will only happen when processing windows paths.
756 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
757 pub(crate) fn url_from_abs_path(path: &AbsPath) -> lsp_types::Url {
758 let url = lsp_types::Url::from_file_path(path).unwrap();
759 match path.as_ref().components().next() {
760 Some(path::Component::Prefix(prefix))
761 if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
763 // Need to lowercase driver letter
768 let driver_letter_range = {
769 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
773 let start = scheme.len() + ':'.len_utf8();
774 start..(start + drive_letter.len())
777 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
778 // machinery *also* canonicalizes the drive letter. So, just massage the
780 let mut url: String = url.into();
781 url[driver_letter_range].make_ascii_lowercase();
782 lsp_types::Url::parse(&url).unwrap()
785 pub(crate) fn optional_versioned_text_document_identifier(
786 snap: &GlobalStateSnapshot,
788 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
789 let url = url(snap, file_id);
790 let version = snap.url_file_version(&url);
791 lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
794 pub(crate) fn location(
795 snap: &GlobalStateSnapshot,
797 ) -> Result<lsp_types::Location> {
798 let url = url(snap, frange.file_id);
799 let line_index = snap.file_line_index(frange.file_id)?;
800 let range = range(&line_index, frange.range);
801 let loc = lsp_types::Location::new(url, range);
805 /// Prefer using `location_link`, if the client has the cap.
806 pub(crate) fn location_from_nav(
807 snap: &GlobalStateSnapshot,
808 nav: NavigationTarget,
809 ) -> Result<lsp_types::Location> {
810 let url = url(snap, nav.file_id);
811 let line_index = snap.file_line_index(nav.file_id)?;
812 let range = range(&line_index, nav.full_range);
813 let loc = lsp_types::Location::new(url, range);
817 pub(crate) fn location_link(
818 snap: &GlobalStateSnapshot,
819 src: Option<FileRange>,
820 target: NavigationTarget,
821 ) -> Result<lsp_types::LocationLink> {
822 let origin_selection_range = match src {
824 let line_index = snap.file_line_index(src.file_id)?;
825 let range = range(&line_index, src.range);
830 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
831 let res = lsp_types::LocationLink {
832 origin_selection_range,
835 target_selection_range,
841 snap: &GlobalStateSnapshot,
842 target: NavigationTarget,
843 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
844 let line_index = snap.file_line_index(target.file_id)?;
846 let target_uri = url(snap, target.file_id);
847 let target_range = range(&line_index, target.full_range);
848 let target_selection_range =
849 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
850 Ok((target_uri, target_range, target_selection_range))
853 pub(crate) fn goto_definition_response(
854 snap: &GlobalStateSnapshot,
855 src: Option<FileRange>,
856 targets: Vec<NavigationTarget>,
857 ) -> Result<lsp_types::GotoDefinitionResponse> {
858 if snap.config.location_link() {
861 .map(|nav| location_link(snap, src, nav))
862 .collect::<Result<Vec<_>>>()?;
865 let locations = targets
868 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
870 .collect::<Result<Vec<_>>>()?;
875 fn outside_workspace_annotation_id() -> String {
876 String::from("OutsideWorkspace")
879 pub(crate) fn snippet_text_document_edit(
880 snap: &GlobalStateSnapshot,
884 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
885 let text_document = optional_versioned_text_document_identifier(snap, file_id);
886 let line_index = snap.file_line_index(file_id)?;
887 let mut edits: Vec<_> =
888 edit.into_iter().map(|it| snippet_text_edit(&line_index, is_snippet, it)).collect();
890 if snap.analysis.is_library_file(file_id)? && snap.config.change_annotation_support() {
891 for edit in &mut edits {
892 edit.annotation_id = Some(outside_workspace_annotation_id())
895 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
898 pub(crate) fn snippet_text_document_ops(
899 snap: &GlobalStateSnapshot,
900 file_system_edit: FileSystemEdit,
901 ) -> Cancellable<Vec<lsp_ext::SnippetDocumentChangeOperation>> {
902 let mut ops = Vec::new();
903 match file_system_edit {
904 FileSystemEdit::CreateFile { dst, initial_contents } => {
905 let uri = snap.anchored_path(&dst);
906 let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
911 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
912 if !initial_contents.is_empty() {
914 lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
915 let text_edit = lsp_ext::SnippetTextEdit {
916 range: lsp_types::Range::default(),
917 new_text: initial_contents,
918 insert_text_format: Some(lsp_types::InsertTextFormat::PLAIN_TEXT),
922 lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
923 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
926 FileSystemEdit::MoveFile { src, dst } => {
927 let old_uri = snap.file_id_to_url(src);
928 let new_uri = snap.anchored_path(&dst);
929 let mut rename_file =
930 lsp_types::RenameFile { old_uri, new_uri, options: None, annotation_id: None };
931 if snap.analysis.is_library_file(src).ok() == Some(true)
932 && snap.config.change_annotation_support()
934 rename_file.annotation_id = Some(outside_workspace_annotation_id())
936 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(lsp_types::ResourceOp::Rename(
940 FileSystemEdit::MoveDir { src, src_id, dst } => {
941 let old_uri = snap.anchored_path(&src);
942 let new_uri = snap.anchored_path(&dst);
943 let mut rename_file =
944 lsp_types::RenameFile { old_uri, new_uri, options: None, annotation_id: None };
945 if snap.analysis.is_library_file(src_id).ok() == Some(true)
946 && snap.config.change_annotation_support()
948 rename_file.annotation_id = Some(outside_workspace_annotation_id())
950 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(lsp_types::ResourceOp::Rename(
958 pub(crate) fn snippet_workspace_edit(
959 snap: &GlobalStateSnapshot,
960 source_change: SourceChange,
961 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
962 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
964 for op in source_change.file_system_edits {
965 let ops = snippet_text_document_ops(snap, op)?;
966 document_changes.extend_from_slice(&ops);
968 for (file_id, edit) in source_change.source_file_edits {
969 let edit = snippet_text_document_edit(snap, source_change.is_snippet, file_id, edit)?;
970 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
972 let mut workspace_edit = lsp_ext::SnippetWorkspaceEdit {
974 document_changes: Some(document_changes),
975 change_annotations: None,
977 if snap.config.change_annotation_support() {
978 workspace_edit.change_annotations = Some(
980 outside_workspace_annotation_id(),
981 lsp_types::ChangeAnnotation {
982 label: String::from("Edit outside of the workspace"),
983 needs_confirmation: Some(true),
984 description: Some(String::from(
985 "This edit lies outside of the workspace and may affect dependencies",
995 pub(crate) fn workspace_edit(
996 snap: &GlobalStateSnapshot,
997 source_change: SourceChange,
998 ) -> Result<lsp_types::WorkspaceEdit> {
999 assert!(!source_change.is_snippet);
1000 snippet_workspace_edit(snap, source_change).map(|it| it.into())
1003 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
1004 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
1005 lsp_types::WorkspaceEdit {
1007 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
1008 lsp_types::DocumentChanges::Operations(
1011 .map(|change| match change {
1012 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
1013 lsp_types::DocumentChangeOperation::Op(op)
1015 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
1016 lsp_types::DocumentChangeOperation::Edit(
1017 lsp_types::TextDocumentEdit {
1018 text_document: edit.text_document,
1019 edits: edit.edits.into_iter().map(From::from).collect(),
1027 change_annotations: snippet_workspace_edit.change_annotations,
1032 impl From<lsp_ext::SnippetTextEdit>
1033 for lsp_types::OneOf<lsp_types::TextEdit, lsp_types::AnnotatedTextEdit>
1036 lsp_ext::SnippetTextEdit { annotation_id, insert_text_format:_, new_text, range }: lsp_ext::SnippetTextEdit,
1038 match annotation_id {
1039 Some(annotation_id) => lsp_types::OneOf::Right(lsp_types::AnnotatedTextEdit {
1040 text_edit: lsp_types::TextEdit { range, new_text },
1043 None => lsp_types::OneOf::Left(lsp_types::TextEdit { range, new_text }),
1048 pub(crate) fn call_hierarchy_item(
1049 snap: &GlobalStateSnapshot,
1050 target: NavigationTarget,
1051 ) -> Result<lsp_types::CallHierarchyItem> {
1052 let name = target.name.to_string();
1053 let detail = target.description.clone();
1054 let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::FUNCTION);
1055 let (uri, range, selection_range) = location_info(snap, target)?;
1056 Ok(lsp_types::CallHierarchyItem {
1068 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
1070 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
1071 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
1072 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
1073 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
1074 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
1075 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
1079 pub(crate) fn code_action(
1080 snap: &GlobalStateSnapshot,
1082 resolve_data: Option<(usize, lsp_types::CodeActionParams)>,
1083 ) -> Result<lsp_ext::CodeAction> {
1084 let mut res = lsp_ext::CodeAction {
1085 title: assist.label.to_string(),
1086 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
1087 kind: Some(code_action_kind(assist.id.1)),
1094 if assist.trigger_signature_help && snap.config.client_commands().trigger_parameter_hints {
1095 res.command = Some(command::trigger_parameter_hints());
1098 match (assist.source_change, resolve_data) {
1099 (Some(it), _) => res.edit = Some(snippet_workspace_edit(snap, it)?),
1100 (None, Some((index, code_action_params))) => {
1101 res.data = Some(lsp_ext::CodeActionData {
1102 id: format!("{}:{}:{}", assist.id.0, assist.id.1.name(), index),
1107 stdx::never!("assist should always be resolved if client can't do lazy resolving")
1113 pub(crate) fn runnable(
1114 snap: &GlobalStateSnapshot,
1116 ) -> Result<lsp_ext::Runnable> {
1117 let config = snap.config.runnables();
1118 let spec = CargoTargetSpec::for_file(snap, runnable.nav.file_id)?;
1119 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
1120 let target = spec.as_ref().map(|s| s.target.clone());
1121 let (cargo_args, executable_args) =
1122 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
1123 let label = runnable.label(target);
1124 let location = location_link(snap, None, runnable.nav)?;
1126 Ok(lsp_ext::Runnable {
1128 location: Some(location),
1129 kind: lsp_ext::RunnableKind::Cargo,
1130 args: lsp_ext::CargoRunnable {
1131 workspace_root: workspace_root.map(|it| it.into()),
1132 override_cargo: config.override_cargo,
1134 cargo_extra_args: config.cargo_extra_args,
1141 pub(crate) fn code_lens(
1142 acc: &mut Vec<lsp_types::CodeLens>,
1143 snap: &GlobalStateSnapshot,
1144 annotation: Annotation,
1146 let client_commands_config = snap.config.client_commands();
1147 match annotation.kind {
1148 AnnotationKind::Runnable(run) => {
1149 let line_index = snap.file_line_index(run.nav.file_id)?;
1150 let annotation_range = range(&line_index, annotation.range);
1152 let title = run.title();
1153 let can_debug = match run.kind {
1154 ide::RunnableKind::DocTest { .. } => false,
1155 ide::RunnableKind::TestMod { .. }
1156 | ide::RunnableKind::Test { .. }
1157 | ide::RunnableKind::Bench { .. }
1158 | ide::RunnableKind::Bin => true,
1160 let r = runnable(snap, run)?;
1162 let lens_config = snap.config.lens();
1163 if lens_config.run && client_commands_config.run_single {
1164 let command = command::run_single(&r, &title);
1165 acc.push(lsp_types::CodeLens {
1166 range: annotation_range,
1167 command: Some(command),
1171 if lens_config.debug && can_debug && client_commands_config.debug_single {
1172 let command = command::debug_single(&r);
1173 acc.push(lsp_types::CodeLens {
1174 range: annotation_range,
1175 command: Some(command),
1180 AnnotationKind::HasImpls { file_id, data } => {
1181 if !client_commands_config.show_reference {
1184 let line_index = snap.file_line_index(file_id)?;
1185 let annotation_range = range(&line_index, annotation.range);
1186 let url = url(snap, file_id);
1188 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1190 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, annotation_range.start);
1192 let goto_params = lsp_types::request::GotoImplementationParams {
1193 text_document_position_params: doc_pos,
1194 work_done_progress_params: Default::default(),
1195 partial_result_params: Default::default(),
1198 let command = data.map(|ranges| {
1199 let locations: Vec<lsp_types::Location> = ranges
1201 .filter_map(|target| {
1204 FileRange { file_id: target.file_id, range: target.full_range },
1210 command::show_references(
1211 implementation_title(locations.len()),
1213 annotation_range.start,
1218 acc.push(lsp_types::CodeLens {
1219 range: annotation_range,
1221 data: Some(to_value(lsp_ext::CodeLensResolveData::Impls(goto_params)).unwrap()),
1224 AnnotationKind::HasReferences { file_id, data } => {
1225 if !client_commands_config.show_reference {
1228 let line_index = snap.file_line_index(file_id)?;
1229 let annotation_range = range(&line_index, annotation.range);
1230 let url = url(snap, file_id);
1232 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1234 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, annotation_range.start);
1236 let command = data.map(|ranges| {
1237 let locations: Vec<lsp_types::Location> =
1238 ranges.into_iter().filter_map(|range| location(snap, range).ok()).collect();
1240 command::show_references(
1241 reference_title(locations.len()),
1243 annotation_range.start,
1248 acc.push(lsp_types::CodeLens {
1249 range: annotation_range,
1251 data: Some(to_value(lsp_ext::CodeLensResolveData::References(doc_pos)).unwrap()),
1258 pub(crate) mod command {
1259 use ide::{FileRange, NavigationTarget};
1260 use serde_json::to_value;
1263 global_state::GlobalStateSnapshot,
1265 to_proto::{location, location_link},
1268 pub(crate) fn show_references(
1270 uri: &lsp_types::Url,
1271 position: lsp_types::Position,
1272 locations: Vec<lsp_types::Location>,
1273 ) -> lsp_types::Command {
1274 // We cannot use the 'editor.action.showReferences' command directly
1275 // because that command requires vscode types which we convert in the handler
1276 // on the client side.
1278 lsp_types::Command {
1280 command: "rust-analyzer.showReferences".into(),
1281 arguments: Some(vec![
1282 to_value(uri).unwrap(),
1283 to_value(position).unwrap(),
1284 to_value(locations).unwrap(),
1289 pub(crate) fn run_single(runnable: &lsp_ext::Runnable, title: &str) -> lsp_types::Command {
1290 lsp_types::Command {
1291 title: title.to_string(),
1292 command: "rust-analyzer.runSingle".into(),
1293 arguments: Some(vec![to_value(runnable).unwrap()]),
1297 pub(crate) fn debug_single(runnable: &lsp_ext::Runnable) -> lsp_types::Command {
1298 lsp_types::Command {
1299 title: "Debug".into(),
1300 command: "rust-analyzer.debugSingle".into(),
1301 arguments: Some(vec![to_value(runnable).unwrap()]),
1305 pub(crate) fn goto_location(
1306 snap: &GlobalStateSnapshot,
1307 nav: &NavigationTarget,
1308 ) -> Option<lsp_types::Command> {
1309 let value = if snap.config.location_link() {
1310 let link = location_link(snap, None, nav.clone()).ok()?;
1311 to_value(link).ok()?
1313 let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1314 let location = location(snap, range).ok()?;
1315 to_value(location).ok()?
1318 Some(lsp_types::Command {
1319 title: nav.name.to_string(),
1320 command: "rust-analyzer.gotoLocation".into(),
1321 arguments: Some(vec![value]),
1325 pub(crate) fn trigger_parameter_hints() -> lsp_types::Command {
1326 lsp_types::Command {
1327 title: "triggerParameterHints".into(),
1328 command: "editor.action.triggerParameterHints".into(),
1334 pub(crate) fn implementation_title(count: usize) -> String {
1336 "1 implementation".into()
1338 format!("{} implementations", count)
1342 pub(crate) fn reference_title(count: usize) -> String {
1344 "1 reference".into()
1346 format!("{} references", count)
1350 pub(crate) fn markup_content(
1352 kind: ide::HoverDocFormat,
1353 ) -> lsp_types::MarkupContent {
1354 let kind = match kind {
1355 ide::HoverDocFormat::Markdown => lsp_types::MarkupKind::Markdown,
1356 ide::HoverDocFormat::PlainText => lsp_types::MarkupKind::PlainText,
1358 let value = crate::markdown::format_docs(markup.as_str());
1359 lsp_types::MarkupContent { kind, value }
1362 pub(crate) fn rename_error(err: RenameError) -> crate::LspError {
1363 // This is wrong, but we don't have a better alternative I suppose?
1364 // https://github.com/microsoft/language-server-protocol/issues/1341
1365 invalid_params_error(err.to_string())
1377 fn conv_fold_line_folding_only_fixup() {
1378 let text = r#"mod a;
1390 let (analysis, file_id) = Analysis::from_single_file(text.to_string());
1391 let folds = analysis.folding_ranges(file_id).unwrap();
1392 assert_eq!(folds.len(), 4);
1394 let line_index = LineIndex {
1395 index: Arc::new(ide::LineIndex::new(text)),
1396 endings: LineEndings::Unix,
1397 encoding: OffsetEncoding::Utf16,
1399 let converted: Vec<lsp_types::FoldingRange> =
1400 folds.into_iter().map(|it| folding_range(text, &line_index, true, it)).collect();
1402 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
1403 assert_eq!(converted.len(), expected_lines.len());
1404 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
1405 assert_eq!(folding_range.start_line, *start_line);
1406 assert_eq!(folding_range.start_character, None);
1407 assert_eq!(folding_range.end_line, *end_line);
1408 assert_eq!(folding_range.end_character, None);
1412 // `Url` is not able to parse windows paths on unix machines.
1414 #[cfg(target_os = "windows")]
1415 fn test_lowercase_drive_letter() {
1416 use std::path::Path;
1418 let url = url_from_abs_path(Path::new("C:\\Test").try_into().unwrap());
1419 assert_eq!(url.to_string(), "file:///c:/Test");
1421 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#).try_into().unwrap());
1422 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");