1 //! Conversion of rust-analyzer specific types to lsp_types equivalents.
4 sync::atomic::{AtomicU32, Ordering},
8 Assist, AssistKind, CallInfo, CompletionItem, CompletionItemKind, Documentation,
9 FileSystemEdit, Fold, FoldKind, Highlight, HighlightModifier, HighlightTag, HighlightedRange,
10 Indel, InlayHint, InlayKind, InsertTextFormat, LineIndex, Markup, NavigationTarget,
11 ReferenceAccess, ResolvedAssist, Runnable, Severity, SourceChange, SourceFileEdit, TextEdit,
13 use ide_db::base_db::{FileId, FileRange};
14 use itertools::Itertools;
15 use syntax::{SyntaxKind, TextRange, TextSize};
18 cargo_target_spec::CargoTargetSpec, global_state::GlobalStateSnapshot,
19 line_endings::LineEndings, lsp_ext, semantic_tokens, Result,
22 pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position {
23 let line_col = line_index.line_col(offset);
24 lsp_types::Position::new(line_col.line, line_col.col_utf16)
27 pub(crate) fn range(line_index: &LineIndex, range: TextRange) -> lsp_types::Range {
28 let start = position(line_index, range.start());
29 let end = position(line_index, range.end());
30 lsp_types::Range::new(start, end)
33 pub(crate) fn symbol_kind(syntax_kind: SyntaxKind) -> lsp_types::SymbolKind {
35 SyntaxKind::FN => lsp_types::SymbolKind::Function,
36 SyntaxKind::STRUCT => lsp_types::SymbolKind::Struct,
37 SyntaxKind::ENUM => lsp_types::SymbolKind::Enum,
38 SyntaxKind::VARIANT => lsp_types::SymbolKind::EnumMember,
39 SyntaxKind::TRAIT => lsp_types::SymbolKind::Interface,
40 SyntaxKind::MACRO_CALL => lsp_types::SymbolKind::Function,
41 SyntaxKind::MODULE => lsp_types::SymbolKind::Module,
42 SyntaxKind::TYPE_ALIAS => lsp_types::SymbolKind::TypeParameter,
43 SyntaxKind::RECORD_FIELD => lsp_types::SymbolKind::Field,
44 SyntaxKind::STATIC => lsp_types::SymbolKind::Constant,
45 SyntaxKind::CONST => lsp_types::SymbolKind::Constant,
46 SyntaxKind::IMPL => lsp_types::SymbolKind::Object,
47 _ => lsp_types::SymbolKind::Variable,
51 pub(crate) fn document_highlight_kind(
52 reference_access: ReferenceAccess,
53 ) -> lsp_types::DocumentHighlightKind {
54 match reference_access {
55 ReferenceAccess::Read => lsp_types::DocumentHighlightKind::Read,
56 ReferenceAccess::Write => lsp_types::DocumentHighlightKind::Write,
60 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
62 Severity::Error => lsp_types::DiagnosticSeverity::Error,
63 Severity::WeakWarning => lsp_types::DiagnosticSeverity::Hint,
67 pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
68 let value = crate::markdown::format_docs(documentation.as_str());
69 let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
70 lsp_types::Documentation::MarkupContent(markup_content)
73 pub(crate) fn insert_text_format(
74 insert_text_format: InsertTextFormat,
75 ) -> lsp_types::InsertTextFormat {
76 match insert_text_format {
77 InsertTextFormat::Snippet => lsp_types::InsertTextFormat::Snippet,
78 InsertTextFormat::PlainText => lsp_types::InsertTextFormat::PlainText,
82 pub(crate) fn completion_item_kind(
83 completion_item_kind: CompletionItemKind,
84 ) -> lsp_types::CompletionItemKind {
85 match completion_item_kind {
86 CompletionItemKind::Keyword => lsp_types::CompletionItemKind::Keyword,
87 CompletionItemKind::Snippet => lsp_types::CompletionItemKind::Snippet,
88 CompletionItemKind::Module => lsp_types::CompletionItemKind::Module,
89 CompletionItemKind::Function => lsp_types::CompletionItemKind::Function,
90 CompletionItemKind::Struct => lsp_types::CompletionItemKind::Struct,
91 CompletionItemKind::Enum => lsp_types::CompletionItemKind::Enum,
92 CompletionItemKind::EnumVariant => lsp_types::CompletionItemKind::EnumMember,
93 CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::Struct,
94 CompletionItemKind::Binding => lsp_types::CompletionItemKind::Variable,
95 CompletionItemKind::Field => lsp_types::CompletionItemKind::Field,
96 CompletionItemKind::Trait => lsp_types::CompletionItemKind::Interface,
97 CompletionItemKind::TypeAlias => lsp_types::CompletionItemKind::Struct,
98 CompletionItemKind::Const => lsp_types::CompletionItemKind::Constant,
99 CompletionItemKind::Static => lsp_types::CompletionItemKind::Value,
100 CompletionItemKind::Method => lsp_types::CompletionItemKind::Method,
101 CompletionItemKind::TypeParam => lsp_types::CompletionItemKind::TypeParameter,
102 CompletionItemKind::Macro => lsp_types::CompletionItemKind::Method,
103 CompletionItemKind::Attribute => lsp_types::CompletionItemKind::EnumMember,
104 CompletionItemKind::UnresolvedReference => lsp_types::CompletionItemKind::Reference,
108 pub(crate) fn text_edit(
109 line_index: &LineIndex,
110 line_endings: LineEndings,
112 ) -> lsp_types::TextEdit {
113 let range = range(line_index, indel.delete);
114 let new_text = match line_endings {
115 LineEndings::Unix => indel.insert,
116 LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
118 lsp_types::TextEdit { range, new_text }
121 pub(crate) fn snippet_text_edit(
122 line_index: &LineIndex,
123 line_endings: LineEndings,
126 ) -> lsp_ext::SnippetTextEdit {
127 let text_edit = text_edit(line_index, line_endings, indel);
128 let insert_text_format =
129 if is_snippet { Some(lsp_types::InsertTextFormat::Snippet) } else { None };
130 lsp_ext::SnippetTextEdit {
131 range: text_edit.range,
132 new_text: text_edit.new_text,
137 pub(crate) fn text_edit_vec(
138 line_index: &LineIndex,
139 line_endings: LineEndings,
141 ) -> Vec<lsp_types::TextEdit> {
142 text_edit.into_iter().map(|indel| self::text_edit(line_index, line_endings, indel)).collect()
145 pub(crate) fn snippet_text_edit_vec(
146 line_index: &LineIndex,
147 line_endings: LineEndings,
150 ) -> Vec<lsp_ext::SnippetTextEdit> {
153 .map(|indel| self::snippet_text_edit(line_index, line_endings, is_snippet, indel))
157 pub(crate) fn completion_item(
158 line_index: &LineIndex,
159 line_endings: LineEndings,
160 completion_item: CompletionItem,
161 ) -> Vec<lsp_types::CompletionItem> {
162 fn set_score(res: &mut lsp_types::CompletionItem, label: &str) {
163 res.preselect = Some(true);
164 // HACK: sort preselect items first
165 res.sort_text = Some(format!(" {}", label));
168 let mut additional_text_edits = Vec::new();
169 let mut text_edit = None;
170 // LSP does not allow arbitrary edits in completion, so we have to do a
171 // non-trivial mapping here.
172 let source_range = completion_item.source_range();
173 for indel in completion_item.text_edit().iter() {
174 if indel.delete.contains_range(source_range) {
175 text_edit = Some(if indel.delete == source_range {
176 self::text_edit(line_index, line_endings, indel.clone())
178 assert!(source_range.end() == indel.delete.end());
179 let range1 = TextRange::new(indel.delete.start(), source_range.start());
180 let range2 = source_range;
181 let indel1 = Indel::replace(range1, String::new());
182 let indel2 = Indel::replace(range2, indel.insert.clone());
183 additional_text_edits.push(self::text_edit(line_index, line_endings, indel1));
184 self::text_edit(line_index, line_endings, indel2)
187 assert!(source_range.intersect(indel.delete).is_none());
188 let text_edit = self::text_edit(line_index, line_endings, indel.clone());
189 additional_text_edits.push(text_edit);
192 let text_edit = text_edit.unwrap();
194 let mut res = lsp_types::CompletionItem {
195 label: completion_item.label().to_string(),
196 detail: completion_item.detail().map(|it| it.to_string()),
197 filter_text: Some(completion_item.lookup().to_string()),
198 kind: completion_item.kind().map(completion_item_kind),
199 text_edit: Some(text_edit.into()),
200 additional_text_edits: Some(additional_text_edits),
201 documentation: completion_item.documentation().map(documentation),
202 deprecated: Some(completion_item.deprecated()),
206 if completion_item.score().is_some() {
207 set_score(&mut res, completion_item.label());
210 if completion_item.deprecated() {
211 res.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
214 if completion_item.trigger_call_info() {
215 res.command = Some(lsp_types::Command {
216 title: "triggerParameterHints".into(),
217 command: "editor.action.triggerParameterHints".into(),
222 let mut all_results = match completion_item.ref_match() {
224 let mut refed = res.clone();
225 let (mutability, _score) = ref_match;
226 let label = format!("&{}{}", mutability.as_keyword_for_ref(), refed.label);
227 set_score(&mut refed, &label);
234 for mut r in all_results.iter_mut() {
235 r.insert_text_format = Some(insert_text_format(completion_item.insert_text_format()));
240 pub(crate) fn signature_help(
244 ) -> lsp_types::SignatureHelp {
245 let (label, parameters) = match (concise, label_offsets) {
247 let params = call_info
249 .map(|label| lsp_types::ParameterInformation {
250 label: lsp_types::ParameterLabel::Simple(label.to_string()),
253 .collect::<Vec<_>>();
255 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
259 let params = call_info
262 .map(|it| [u32::from(it.start()).into(), u32::from(it.end()).into()])
263 .map(|label_offsets| lsp_types::ParameterInformation {
264 label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
267 .collect::<Vec<_>>();
268 (call_info.signature, params)
271 let mut params = Vec::new();
272 let mut label = String::new();
273 let mut first = true;
274 for param in call_info.parameter_labels() {
276 label.push_str(", ");
279 let start = label.len() as u32;
280 label.push_str(param);
281 let end = label.len() as u32;
282 params.push(lsp_types::ParameterInformation {
283 label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
292 let documentation = if concise {
295 call_info.doc.map(|doc| {
296 lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
297 kind: lsp_types::MarkupKind::Markdown,
303 let active_parameter = call_info.active_parameter.map(|it| it as u32);
305 let signature = lsp_types::SignatureInformation {
308 parameters: Some(parameters),
311 lsp_types::SignatureHelp {
312 signatures: vec![signature],
313 active_signature: None,
318 pub(crate) fn inlay_hint(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
320 label: inlay_hint.label.to_string(),
321 range: range(line_index, inlay_hint.range),
322 kind: match inlay_hint.kind {
323 InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
324 InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
325 InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
330 static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
332 pub(crate) fn semantic_tokens(
334 line_index: &LineIndex,
335 highlights: Vec<HighlightedRange>,
336 ) -> lsp_types::SemanticTokens {
337 let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
338 let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
340 for highlight_range in highlights {
341 let (type_, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
342 let token_index = semantic_tokens::type_index(type_);
343 let modifier_bitset = mods.0;
345 for mut text_range in line_index.lines(highlight_range.range) {
346 if text[text_range].ends_with('\n') {
348 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
350 let range = range(&line_index, text_range);
351 builder.push(range, token_index, modifier_bitset);
358 pub(crate) fn semantic_token_delta(
359 previous: &lsp_types::SemanticTokens,
360 current: &lsp_types::SemanticTokens,
361 ) -> lsp_types::SemanticTokensDelta {
362 let result_id = current.result_id.clone();
363 let edits = semantic_tokens::diff_tokens(&previous.data, ¤t.data);
364 lsp_types::SemanticTokensDelta { result_id, edits }
367 fn semantic_token_type_and_modifiers(
368 highlight: Highlight,
369 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
370 let mut mods = semantic_tokens::ModifierSet::default();
371 let type_ = match highlight.tag {
372 HighlightTag::Struct => lsp_types::SemanticTokenType::STRUCT,
373 HighlightTag::Enum => lsp_types::SemanticTokenType::ENUM,
374 HighlightTag::Union => semantic_tokens::UNION,
375 HighlightTag::TypeAlias => semantic_tokens::TYPE_ALIAS,
376 HighlightTag::Trait => lsp_types::SemanticTokenType::INTERFACE,
377 HighlightTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
378 HighlightTag::SelfKeyword => semantic_tokens::SELF_KEYWORD,
379 HighlightTag::SelfType => lsp_types::SemanticTokenType::TYPE,
380 HighlightTag::Field => lsp_types::SemanticTokenType::PROPERTY,
381 HighlightTag::Function => lsp_types::SemanticTokenType::FUNCTION,
382 HighlightTag::Generic => semantic_tokens::GENERIC,
383 HighlightTag::Module => lsp_types::SemanticTokenType::NAMESPACE,
384 HighlightTag::Method => lsp_types::SemanticTokenType::METHOD,
385 HighlightTag::Constant => {
386 mods |= semantic_tokens::CONSTANT;
387 mods |= lsp_types::SemanticTokenModifier::STATIC;
388 lsp_types::SemanticTokenType::VARIABLE
390 HighlightTag::Static => {
391 mods |= lsp_types::SemanticTokenModifier::STATIC;
392 lsp_types::SemanticTokenType::VARIABLE
394 HighlightTag::EnumVariant => lsp_types::SemanticTokenType::ENUM_MEMBER,
395 HighlightTag::Macro => lsp_types::SemanticTokenType::MACRO,
396 HighlightTag::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
397 HighlightTag::Local => lsp_types::SemanticTokenType::VARIABLE,
398 HighlightTag::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
399 HighlightTag::Lifetime => semantic_tokens::LIFETIME,
400 HighlightTag::ByteLiteral | HighlightTag::NumericLiteral => {
401 lsp_types::SemanticTokenType::NUMBER
403 HighlightTag::BoolLiteral => semantic_tokens::BOOLEAN,
404 HighlightTag::CharLiteral | HighlightTag::StringLiteral => {
405 lsp_types::SemanticTokenType::STRING
407 HighlightTag::Comment => lsp_types::SemanticTokenType::COMMENT,
408 HighlightTag::Attribute => semantic_tokens::ATTRIBUTE,
409 HighlightTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
410 HighlightTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
411 HighlightTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
412 HighlightTag::Operator => lsp_types::SemanticTokenType::OPERATOR,
413 HighlightTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
414 HighlightTag::Punctuation => semantic_tokens::PUNCTUATION,
417 for modifier in highlight.modifiers.iter() {
418 let modifier = match modifier {
419 HighlightModifier::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
420 HighlightModifier::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
421 HighlightModifier::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
422 HighlightModifier::Injected => semantic_tokens::INJECTED,
423 HighlightModifier::ControlFlow => semantic_tokens::CONTROL_FLOW,
424 HighlightModifier::Mutable => semantic_tokens::MUTABLE,
425 HighlightModifier::Consuming => semantic_tokens::CONSUMING,
426 HighlightModifier::Unsafe => semantic_tokens::UNSAFE,
427 HighlightModifier::Callable => semantic_tokens::CALLABLE,
428 HighlightModifier::Static => lsp_types::SemanticTokenModifier::STATIC,
436 pub(crate) fn folding_range(
438 line_index: &LineIndex,
439 line_folding_only: bool,
441 ) -> lsp_types::FoldingRange {
442 let kind = match fold.kind {
443 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
444 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
445 FoldKind::Mods | FoldKind::Block | FoldKind::ArgList => None,
448 let range = range(line_index, fold.range);
450 if line_folding_only {
451 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
452 // even if it contains text not in the folding range. To prevent that we exclude
453 // range.end.line from the folding region if there is more text after range.end
455 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
457 .take_while(|it| *it != '\n')
458 .any(|it| !it.is_whitespace());
460 let end_line = if has_more_text_on_end_line {
461 range.end.line.saturating_sub(1)
466 lsp_types::FoldingRange {
467 start_line: range.start.line,
468 start_character: None,
474 lsp_types::FoldingRange {
475 start_line: range.start.line,
476 start_character: Some(range.start.character),
477 end_line: range.end.line,
478 end_character: Some(range.end.character),
484 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
485 snap.file_id_to_url(file_id)
488 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
489 /// This will only happen when processing windows paths.
491 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
492 pub(crate) fn url_from_abs_path(path: &Path) -> lsp_types::Url {
493 assert!(path.is_absolute());
494 let url = lsp_types::Url::from_file_path(path).unwrap();
495 match path.components().next() {
496 Some(path::Component::Prefix(prefix)) if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
498 // Need to lowercase driver letter
503 let driver_letter_range = {
504 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
508 let start = scheme.len() + ':'.len_utf8();
509 start..(start + drive_letter.len())
512 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
513 // machinery *also* canonicalizes the drive letter. So, just massage the
515 let mut url = url.into_string();
516 url[driver_letter_range].make_ascii_lowercase();
517 lsp_types::Url::parse(&url).unwrap()
520 pub(crate) fn optional_versioned_text_document_identifier(
521 snap: &GlobalStateSnapshot,
523 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
524 let url = url(snap, file_id);
525 let version = snap.url_file_version(&url);
526 lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
529 pub(crate) fn location(
530 snap: &GlobalStateSnapshot,
532 ) -> Result<lsp_types::Location> {
533 let url = url(snap, frange.file_id);
534 let line_index = snap.analysis.file_line_index(frange.file_id)?;
535 let range = range(&line_index, frange.range);
536 let loc = lsp_types::Location::new(url, range);
540 /// Perefer using `location_link`, if the client has the cap.
541 pub(crate) fn location_from_nav(
542 snap: &GlobalStateSnapshot,
543 nav: NavigationTarget,
544 ) -> Result<lsp_types::Location> {
545 let url = url(snap, nav.file_id);
546 let line_index = snap.analysis.file_line_index(nav.file_id)?;
547 let range = range(&line_index, nav.full_range);
548 let loc = lsp_types::Location::new(url, range);
552 pub(crate) fn location_link(
553 snap: &GlobalStateSnapshot,
554 src: Option<FileRange>,
555 target: NavigationTarget,
556 ) -> Result<lsp_types::LocationLink> {
557 let origin_selection_range = match src {
559 let line_index = snap.analysis.file_line_index(src.file_id)?;
560 let range = range(&line_index, src.range);
565 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
566 let res = lsp_types::LocationLink {
567 origin_selection_range,
570 target_selection_range,
576 snap: &GlobalStateSnapshot,
577 target: NavigationTarget,
578 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
579 let line_index = snap.analysis.file_line_index(target.file_id)?;
581 let target_uri = url(snap, target.file_id);
582 let target_range = range(&line_index, target.full_range);
583 let target_selection_range =
584 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
585 Ok((target_uri, target_range, target_selection_range))
588 pub(crate) fn goto_definition_response(
589 snap: &GlobalStateSnapshot,
590 src: Option<FileRange>,
591 targets: Vec<NavigationTarget>,
592 ) -> Result<lsp_types::GotoDefinitionResponse> {
593 if snap.config.client_caps.location_link {
596 .map(|nav| location_link(snap, src, nav))
597 .collect::<Result<Vec<_>>>()?;
600 let locations = targets
603 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
605 .collect::<Result<Vec<_>>>()?;
610 pub(crate) fn snippet_text_document_edit(
611 snap: &GlobalStateSnapshot,
613 source_file_edit: SourceFileEdit,
614 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
615 let text_document = optional_versioned_text_document_identifier(snap, source_file_edit.file_id);
616 let line_index = snap.analysis.file_line_index(source_file_edit.file_id)?;
617 let line_endings = snap.file_line_endings(source_file_edit.file_id);
618 let edits = source_file_edit
621 .map(|it| snippet_text_edit(&line_index, line_endings, is_snippet, it))
623 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
626 pub(crate) fn resource_op(
627 snap: &GlobalStateSnapshot,
628 file_system_edit: FileSystemEdit,
629 ) -> lsp_types::ResourceOp {
630 match file_system_edit {
631 FileSystemEdit::CreateFile { dst } => {
632 let uri = snap.anchored_path(&dst);
633 lsp_types::ResourceOp::Create(lsp_types::CreateFile {
639 FileSystemEdit::MoveFile { src, dst } => {
640 let old_uri = snap.file_id_to_url(src);
641 let new_uri = snap.anchored_path(&dst);
642 lsp_types::ResourceOp::Rename(lsp_types::RenameFile {
652 pub(crate) fn snippet_workspace_edit(
653 snap: &GlobalStateSnapshot,
654 source_change: SourceChange,
655 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
656 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
657 for op in source_change.file_system_edits {
658 let op = resource_op(&snap, op);
659 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Op(op));
661 for edit in source_change.source_file_edits {
662 let edit = snippet_text_document_edit(&snap, source_change.is_snippet, edit)?;
663 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
666 lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
670 pub(crate) fn workspace_edit(
671 snap: &GlobalStateSnapshot,
672 source_change: SourceChange,
673 ) -> Result<lsp_types::WorkspaceEdit> {
674 assert!(!source_change.is_snippet);
675 snippet_workspace_edit(snap, source_change).map(|it| it.into())
678 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
679 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
680 lsp_types::WorkspaceEdit {
682 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
683 lsp_types::DocumentChanges::Operations(
686 .map(|change| match change {
687 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
688 lsp_types::DocumentChangeOperation::Op(op)
690 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
691 lsp_types::DocumentChangeOperation::Edit(
692 lsp_types::TextDocumentEdit {
693 text_document: edit.text_document,
698 lsp_types::OneOf::Left(lsp_types::TextEdit {
700 new_text: edit.new_text,
715 pub(crate) fn call_hierarchy_item(
716 snap: &GlobalStateSnapshot,
717 target: NavigationTarget,
718 ) -> Result<lsp_types::CallHierarchyItem> {
719 let name = target.name.to_string();
720 let detail = target.description.clone();
721 let kind = symbol_kind(target.kind);
722 let (uri, range, selection_range) = location_info(snap, target)?;
723 Ok(lsp_types::CallHierarchyItem {
735 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
737 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
738 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
739 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
740 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
741 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
742 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
746 pub(crate) fn unresolved_code_action(
747 snap: &GlobalStateSnapshot,
748 code_action_params: lsp_types::CodeActionParams,
751 ) -> Result<lsp_ext::CodeAction> {
752 let res = lsp_ext::CodeAction {
753 title: assist.label.to_string(),
754 group: assist.group.filter(|_| snap.config.client_caps.code_action_group).map(|gr| gr.0),
755 kind: Some(code_action_kind(assist.id.1)),
758 data: Some(lsp_ext::CodeActionData {
759 id: format!("{}:{}", assist.id.0, index.to_string()),
766 pub(crate) fn resolved_code_action(
767 snap: &GlobalStateSnapshot,
768 assist: ResolvedAssist,
769 ) -> Result<lsp_ext::CodeAction> {
770 let change = assist.source_change;
771 let res = lsp_ext::CodeAction {
772 edit: Some(snippet_workspace_edit(snap, change)?),
773 title: assist.assist.label.to_string(),
777 .filter(|_| snap.config.client_caps.code_action_group)
779 kind: Some(code_action_kind(assist.assist.id.1)),
786 pub(crate) fn runnable(
787 snap: &GlobalStateSnapshot,
790 ) -> Result<lsp_ext::Runnable> {
791 let config = &snap.config.runnables;
792 let spec = CargoTargetSpec::for_file(snap, file_id)?;
793 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
794 let target = spec.as_ref().map(|s| s.target.clone());
795 let (cargo_args, executable_args) =
796 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
797 let label = runnable.label(target);
798 let location = location_link(snap, None, runnable.nav)?;
800 Ok(lsp_ext::Runnable {
802 location: Some(location),
803 kind: lsp_ext::RunnableKind::Cargo,
804 args: lsp_ext::CargoRunnable {
805 workspace_root: workspace_root.map(|it| it.into()),
806 override_cargo: config.override_cargo.clone(),
808 cargo_extra_args: config.cargo_extra_args.clone(),
815 pub(crate) fn markup_content(markup: Markup) -> lsp_types::MarkupContent {
816 let value = crate::markdown::format_docs(markup.as_str());
817 lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value }
827 fn test_completion_with_ref() {
836 let (offset, text) = test_utils::extract_offset(fixture);
837 let line_index = LineIndex::new(&text);
838 let (analysis, file_id) = Analysis::from_single_file(text);
839 let completions: Vec<(String, Option<String>)> = analysis
841 &ide::CompletionConfig::default(),
842 ide_db::base_db::FilePosition { file_id, offset },
847 .filter(|c| c.label().ends_with("arg"))
848 .map(|c| completion_item(&line_index, LineEndings::Unix, c))
849 .flat_map(|comps| comps.into_iter().map(|c| (c.label, c.sort_text)))
851 expect_test::expect![[r#"
865 .assert_debug_eq(&completions);
869 fn conv_fold_line_folding_only_fixup() {
882 let (analysis, file_id) = Analysis::from_single_file(text.to_string());
883 let folds = analysis.folding_ranges(file_id).unwrap();
884 assert_eq!(folds.len(), 4);
886 let line_index = LineIndex::new(&text);
887 let converted: Vec<lsp_types::FoldingRange> =
888 folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
890 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
891 assert_eq!(converted.len(), expected_lines.len());
892 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
893 assert_eq!(folding_range.start_line, *start_line);
894 assert_eq!(folding_range.start_character, None);
895 assert_eq!(folding_range.end_line, *end_line);
896 assert_eq!(folding_range.end_character, None);
900 // `Url` is not able to parse windows paths on unix machines.
902 #[cfg(target_os = "windows")]
903 fn test_lowercase_drive_letter_with_drive() {
904 let url = url_from_abs_path(Path::new("C:\\Test"));
905 assert_eq!(url.to_string(), "file:///c:/Test");
909 #[cfg(target_os = "windows")]
910 fn test_drive_without_colon_passthrough() {
911 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#));
912 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");