1 //! Conversion of rust-analyzer specific types to lsp_types equivalents.
4 sync::atomic::{AtomicU32, Ordering},
8 Assist, AssistKind, CallInfo, CompletionItem, CompletionItemKind, Documentation, FileId,
9 FileRange, FileSystemEdit, Fold, FoldKind, Highlight, HighlightModifier, HighlightTag,
10 HighlightedRange, Indel, InlayHint, InlayKind, InsertTextFormat, LineIndex, Markup,
11 NavigationTarget, ReferenceAccess, Runnable, Severity, SourceChange, SourceFileEdit,
12 SymbolKind, TextEdit, TextRange, TextSize,
14 use itertools::Itertools;
17 cargo_target_spec::CargoTargetSpec, global_state::GlobalStateSnapshot,
18 line_endings::LineEndings, lsp_ext, semantic_tokens, Result,
21 pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position {
22 let line_col = line_index.line_col(offset);
23 lsp_types::Position::new(line_col.line, line_col.col_utf16)
26 pub(crate) fn range(line_index: &LineIndex, range: TextRange) -> lsp_types::Range {
27 let start = position(line_index, range.start());
28 let end = position(line_index, range.end());
29 lsp_types::Range::new(start, end)
32 pub(crate) fn symbol_kind(symbol_kind: SymbolKind) -> lsp_types::SymbolKind {
34 SymbolKind::Function => lsp_types::SymbolKind::Function,
35 SymbolKind::Struct => lsp_types::SymbolKind::Struct,
36 SymbolKind::Enum => lsp_types::SymbolKind::Enum,
37 SymbolKind::Variant => lsp_types::SymbolKind::EnumMember,
38 SymbolKind::Trait => lsp_types::SymbolKind::Interface,
39 SymbolKind::Macro => lsp_types::SymbolKind::Function,
40 SymbolKind::Module => lsp_types::SymbolKind::Module,
41 SymbolKind::TypeAlias | SymbolKind::TypeParam => lsp_types::SymbolKind::TypeParameter,
42 SymbolKind::Field => lsp_types::SymbolKind::Field,
43 SymbolKind::Static => lsp_types::SymbolKind::Constant,
44 SymbolKind::Const => lsp_types::SymbolKind::Constant,
45 SymbolKind::ConstParam => lsp_types::SymbolKind::Constant,
46 SymbolKind::Impl => lsp_types::SymbolKind::Object,
48 | SymbolKind::SelfParam
49 | SymbolKind::LifetimeParam
50 | SymbolKind::ValueParam
51 | SymbolKind::Label => lsp_types::SymbolKind::Variable,
52 SymbolKind::Union => lsp_types::SymbolKind::Struct,
56 pub(crate) fn document_highlight_kind(
57 reference_access: ReferenceAccess,
58 ) -> lsp_types::DocumentHighlightKind {
59 match reference_access {
60 ReferenceAccess::Read => lsp_types::DocumentHighlightKind::Read,
61 ReferenceAccess::Write => lsp_types::DocumentHighlightKind::Write,
65 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
67 Severity::Error => lsp_types::DiagnosticSeverity::Error,
68 Severity::WeakWarning => lsp_types::DiagnosticSeverity::Hint,
72 pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
73 let value = crate::markdown::format_docs(documentation.as_str());
74 let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
75 lsp_types::Documentation::MarkupContent(markup_content)
78 pub(crate) fn insert_text_format(
79 insert_text_format: InsertTextFormat,
80 ) -> lsp_types::InsertTextFormat {
81 match insert_text_format {
82 InsertTextFormat::Snippet => lsp_types::InsertTextFormat::Snippet,
83 InsertTextFormat::PlainText => lsp_types::InsertTextFormat::PlainText,
87 pub(crate) fn completion_item_kind(
88 completion_item_kind: CompletionItemKind,
89 ) -> lsp_types::CompletionItemKind {
90 match completion_item_kind {
91 CompletionItemKind::Keyword => lsp_types::CompletionItemKind::Keyword,
92 CompletionItemKind::Snippet => lsp_types::CompletionItemKind::Snippet,
93 CompletionItemKind::Module => lsp_types::CompletionItemKind::Module,
94 CompletionItemKind::Function => lsp_types::CompletionItemKind::Function,
95 CompletionItemKind::Struct => lsp_types::CompletionItemKind::Struct,
96 CompletionItemKind::Enum => lsp_types::CompletionItemKind::Enum,
97 CompletionItemKind::EnumVariant => lsp_types::CompletionItemKind::EnumMember,
98 CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::Struct,
99 CompletionItemKind::Binding => lsp_types::CompletionItemKind::Variable,
100 CompletionItemKind::Field => lsp_types::CompletionItemKind::Field,
101 CompletionItemKind::Trait => lsp_types::CompletionItemKind::Interface,
102 CompletionItemKind::TypeAlias => lsp_types::CompletionItemKind::Struct,
103 CompletionItemKind::Const => lsp_types::CompletionItemKind::Constant,
104 CompletionItemKind::Static => lsp_types::CompletionItemKind::Value,
105 CompletionItemKind::Method => lsp_types::CompletionItemKind::Method,
106 CompletionItemKind::TypeParam => lsp_types::CompletionItemKind::TypeParameter,
107 CompletionItemKind::Macro => lsp_types::CompletionItemKind::Method,
108 CompletionItemKind::Attribute => lsp_types::CompletionItemKind::EnumMember,
109 CompletionItemKind::UnresolvedReference => lsp_types::CompletionItemKind::Reference,
113 pub(crate) fn text_edit(
114 line_index: &LineIndex,
115 line_endings: LineEndings,
117 ) -> lsp_types::TextEdit {
118 let range = range(line_index, indel.delete);
119 let new_text = match line_endings {
120 LineEndings::Unix => indel.insert,
121 LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
123 lsp_types::TextEdit { range, new_text }
126 pub(crate) fn snippet_text_edit(
127 line_index: &LineIndex,
128 line_endings: LineEndings,
131 ) -> lsp_ext::SnippetTextEdit {
132 let text_edit = text_edit(line_index, line_endings, indel);
133 let insert_text_format =
134 if is_snippet { Some(lsp_types::InsertTextFormat::Snippet) } else { None };
135 lsp_ext::SnippetTextEdit {
136 range: text_edit.range,
137 new_text: text_edit.new_text,
142 pub(crate) fn text_edit_vec(
143 line_index: &LineIndex,
144 line_endings: LineEndings,
146 ) -> Vec<lsp_types::TextEdit> {
147 text_edit.into_iter().map(|indel| self::text_edit(line_index, line_endings, indel)).collect()
150 pub(crate) fn snippet_text_edit_vec(
151 line_index: &LineIndex,
152 line_endings: LineEndings,
155 ) -> Vec<lsp_ext::SnippetTextEdit> {
158 .map(|indel| self::snippet_text_edit(line_index, line_endings, is_snippet, indel))
162 pub(crate) fn completion_item(
163 line_index: &LineIndex,
164 line_endings: LineEndings,
165 completion_item: CompletionItem,
166 ) -> Vec<lsp_types::CompletionItem> {
167 fn set_score(res: &mut lsp_types::CompletionItem, label: &str) {
168 res.preselect = Some(true);
169 // HACK: sort preselect items first
170 res.sort_text = Some(format!(" {}", label));
173 let mut additional_text_edits = Vec::new();
174 let mut text_edit = None;
175 // LSP does not allow arbitrary edits in completion, so we have to do a
176 // non-trivial mapping here.
177 let source_range = completion_item.source_range();
178 for indel in completion_item.text_edit().iter() {
179 if indel.delete.contains_range(source_range) {
180 text_edit = Some(if indel.delete == source_range {
181 self::text_edit(line_index, line_endings, indel.clone())
183 assert!(source_range.end() == indel.delete.end());
184 let range1 = TextRange::new(indel.delete.start(), source_range.start());
185 let range2 = source_range;
186 let indel1 = Indel::replace(range1, String::new());
187 let indel2 = Indel::replace(range2, indel.insert.clone());
188 additional_text_edits.push(self::text_edit(line_index, line_endings, indel1));
189 self::text_edit(line_index, line_endings, indel2)
192 assert!(source_range.intersect(indel.delete).is_none());
193 let text_edit = self::text_edit(line_index, line_endings, indel.clone());
194 additional_text_edits.push(text_edit);
197 let text_edit = text_edit.unwrap();
199 let mut res = lsp_types::CompletionItem {
200 label: completion_item.label().to_string(),
201 detail: completion_item.detail().map(|it| it.to_string()),
202 filter_text: Some(completion_item.lookup().to_string()),
203 kind: completion_item.kind().map(completion_item_kind),
204 text_edit: Some(text_edit.into()),
205 additional_text_edits: Some(additional_text_edits),
206 documentation: completion_item.documentation().map(documentation),
207 deprecated: Some(completion_item.deprecated()),
211 if completion_item.score().is_some() {
212 set_score(&mut res, completion_item.label());
215 if completion_item.deprecated() {
216 res.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
219 if completion_item.trigger_call_info() {
220 res.command = Some(lsp_types::Command {
221 title: "triggerParameterHints".into(),
222 command: "editor.action.triggerParameterHints".into(),
227 let mut all_results = match completion_item.ref_match() {
229 let mut refed = res.clone();
230 let (mutability, _score) = ref_match;
231 let label = format!("&{}{}", mutability.as_keyword_for_ref(), refed.label);
232 set_score(&mut refed, &label);
239 for mut r in all_results.iter_mut() {
240 r.insert_text_format = Some(insert_text_format(completion_item.insert_text_format()));
245 pub(crate) fn signature_help(
249 ) -> lsp_types::SignatureHelp {
250 let (label, parameters) = match (concise, label_offsets) {
252 let params = call_info
254 .map(|label| lsp_types::ParameterInformation {
255 label: lsp_types::ParameterLabel::Simple(label.to_string()),
258 .collect::<Vec<_>>();
260 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
264 let params = call_info
267 .map(|it| [u32::from(it.start()).into(), u32::from(it.end()).into()])
268 .map(|label_offsets| lsp_types::ParameterInformation {
269 label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
272 .collect::<Vec<_>>();
273 (call_info.signature, params)
276 let mut params = Vec::new();
277 let mut label = String::new();
278 let mut first = true;
279 for param in call_info.parameter_labels() {
281 label.push_str(", ");
284 let start = label.len() as u32;
285 label.push_str(param);
286 let end = label.len() as u32;
287 params.push(lsp_types::ParameterInformation {
288 label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
297 let documentation = if concise {
300 call_info.doc.map(|doc| {
301 lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
302 kind: lsp_types::MarkupKind::Markdown,
308 let active_parameter = call_info.active_parameter.map(|it| it as u32);
310 let signature = lsp_types::SignatureInformation {
313 parameters: Some(parameters),
316 lsp_types::SignatureHelp {
317 signatures: vec![signature],
318 active_signature: None,
323 pub(crate) fn inlay_hint(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
325 label: inlay_hint.label.to_string(),
326 range: range(line_index, inlay_hint.range),
327 kind: match inlay_hint.kind {
328 InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
329 InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
330 InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
335 static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
337 pub(crate) fn semantic_tokens(
339 line_index: &LineIndex,
340 highlights: Vec<HighlightedRange>,
341 ) -> lsp_types::SemanticTokens {
342 let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
343 let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
345 for highlight_range in highlights {
346 let (type_, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
347 let token_index = semantic_tokens::type_index(type_);
348 let modifier_bitset = mods.0;
350 for mut text_range in line_index.lines(highlight_range.range) {
351 if text[text_range].ends_with('\n') {
353 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
355 let range = range(&line_index, text_range);
356 builder.push(range, token_index, modifier_bitset);
363 pub(crate) fn semantic_token_delta(
364 previous: &lsp_types::SemanticTokens,
365 current: &lsp_types::SemanticTokens,
366 ) -> lsp_types::SemanticTokensDelta {
367 let result_id = current.result_id.clone();
368 let edits = semantic_tokens::diff_tokens(&previous.data, ¤t.data);
369 lsp_types::SemanticTokensDelta { result_id, edits }
372 fn semantic_token_type_and_modifiers(
373 highlight: Highlight,
374 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
375 let mut mods = semantic_tokens::ModifierSet::default();
376 let type_ = match highlight.tag {
377 HighlightTag::Symbol(symbol) => match symbol {
378 SymbolKind::Module => lsp_types::SemanticTokenType::NAMESPACE,
379 SymbolKind::Impl => lsp_types::SemanticTokenType::TYPE,
380 SymbolKind::Field => lsp_types::SemanticTokenType::PROPERTY,
381 SymbolKind::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
382 SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
383 SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
384 SymbolKind::Label => semantic_tokens::LABEL,
385 SymbolKind::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
386 SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
387 SymbolKind::Local => lsp_types::SemanticTokenType::VARIABLE,
388 SymbolKind::Function => {
389 if highlight.modifiers.contains(HighlightModifier::Associated) {
390 lsp_types::SemanticTokenType::METHOD
392 lsp_types::SemanticTokenType::FUNCTION
395 SymbolKind::Const => {
396 mods |= semantic_tokens::CONSTANT;
397 mods |= lsp_types::SemanticTokenModifier::STATIC;
398 lsp_types::SemanticTokenType::VARIABLE
400 SymbolKind::Static => {
401 mods |= lsp_types::SemanticTokenModifier::STATIC;
402 lsp_types::SemanticTokenType::VARIABLE
404 SymbolKind::Struct => lsp_types::SemanticTokenType::STRUCT,
405 SymbolKind::Enum => lsp_types::SemanticTokenType::ENUM,
406 SymbolKind::Variant => lsp_types::SemanticTokenType::ENUM_MEMBER,
407 SymbolKind::Union => semantic_tokens::UNION,
408 SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
409 SymbolKind::Trait => lsp_types::SemanticTokenType::INTERFACE,
410 SymbolKind::Macro => lsp_types::SemanticTokenType::MACRO,
412 HighlightTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
413 HighlightTag::Dummy => semantic_tokens::GENERIC,
414 HighlightTag::ByteLiteral | HighlightTag::NumericLiteral => {
415 lsp_types::SemanticTokenType::NUMBER
417 HighlightTag::BoolLiteral => semantic_tokens::BOOLEAN,
418 HighlightTag::CharLiteral | HighlightTag::StringLiteral => {
419 lsp_types::SemanticTokenType::STRING
421 HighlightTag::Comment => lsp_types::SemanticTokenType::COMMENT,
422 HighlightTag::Attribute => semantic_tokens::ATTRIBUTE,
423 HighlightTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
424 HighlightTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
425 HighlightTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
426 HighlightTag::Operator => lsp_types::SemanticTokenType::OPERATOR,
427 HighlightTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
428 HighlightTag::Punctuation => semantic_tokens::PUNCTUATION,
431 for modifier in highlight.modifiers.iter() {
432 let modifier = match modifier {
433 HighlightModifier::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
434 HighlightModifier::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
435 HighlightModifier::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
436 HighlightModifier::Injected => semantic_tokens::INJECTED,
437 HighlightModifier::ControlFlow => semantic_tokens::CONTROL_FLOW,
438 HighlightModifier::Mutable => semantic_tokens::MUTABLE,
439 HighlightModifier::Consuming => semantic_tokens::CONSUMING,
440 HighlightModifier::Unsafe => semantic_tokens::UNSAFE,
441 HighlightModifier::Callable => semantic_tokens::CALLABLE,
442 HighlightModifier::Static => lsp_types::SemanticTokenModifier::STATIC,
443 HighlightModifier::Associated => continue,
451 pub(crate) fn folding_range(
453 line_index: &LineIndex,
454 line_folding_only: bool,
456 ) -> lsp_types::FoldingRange {
457 let kind = match fold.kind {
458 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
459 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
460 FoldKind::Mods | FoldKind::Block | FoldKind::ArgList => None,
463 let range = range(line_index, fold.range);
465 if line_folding_only {
466 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
467 // even if it contains text not in the folding range. To prevent that we exclude
468 // range.end.line from the folding region if there is more text after range.end
470 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
472 .take_while(|it| *it != '\n')
473 .any(|it| !it.is_whitespace());
475 let end_line = if has_more_text_on_end_line {
476 range.end.line.saturating_sub(1)
481 lsp_types::FoldingRange {
482 start_line: range.start.line,
483 start_character: None,
489 lsp_types::FoldingRange {
490 start_line: range.start.line,
491 start_character: Some(range.start.character),
492 end_line: range.end.line,
493 end_character: Some(range.end.character),
499 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
500 snap.file_id_to_url(file_id)
503 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
504 /// This will only happen when processing windows paths.
506 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
507 pub(crate) fn url_from_abs_path(path: &Path) -> lsp_types::Url {
508 assert!(path.is_absolute());
509 let url = lsp_types::Url::from_file_path(path).unwrap();
510 match path.components().next() {
511 Some(path::Component::Prefix(prefix)) if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
513 // Need to lowercase driver letter
518 let driver_letter_range = {
519 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
523 let start = scheme.len() + ':'.len_utf8();
524 start..(start + drive_letter.len())
527 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
528 // machinery *also* canonicalizes the drive letter. So, just massage the
530 let mut url = url.into_string();
531 url[driver_letter_range].make_ascii_lowercase();
532 lsp_types::Url::parse(&url).unwrap()
535 pub(crate) fn optional_versioned_text_document_identifier(
536 snap: &GlobalStateSnapshot,
538 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
539 let url = url(snap, file_id);
540 let version = snap.url_file_version(&url);
541 lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
544 pub(crate) fn location(
545 snap: &GlobalStateSnapshot,
547 ) -> Result<lsp_types::Location> {
548 let url = url(snap, frange.file_id);
549 let line_index = snap.analysis.file_line_index(frange.file_id)?;
550 let range = range(&line_index, frange.range);
551 let loc = lsp_types::Location::new(url, range);
555 /// Perefer using `location_link`, if the client has the cap.
556 pub(crate) fn location_from_nav(
557 snap: &GlobalStateSnapshot,
558 nav: NavigationTarget,
559 ) -> Result<lsp_types::Location> {
560 let url = url(snap, nav.file_id);
561 let line_index = snap.analysis.file_line_index(nav.file_id)?;
562 let range = range(&line_index, nav.full_range);
563 let loc = lsp_types::Location::new(url, range);
567 pub(crate) fn location_link(
568 snap: &GlobalStateSnapshot,
569 src: Option<FileRange>,
570 target: NavigationTarget,
571 ) -> Result<lsp_types::LocationLink> {
572 let origin_selection_range = match src {
574 let line_index = snap.analysis.file_line_index(src.file_id)?;
575 let range = range(&line_index, src.range);
580 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
581 let res = lsp_types::LocationLink {
582 origin_selection_range,
585 target_selection_range,
591 snap: &GlobalStateSnapshot,
592 target: NavigationTarget,
593 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
594 let line_index = snap.analysis.file_line_index(target.file_id)?;
596 let target_uri = url(snap, target.file_id);
597 let target_range = range(&line_index, target.full_range);
598 let target_selection_range =
599 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
600 Ok((target_uri, target_range, target_selection_range))
603 pub(crate) fn goto_definition_response(
604 snap: &GlobalStateSnapshot,
605 src: Option<FileRange>,
606 targets: Vec<NavigationTarget>,
607 ) -> Result<lsp_types::GotoDefinitionResponse> {
608 if snap.config.client_caps.location_link {
611 .map(|nav| location_link(snap, src, nav))
612 .collect::<Result<Vec<_>>>()?;
615 let locations = targets
618 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
620 .collect::<Result<Vec<_>>>()?;
625 pub(crate) fn snippet_text_document_edit(
626 snap: &GlobalStateSnapshot,
628 source_file_edit: SourceFileEdit,
629 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
630 let text_document = optional_versioned_text_document_identifier(snap, source_file_edit.file_id);
631 let line_index = snap.analysis.file_line_index(source_file_edit.file_id)?;
632 let line_endings = snap.file_line_endings(source_file_edit.file_id);
633 let edits = source_file_edit
636 .map(|it| snippet_text_edit(&line_index, line_endings, is_snippet, it))
638 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
641 pub(crate) fn snippet_text_document_ops(
642 snap: &GlobalStateSnapshot,
643 file_system_edit: FileSystemEdit,
644 ) -> Vec<lsp_ext::SnippetDocumentChangeOperation> {
645 let mut ops = Vec::new();
646 match file_system_edit {
647 FileSystemEdit::CreateFile { dst, initial_contents } => {
648 let uri = snap.anchored_path(&dst);
649 let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
654 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
655 if !initial_contents.is_empty() {
657 lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
658 let range = range(&LineIndex::new(""), TextRange::empty(TextSize::from(0)));
659 let text_edit = lsp_ext::SnippetTextEdit {
661 new_text: initial_contents,
662 insert_text_format: Some(lsp_types::InsertTextFormat::PlainText),
665 lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
666 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
669 FileSystemEdit::MoveFile { src, dst } => {
670 let old_uri = snap.file_id_to_url(src);
671 let new_uri = snap.anchored_path(&dst);
672 let rename_file = lsp_types::ResourceOp::Rename(lsp_types::RenameFile {
678 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(rename_file))
684 pub(crate) fn snippet_workspace_edit(
685 snap: &GlobalStateSnapshot,
686 source_change: SourceChange,
687 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
688 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
689 for op in source_change.file_system_edits {
690 let ops = snippet_text_document_ops(snap, op);
691 document_changes.extend_from_slice(&ops);
693 for edit in source_change.source_file_edits {
694 let edit = snippet_text_document_edit(&snap, source_change.is_snippet, edit)?;
695 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
698 lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
702 pub(crate) fn workspace_edit(
703 snap: &GlobalStateSnapshot,
704 source_change: SourceChange,
705 ) -> Result<lsp_types::WorkspaceEdit> {
706 assert!(!source_change.is_snippet);
707 snippet_workspace_edit(snap, source_change).map(|it| it.into())
710 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
711 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
712 lsp_types::WorkspaceEdit {
714 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
715 lsp_types::DocumentChanges::Operations(
718 .map(|change| match change {
719 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
720 lsp_types::DocumentChangeOperation::Op(op)
722 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
723 lsp_types::DocumentChangeOperation::Edit(
724 lsp_types::TextDocumentEdit {
725 text_document: edit.text_document,
730 lsp_types::OneOf::Left(lsp_types::TextEdit {
732 new_text: edit.new_text,
743 change_annotations: None,
748 pub(crate) fn call_hierarchy_item(
749 snap: &GlobalStateSnapshot,
750 target: NavigationTarget,
751 ) -> Result<lsp_types::CallHierarchyItem> {
752 let name = target.name.to_string();
753 let detail = target.description.clone();
754 let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::Function);
755 let (uri, range, selection_range) = location_info(snap, target)?;
756 Ok(lsp_types::CallHierarchyItem {
768 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
770 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
771 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
772 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
773 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
774 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
775 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
779 pub(crate) fn unresolved_code_action(
780 snap: &GlobalStateSnapshot,
781 code_action_params: lsp_types::CodeActionParams,
784 ) -> Result<lsp_ext::CodeAction> {
785 assert!(assist.source_change.is_none());
786 let res = lsp_ext::CodeAction {
787 title: assist.label.to_string(),
788 group: assist.group.filter(|_| snap.config.client_caps.code_action_group).map(|gr| gr.0),
789 kind: Some(code_action_kind(assist.id.1)),
792 data: Some(lsp_ext::CodeActionData {
793 id: format!("{}:{}", assist.id.0, index.to_string()),
800 pub(crate) fn resolved_code_action(
801 snap: &GlobalStateSnapshot,
803 ) -> Result<lsp_ext::CodeAction> {
804 let change = assist.source_change.unwrap();
805 let res = lsp_ext::CodeAction {
806 edit: Some(snippet_workspace_edit(snap, change)?),
807 title: assist.label.to_string(),
808 group: assist.group.filter(|_| snap.config.client_caps.code_action_group).map(|gr| gr.0),
809 kind: Some(code_action_kind(assist.id.1)),
816 pub(crate) fn runnable(
817 snap: &GlobalStateSnapshot,
820 ) -> Result<lsp_ext::Runnable> {
821 let config = &snap.config.runnables;
822 let spec = CargoTargetSpec::for_file(snap, file_id)?;
823 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
824 let target = spec.as_ref().map(|s| s.target.clone());
825 let (cargo_args, executable_args) =
826 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
827 let label = runnable.label(target);
828 let location = location_link(snap, None, runnable.nav)?;
830 Ok(lsp_ext::Runnable {
832 location: Some(location),
833 kind: lsp_ext::RunnableKind::Cargo,
834 args: lsp_ext::CargoRunnable {
835 workspace_root: workspace_root.map(|it| it.into()),
836 override_cargo: config.override_cargo.clone(),
838 cargo_extra_args: config.cargo_extra_args.clone(),
845 pub(crate) fn markup_content(markup: Markup) -> lsp_types::MarkupContent {
846 let value = crate::markdown::format_docs(markup.as_str());
847 lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value }
857 fn test_completion_with_ref() {
866 let (offset, text) = test_utils::extract_offset(fixture);
867 let line_index = LineIndex::new(&text);
868 let (analysis, file_id) = Analysis::from_single_file(text);
869 let completions: Vec<(String, Option<String>)> = analysis
871 &ide::CompletionConfig::default(),
872 ide_db::base_db::FilePosition { file_id, offset },
877 .filter(|c| c.label().ends_with("arg"))
878 .map(|c| completion_item(&line_index, LineEndings::Unix, c))
879 .flat_map(|comps| comps.into_iter().map(|c| (c.label, c.sort_text)))
881 expect_test::expect![[r#"
895 .assert_debug_eq(&completions);
899 fn conv_fold_line_folding_only_fixup() {
912 let (analysis, file_id) = Analysis::from_single_file(text.to_string());
913 let folds = analysis.folding_ranges(file_id).unwrap();
914 assert_eq!(folds.len(), 4);
916 let line_index = LineIndex::new(&text);
917 let converted: Vec<lsp_types::FoldingRange> =
918 folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
920 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
921 assert_eq!(converted.len(), expected_lines.len());
922 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
923 assert_eq!(folding_range.start_line, *start_line);
924 assert_eq!(folding_range.start_character, None);
925 assert_eq!(folding_range.end_line, *end_line);
926 assert_eq!(folding_range.end_character, None);
930 // `Url` is not able to parse windows paths on unix machines.
932 #[cfg(target_os = "windows")]
933 fn test_lowercase_drive_letter_with_drive() {
934 let url = url_from_abs_path(Path::new("C:\\Test"));
935 assert_eq!(url.to_string(), "file:///c:/Test");
939 #[cfg(target_os = "windows")]
940 fn test_drive_without_colon_passthrough() {
941 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#));
942 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");