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 if highlight_range.highlight.is_empty() {
349 let (type_, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
350 let token_index = semantic_tokens::type_index(type_);
351 let modifier_bitset = mods.0;
353 for mut text_range in line_index.lines(highlight_range.range) {
354 if text[text_range].ends_with('\n') {
356 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
358 let range = range(&line_index, text_range);
359 builder.push(range, token_index, modifier_bitset);
366 pub(crate) fn semantic_token_delta(
367 previous: &lsp_types::SemanticTokens,
368 current: &lsp_types::SemanticTokens,
369 ) -> lsp_types::SemanticTokensDelta {
370 let result_id = current.result_id.clone();
371 let edits = semantic_tokens::diff_tokens(&previous.data, ¤t.data);
372 lsp_types::SemanticTokensDelta { result_id, edits }
375 fn semantic_token_type_and_modifiers(
376 highlight: Highlight,
377 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
378 let mut mods = semantic_tokens::ModifierSet::default();
379 let type_ = match highlight.tag {
380 HighlightTag::Symbol(symbol) => match symbol {
381 SymbolKind::Module => lsp_types::SemanticTokenType::NAMESPACE,
382 SymbolKind::Impl => lsp_types::SemanticTokenType::TYPE,
383 SymbolKind::Field => lsp_types::SemanticTokenType::PROPERTY,
384 SymbolKind::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
385 SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
386 SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
387 SymbolKind::Label => semantic_tokens::LABEL,
388 SymbolKind::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
389 SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
390 SymbolKind::Local => lsp_types::SemanticTokenType::VARIABLE,
391 SymbolKind::Function => {
392 if highlight.modifiers.contains(HighlightModifier::Associated) {
393 lsp_types::SemanticTokenType::METHOD
395 lsp_types::SemanticTokenType::FUNCTION
398 SymbolKind::Const => {
399 mods |= semantic_tokens::CONSTANT;
400 mods |= lsp_types::SemanticTokenModifier::STATIC;
401 lsp_types::SemanticTokenType::VARIABLE
403 SymbolKind::Static => {
404 mods |= lsp_types::SemanticTokenModifier::STATIC;
405 lsp_types::SemanticTokenType::VARIABLE
407 SymbolKind::Struct => lsp_types::SemanticTokenType::STRUCT,
408 SymbolKind::Enum => lsp_types::SemanticTokenType::ENUM,
409 SymbolKind::Variant => lsp_types::SemanticTokenType::ENUM_MEMBER,
410 SymbolKind::Union => semantic_tokens::UNION,
411 SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
412 SymbolKind::Trait => lsp_types::SemanticTokenType::INTERFACE,
413 SymbolKind::Macro => lsp_types::SemanticTokenType::MACRO,
415 HighlightTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
416 HighlightTag::Dummy => semantic_tokens::GENERIC,
417 HighlightTag::ByteLiteral | HighlightTag::NumericLiteral => {
418 lsp_types::SemanticTokenType::NUMBER
420 HighlightTag::BoolLiteral => semantic_tokens::BOOLEAN,
421 HighlightTag::CharLiteral | HighlightTag::StringLiteral => {
422 lsp_types::SemanticTokenType::STRING
424 HighlightTag::Comment => lsp_types::SemanticTokenType::COMMENT,
425 HighlightTag::Attribute => semantic_tokens::ATTRIBUTE,
426 HighlightTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
427 HighlightTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
428 HighlightTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
429 HighlightTag::Operator => lsp_types::SemanticTokenType::OPERATOR,
430 HighlightTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
431 HighlightTag::Punctuation => semantic_tokens::PUNCTUATION,
434 for modifier in highlight.modifiers.iter() {
435 let modifier = match modifier {
436 HighlightModifier::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
437 HighlightModifier::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
438 HighlightModifier::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
439 HighlightModifier::Injected => semantic_tokens::INJECTED,
440 HighlightModifier::ControlFlow => semantic_tokens::CONTROL_FLOW,
441 HighlightModifier::Mutable => semantic_tokens::MUTABLE,
442 HighlightModifier::Consuming => semantic_tokens::CONSUMING,
443 HighlightModifier::Unsafe => semantic_tokens::UNSAFE,
444 HighlightModifier::Callable => semantic_tokens::CALLABLE,
445 HighlightModifier::Static => lsp_types::SemanticTokenModifier::STATIC,
446 HighlightModifier::Associated => continue,
454 pub(crate) fn folding_range(
456 line_index: &LineIndex,
457 line_folding_only: bool,
459 ) -> lsp_types::FoldingRange {
460 let kind = match fold.kind {
461 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
462 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
463 FoldKind::Mods | FoldKind::Block | FoldKind::ArgList => None,
466 let range = range(line_index, fold.range);
468 if line_folding_only {
469 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
470 // even if it contains text not in the folding range. To prevent that we exclude
471 // range.end.line from the folding region if there is more text after range.end
473 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
475 .take_while(|it| *it != '\n')
476 .any(|it| !it.is_whitespace());
478 let end_line = if has_more_text_on_end_line {
479 range.end.line.saturating_sub(1)
484 lsp_types::FoldingRange {
485 start_line: range.start.line,
486 start_character: None,
492 lsp_types::FoldingRange {
493 start_line: range.start.line,
494 start_character: Some(range.start.character),
495 end_line: range.end.line,
496 end_character: Some(range.end.character),
502 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
503 snap.file_id_to_url(file_id)
506 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
507 /// This will only happen when processing windows paths.
509 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
510 pub(crate) fn url_from_abs_path(path: &Path) -> lsp_types::Url {
511 assert!(path.is_absolute());
512 let url = lsp_types::Url::from_file_path(path).unwrap();
513 match path.components().next() {
514 Some(path::Component::Prefix(prefix)) if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
516 // Need to lowercase driver letter
521 let driver_letter_range = {
522 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
526 let start = scheme.len() + ':'.len_utf8();
527 start..(start + drive_letter.len())
530 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
531 // machinery *also* canonicalizes the drive letter. So, just massage the
533 let mut url = url.into_string();
534 url[driver_letter_range].make_ascii_lowercase();
535 lsp_types::Url::parse(&url).unwrap()
538 pub(crate) fn optional_versioned_text_document_identifier(
539 snap: &GlobalStateSnapshot,
541 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
542 let url = url(snap, file_id);
543 let version = snap.url_file_version(&url);
544 lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
547 pub(crate) fn location(
548 snap: &GlobalStateSnapshot,
550 ) -> Result<lsp_types::Location> {
551 let url = url(snap, frange.file_id);
552 let line_index = snap.analysis.file_line_index(frange.file_id)?;
553 let range = range(&line_index, frange.range);
554 let loc = lsp_types::Location::new(url, range);
558 /// Perefer using `location_link`, if the client has the cap.
559 pub(crate) fn location_from_nav(
560 snap: &GlobalStateSnapshot,
561 nav: NavigationTarget,
562 ) -> Result<lsp_types::Location> {
563 let url = url(snap, nav.file_id);
564 let line_index = snap.analysis.file_line_index(nav.file_id)?;
565 let range = range(&line_index, nav.full_range);
566 let loc = lsp_types::Location::new(url, range);
570 pub(crate) fn location_link(
571 snap: &GlobalStateSnapshot,
572 src: Option<FileRange>,
573 target: NavigationTarget,
574 ) -> Result<lsp_types::LocationLink> {
575 let origin_selection_range = match src {
577 let line_index = snap.analysis.file_line_index(src.file_id)?;
578 let range = range(&line_index, src.range);
583 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
584 let res = lsp_types::LocationLink {
585 origin_selection_range,
588 target_selection_range,
594 snap: &GlobalStateSnapshot,
595 target: NavigationTarget,
596 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
597 let line_index = snap.analysis.file_line_index(target.file_id)?;
599 let target_uri = url(snap, target.file_id);
600 let target_range = range(&line_index, target.full_range);
601 let target_selection_range =
602 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
603 Ok((target_uri, target_range, target_selection_range))
606 pub(crate) fn goto_definition_response(
607 snap: &GlobalStateSnapshot,
608 src: Option<FileRange>,
609 targets: Vec<NavigationTarget>,
610 ) -> Result<lsp_types::GotoDefinitionResponse> {
611 if snap.config.location_link() {
614 .map(|nav| location_link(snap, src, nav))
615 .collect::<Result<Vec<_>>>()?;
618 let locations = targets
621 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
623 .collect::<Result<Vec<_>>>()?;
628 pub(crate) fn snippet_text_document_edit(
629 snap: &GlobalStateSnapshot,
631 source_file_edit: SourceFileEdit,
632 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
633 let text_document = optional_versioned_text_document_identifier(snap, source_file_edit.file_id);
634 let line_index = snap.analysis.file_line_index(source_file_edit.file_id)?;
635 let line_endings = snap.file_line_endings(source_file_edit.file_id);
636 let edits = source_file_edit
639 .map(|it| snippet_text_edit(&line_index, line_endings, is_snippet, it))
641 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
644 pub(crate) fn snippet_text_document_ops(
645 snap: &GlobalStateSnapshot,
646 file_system_edit: FileSystemEdit,
647 ) -> Vec<lsp_ext::SnippetDocumentChangeOperation> {
648 let mut ops = Vec::new();
649 match file_system_edit {
650 FileSystemEdit::CreateFile { dst, initial_contents } => {
651 let uri = snap.anchored_path(&dst);
652 let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
657 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
658 if !initial_contents.is_empty() {
660 lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
661 let range = range(&LineIndex::new(""), TextRange::empty(TextSize::from(0)));
662 let text_edit = lsp_ext::SnippetTextEdit {
664 new_text: initial_contents,
665 insert_text_format: Some(lsp_types::InsertTextFormat::PlainText),
668 lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
669 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
672 FileSystemEdit::MoveFile { src, dst } => {
673 let old_uri = snap.file_id_to_url(src);
674 let new_uri = snap.anchored_path(&dst);
675 let rename_file = lsp_types::ResourceOp::Rename(lsp_types::RenameFile {
681 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(rename_file))
687 pub(crate) fn snippet_workspace_edit(
688 snap: &GlobalStateSnapshot,
689 source_change: SourceChange,
690 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
691 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
692 for op in source_change.file_system_edits {
693 let ops = snippet_text_document_ops(snap, op);
694 document_changes.extend_from_slice(&ops);
696 for edit in source_change.source_file_edits {
697 let edit = snippet_text_document_edit(&snap, source_change.is_snippet, edit)?;
698 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
701 lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
705 pub(crate) fn workspace_edit(
706 snap: &GlobalStateSnapshot,
707 source_change: SourceChange,
708 ) -> Result<lsp_types::WorkspaceEdit> {
709 assert!(!source_change.is_snippet);
710 snippet_workspace_edit(snap, source_change).map(|it| it.into())
713 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
714 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
715 lsp_types::WorkspaceEdit {
717 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
718 lsp_types::DocumentChanges::Operations(
721 .map(|change| match change {
722 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
723 lsp_types::DocumentChangeOperation::Op(op)
725 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
726 lsp_types::DocumentChangeOperation::Edit(
727 lsp_types::TextDocumentEdit {
728 text_document: edit.text_document,
733 lsp_types::OneOf::Left(lsp_types::TextEdit {
735 new_text: edit.new_text,
746 change_annotations: None,
751 pub(crate) fn call_hierarchy_item(
752 snap: &GlobalStateSnapshot,
753 target: NavigationTarget,
754 ) -> Result<lsp_types::CallHierarchyItem> {
755 let name = target.name.to_string();
756 let detail = target.description.clone();
757 let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::Function);
758 let (uri, range, selection_range) = location_info(snap, target)?;
759 Ok(lsp_types::CallHierarchyItem {
771 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
773 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
774 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
775 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
776 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
777 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
778 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
782 pub(crate) fn unresolved_code_action(
783 snap: &GlobalStateSnapshot,
784 code_action_params: lsp_types::CodeActionParams,
787 ) -> Result<lsp_ext::CodeAction> {
788 assert!(assist.source_change.is_none());
789 let res = lsp_ext::CodeAction {
790 title: assist.label.to_string(),
791 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
792 kind: Some(code_action_kind(assist.id.1)),
795 data: Some(lsp_ext::CodeActionData {
796 id: format!("{}:{}", assist.id.0, index.to_string()),
803 pub(crate) fn resolved_code_action(
804 snap: &GlobalStateSnapshot,
806 ) -> Result<lsp_ext::CodeAction> {
807 let change = assist.source_change.unwrap();
808 let res = lsp_ext::CodeAction {
809 edit: Some(snippet_workspace_edit(snap, change)?),
810 title: assist.label.to_string(),
811 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
812 kind: Some(code_action_kind(assist.id.1)),
819 pub(crate) fn runnable(
820 snap: &GlobalStateSnapshot,
823 ) -> Result<lsp_ext::Runnable> {
824 let config = snap.config.runnables();
825 let spec = CargoTargetSpec::for_file(snap, file_id)?;
826 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
827 let target = spec.as_ref().map(|s| s.target.clone());
828 let (cargo_args, executable_args) =
829 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
830 let label = runnable.label(target);
831 let location = location_link(snap, None, runnable.nav)?;
833 Ok(lsp_ext::Runnable {
835 location: Some(location),
836 kind: lsp_ext::RunnableKind::Cargo,
837 args: lsp_ext::CargoRunnable {
838 workspace_root: workspace_root.map(|it| it.into()),
839 override_cargo: config.override_cargo,
841 cargo_extra_args: config.cargo_extra_args,
848 pub(crate) fn markup_content(markup: Markup) -> lsp_types::MarkupContent {
849 let value = crate::markdown::format_docs(markup.as_str());
850 lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value }
856 use ide_db::helpers::SnippetCap;
861 fn test_completion_with_ref() {
870 let (offset, text) = test_utils::extract_offset(fixture);
871 let line_index = LineIndex::new(&text);
872 let (analysis, file_id) = Analysis::from_single_file(text);
873 let completions: Vec<(String, Option<String>)> = analysis
875 &ide::CompletionConfig {
876 enable_postfix_completions: true,
877 enable_autoimport_completions: true,
878 add_call_parenthesis: true,
879 add_call_argument_snippets: true,
880 snippet_cap: SnippetCap::new(true),
883 ide_db::base_db::FilePosition { file_id, offset },
888 .filter(|c| c.label().ends_with("arg"))
889 .map(|c| completion_item(&line_index, LineEndings::Unix, c))
890 .flat_map(|comps| comps.into_iter().map(|c| (c.label, c.sort_text)))
892 expect_test::expect![[r#"
906 .assert_debug_eq(&completions);
910 fn conv_fold_line_folding_only_fixup() {
923 let (analysis, file_id) = Analysis::from_single_file(text.to_string());
924 let folds = analysis.folding_ranges(file_id).unwrap();
925 assert_eq!(folds.len(), 4);
927 let line_index = LineIndex::new(&text);
928 let converted: Vec<lsp_types::FoldingRange> =
929 folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
931 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
932 assert_eq!(converted.len(), expected_lines.len());
933 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
934 assert_eq!(folding_range.start_line, *start_line);
935 assert_eq!(folding_range.start_character, None);
936 assert_eq!(folding_range.end_line, *end_line);
937 assert_eq!(folding_range.end_character, None);
941 // `Url` is not able to parse windows paths on unix machines.
943 #[cfg(target_os = "windows")]
944 fn test_lowercase_drive_letter_with_drive() {
945 let url = url_from_abs_path(Path::new("C:\\Test"));
946 assert_eq!(url.to_string(), "file:///c:/Test");
950 #[cfg(target_os = "windows")]
951 fn test_drive_without_colon_passthrough() {
952 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#));
953 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");