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, HlMod, HlPunct, HlRange, HlTag, Indel,
10 InlayHint, InlayKind, InsertTextFormat, LineIndex, Markup, NavigationTarget, ReferenceAccess,
11 RenameError, Runnable, Severity, SourceChange, SymbolKind, TextEdit, TextRange, TextSize,
13 use itertools::Itertools;
16 cargo_target_spec::CargoTargetSpec, global_state::GlobalStateSnapshot,
17 line_endings::LineEndings, lsp_ext, semantic_tokens, Result,
20 pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position {
21 let line_col = line_index.line_col(offset);
22 lsp_types::Position::new(line_col.line, line_col.col_utf16)
25 pub(crate) fn range(line_index: &LineIndex, range: TextRange) -> lsp_types::Range {
26 let start = position(line_index, range.start());
27 let end = position(line_index, range.end());
28 lsp_types::Range::new(start, end)
31 pub(crate) fn symbol_kind(symbol_kind: SymbolKind) -> lsp_types::SymbolKind {
33 SymbolKind::Function => lsp_types::SymbolKind::Function,
34 SymbolKind::Struct => lsp_types::SymbolKind::Struct,
35 SymbolKind::Enum => lsp_types::SymbolKind::Enum,
36 SymbolKind::Variant => lsp_types::SymbolKind::EnumMember,
37 SymbolKind::Trait => lsp_types::SymbolKind::Interface,
38 SymbolKind::Macro => lsp_types::SymbolKind::Function,
39 SymbolKind::Module => lsp_types::SymbolKind::Module,
40 SymbolKind::TypeAlias | SymbolKind::TypeParam => lsp_types::SymbolKind::TypeParameter,
41 SymbolKind::Field => lsp_types::SymbolKind::Field,
42 SymbolKind::Static => lsp_types::SymbolKind::Constant,
43 SymbolKind::Const => lsp_types::SymbolKind::Constant,
44 SymbolKind::ConstParam => lsp_types::SymbolKind::Constant,
45 SymbolKind::Impl => lsp_types::SymbolKind::Object,
47 | SymbolKind::SelfParam
48 | SymbolKind::LifetimeParam
49 | SymbolKind::ValueParam
50 | SymbolKind::Label => lsp_types::SymbolKind::Variable,
51 SymbolKind::Union => lsp_types::SymbolKind::Struct,
55 pub(crate) fn document_highlight_kind(
56 reference_access: ReferenceAccess,
57 ) -> lsp_types::DocumentHighlightKind {
58 match reference_access {
59 ReferenceAccess::Read => lsp_types::DocumentHighlightKind::Read,
60 ReferenceAccess::Write => lsp_types::DocumentHighlightKind::Write,
64 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
66 Severity::Error => lsp_types::DiagnosticSeverity::Error,
67 Severity::WeakWarning => lsp_types::DiagnosticSeverity::Hint,
71 pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
72 let value = crate::markdown::format_docs(documentation.as_str());
73 let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
74 lsp_types::Documentation::MarkupContent(markup_content)
77 pub(crate) fn insert_text_format(
78 insert_text_format: InsertTextFormat,
79 ) -> lsp_types::InsertTextFormat {
80 match insert_text_format {
81 InsertTextFormat::Snippet => lsp_types::InsertTextFormat::Snippet,
82 InsertTextFormat::PlainText => lsp_types::InsertTextFormat::PlainText,
86 pub(crate) fn completion_item_kind(
87 completion_item_kind: CompletionItemKind,
88 ) -> lsp_types::CompletionItemKind {
89 match completion_item_kind {
90 CompletionItemKind::Keyword => lsp_types::CompletionItemKind::Keyword,
91 CompletionItemKind::Snippet => lsp_types::CompletionItemKind::Snippet,
92 CompletionItemKind::Module => lsp_types::CompletionItemKind::Module,
93 CompletionItemKind::Function => lsp_types::CompletionItemKind::Function,
94 CompletionItemKind::Struct => lsp_types::CompletionItemKind::Struct,
95 CompletionItemKind::Enum => lsp_types::CompletionItemKind::Enum,
96 CompletionItemKind::EnumVariant => lsp_types::CompletionItemKind::EnumMember,
97 CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::Struct,
98 CompletionItemKind::Binding => lsp_types::CompletionItemKind::Variable,
99 CompletionItemKind::Field => lsp_types::CompletionItemKind::Field,
100 CompletionItemKind::Trait => lsp_types::CompletionItemKind::Interface,
101 CompletionItemKind::TypeAlias => lsp_types::CompletionItemKind::Struct,
102 CompletionItemKind::Const => lsp_types::CompletionItemKind::Constant,
103 CompletionItemKind::Static => lsp_types::CompletionItemKind::Value,
104 CompletionItemKind::Method => lsp_types::CompletionItemKind::Method,
105 CompletionItemKind::TypeParam => lsp_types::CompletionItemKind::TypeParameter,
106 CompletionItemKind::Macro => lsp_types::CompletionItemKind::Method,
107 CompletionItemKind::Attribute => lsp_types::CompletionItemKind::EnumMember,
108 CompletionItemKind::UnresolvedReference => lsp_types::CompletionItemKind::Reference,
112 pub(crate) fn text_edit(
113 line_index: &LineIndex,
114 line_endings: LineEndings,
116 ) -> lsp_types::TextEdit {
117 let range = range(line_index, indel.delete);
118 let new_text = match line_endings {
119 LineEndings::Unix => indel.insert,
120 LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
122 lsp_types::TextEdit { range, new_text }
125 pub(crate) fn snippet_text_edit(
126 line_index: &LineIndex,
127 line_endings: LineEndings,
130 ) -> lsp_ext::SnippetTextEdit {
131 let text_edit = text_edit(line_index, line_endings, indel);
132 let insert_text_format =
133 if is_snippet { Some(lsp_types::InsertTextFormat::Snippet) } else { None };
134 lsp_ext::SnippetTextEdit {
135 range: text_edit.range,
136 new_text: text_edit.new_text,
141 pub(crate) fn text_edit_vec(
142 line_index: &LineIndex,
143 line_endings: LineEndings,
145 ) -> Vec<lsp_types::TextEdit> {
146 text_edit.into_iter().map(|indel| self::text_edit(line_index, line_endings, indel)).collect()
149 pub(crate) fn snippet_text_edit_vec(
150 line_index: &LineIndex,
151 line_endings: LineEndings,
154 ) -> Vec<lsp_ext::SnippetTextEdit> {
157 .map(|indel| self::snippet_text_edit(line_index, line_endings, is_snippet, indel))
161 pub(crate) fn completion_item(
162 line_index: &LineIndex,
163 line_endings: LineEndings,
164 completion_item: CompletionItem,
165 ) -> Vec<lsp_types::CompletionItem> {
166 fn set_score(res: &mut lsp_types::CompletionItem, label: &str) {
167 res.preselect = Some(true);
168 // HACK: sort preselect items first
169 res.sort_text = Some(format!(" {}", label));
172 let mut additional_text_edits = Vec::new();
173 let mut text_edit = None;
174 // LSP does not allow arbitrary edits in completion, so we have to do a
175 // non-trivial mapping here.
176 let source_range = completion_item.source_range();
177 for indel in completion_item.text_edit().iter() {
178 if indel.delete.contains_range(source_range) {
179 text_edit = Some(if indel.delete == source_range {
180 self::text_edit(line_index, line_endings, indel.clone())
182 assert!(source_range.end() == indel.delete.end());
183 let range1 = TextRange::new(indel.delete.start(), source_range.start());
184 let range2 = source_range;
185 let indel1 = Indel::replace(range1, String::new());
186 let indel2 = Indel::replace(range2, indel.insert.clone());
187 additional_text_edits.push(self::text_edit(line_index, line_endings, indel1));
188 self::text_edit(line_index, line_endings, indel2)
191 assert!(source_range.intersect(indel.delete).is_none());
192 let text_edit = self::text_edit(line_index, line_endings, indel.clone());
193 additional_text_edits.push(text_edit);
196 let text_edit = text_edit.unwrap();
198 let mut res = lsp_types::CompletionItem {
199 label: completion_item.label().to_string(),
200 detail: completion_item.detail().map(|it| it.to_string()),
201 filter_text: Some(completion_item.lookup().to_string()),
202 kind: completion_item.kind().map(completion_item_kind),
203 text_edit: Some(text_edit.into()),
204 additional_text_edits: Some(additional_text_edits),
205 documentation: completion_item.documentation().map(documentation),
206 deprecated: Some(completion_item.deprecated()),
210 if completion_item.score().is_some() {
211 set_score(&mut res, completion_item.label());
214 if completion_item.deprecated() {
215 res.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
218 if completion_item.trigger_call_info() {
219 res.command = Some(lsp_types::Command {
220 title: "triggerParameterHints".into(),
221 command: "editor.action.triggerParameterHints".into(),
226 let mut all_results = match completion_item.ref_match() {
228 let mut refed = res.clone();
229 let (mutability, _score) = ref_match;
230 let label = format!("&{}{}", mutability.as_keyword_for_ref(), refed.label);
231 set_score(&mut refed, &label);
238 for mut r in all_results.iter_mut() {
239 r.insert_text_format = Some(insert_text_format(completion_item.insert_text_format()));
244 pub(crate) fn signature_help(
248 ) -> lsp_types::SignatureHelp {
249 let (label, parameters) = match (concise, label_offsets) {
251 let params = call_info
253 .map(|label| lsp_types::ParameterInformation {
254 label: lsp_types::ParameterLabel::Simple(label.to_string()),
257 .collect::<Vec<_>>();
259 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
263 let params = call_info
266 .map(|it| [u32::from(it.start()).into(), u32::from(it.end()).into()])
267 .map(|label_offsets| lsp_types::ParameterInformation {
268 label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
271 .collect::<Vec<_>>();
272 (call_info.signature, params)
275 let mut params = Vec::new();
276 let mut label = String::new();
277 let mut first = true;
278 for param in call_info.parameter_labels() {
280 label.push_str(", ");
283 let start = label.len() as u32;
284 label.push_str(param);
285 let end = label.len() as u32;
286 params.push(lsp_types::ParameterInformation {
287 label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
296 let documentation = if concise {
299 call_info.doc.map(|doc| {
300 lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
301 kind: lsp_types::MarkupKind::Markdown,
307 let active_parameter = call_info.active_parameter.map(|it| it as u32);
309 let signature = lsp_types::SignatureInformation {
312 parameters: Some(parameters),
315 lsp_types::SignatureHelp {
316 signatures: vec![signature],
317 active_signature: None,
322 pub(crate) fn inlay_hint(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
324 label: inlay_hint.label.to_string(),
325 range: range(line_index, inlay_hint.range),
326 kind: match inlay_hint.kind {
327 InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
328 InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
329 InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
334 static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
336 pub(crate) fn semantic_tokens(
338 line_index: &LineIndex,
339 highlights: Vec<HlRange>,
340 ) -> lsp_types::SemanticTokens {
341 let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
342 let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
344 for highlight_range in highlights {
345 if highlight_range.highlight.is_empty() {
348 let (type_, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
349 let token_index = semantic_tokens::type_index(type_);
350 let modifier_bitset = mods.0;
352 for mut text_range in line_index.lines(highlight_range.range) {
353 if text[text_range].ends_with('\n') {
355 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
357 let range = range(&line_index, text_range);
358 builder.push(range, token_index, modifier_bitset);
365 pub(crate) fn semantic_token_delta(
366 previous: &lsp_types::SemanticTokens,
367 current: &lsp_types::SemanticTokens,
368 ) -> lsp_types::SemanticTokensDelta {
369 let result_id = current.result_id.clone();
370 let edits = semantic_tokens::diff_tokens(&previous.data, ¤t.data);
371 lsp_types::SemanticTokensDelta { result_id, edits }
374 fn semantic_token_type_and_modifiers(
375 highlight: Highlight,
376 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
377 let mut mods = semantic_tokens::ModifierSet::default();
378 let type_ = match highlight.tag {
379 HlTag::Symbol(symbol) => match symbol {
380 SymbolKind::Module => lsp_types::SemanticTokenType::NAMESPACE,
381 SymbolKind::Impl => lsp_types::SemanticTokenType::TYPE,
382 SymbolKind::Field => lsp_types::SemanticTokenType::PROPERTY,
383 SymbolKind::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
384 SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
385 SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
386 SymbolKind::Label => semantic_tokens::LABEL,
387 SymbolKind::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
388 SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
389 SymbolKind::Local => lsp_types::SemanticTokenType::VARIABLE,
390 SymbolKind::Function => {
391 if highlight.mods.contains(HlMod::Associated) {
392 lsp_types::SemanticTokenType::METHOD
394 lsp_types::SemanticTokenType::FUNCTION
397 SymbolKind::Const => {
398 mods |= semantic_tokens::CONSTANT;
399 mods |= lsp_types::SemanticTokenModifier::STATIC;
400 lsp_types::SemanticTokenType::VARIABLE
402 SymbolKind::Static => {
403 mods |= lsp_types::SemanticTokenModifier::STATIC;
404 lsp_types::SemanticTokenType::VARIABLE
406 SymbolKind::Struct => lsp_types::SemanticTokenType::STRUCT,
407 SymbolKind::Enum => lsp_types::SemanticTokenType::ENUM,
408 SymbolKind::Variant => lsp_types::SemanticTokenType::ENUM_MEMBER,
409 SymbolKind::Union => semantic_tokens::UNION,
410 SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
411 SymbolKind::Trait => lsp_types::SemanticTokenType::INTERFACE,
412 SymbolKind::Macro => lsp_types::SemanticTokenType::MACRO,
414 HlTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
415 HlTag::None => semantic_tokens::GENERIC,
416 HlTag::ByteLiteral | HlTag::NumericLiteral => lsp_types::SemanticTokenType::NUMBER,
417 HlTag::BoolLiteral => semantic_tokens::BOOLEAN,
418 HlTag::CharLiteral | HlTag::StringLiteral => lsp_types::SemanticTokenType::STRING,
419 HlTag::Comment => lsp_types::SemanticTokenType::COMMENT,
420 HlTag::Attribute => semantic_tokens::ATTRIBUTE,
421 HlTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
422 HlTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
423 HlTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
424 HlTag::Operator => lsp_types::SemanticTokenType::OPERATOR,
425 HlTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
426 HlTag::Punctuation(punct) => match punct {
427 HlPunct::Bracket => semantic_tokens::BRACKET,
428 HlPunct::Brace => semantic_tokens::BRACE,
429 HlPunct::Parenthesis => semantic_tokens::PARENTHESIS,
430 HlPunct::Angle => semantic_tokens::ANGLE,
431 HlPunct::Comma => semantic_tokens::COMMA,
432 HlPunct::Dot => semantic_tokens::DOT,
433 HlPunct::Colon => semantic_tokens::COLON,
434 HlPunct::Semi => semantic_tokens::SEMICOLON,
435 HlPunct::Other => semantic_tokens::PUNCTUATION,
439 for modifier in highlight.mods.iter() {
440 let modifier = match modifier {
441 HlMod::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
442 HlMod::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
443 HlMod::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
444 HlMod::Injected => semantic_tokens::INJECTED,
445 HlMod::ControlFlow => semantic_tokens::CONTROL_FLOW,
446 HlMod::Mutable => semantic_tokens::MUTABLE,
447 HlMod::Consuming => semantic_tokens::CONSUMING,
448 HlMod::Unsafe => semantic_tokens::UNSAFE,
449 HlMod::Callable => semantic_tokens::CALLABLE,
450 HlMod::Static => lsp_types::SemanticTokenModifier::STATIC,
451 HlMod::Associated => continue,
459 pub(crate) fn folding_range(
461 line_index: &LineIndex,
462 line_folding_only: bool,
464 ) -> lsp_types::FoldingRange {
465 let kind = match fold.kind {
466 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
467 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
468 FoldKind::Mods | FoldKind::Block | FoldKind::ArgList | FoldKind::Region => None,
471 let range = range(line_index, fold.range);
473 if line_folding_only {
474 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
475 // even if it contains text not in the folding range. To prevent that we exclude
476 // range.end.line from the folding region if there is more text after range.end
478 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
480 .take_while(|it| *it != '\n')
481 .any(|it| !it.is_whitespace());
483 let end_line = if has_more_text_on_end_line {
484 range.end.line.saturating_sub(1)
489 lsp_types::FoldingRange {
490 start_line: range.start.line,
491 start_character: None,
497 lsp_types::FoldingRange {
498 start_line: range.start.line,
499 start_character: Some(range.start.character),
500 end_line: range.end.line,
501 end_character: Some(range.end.character),
507 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
508 snap.file_id_to_url(file_id)
511 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
512 /// This will only happen when processing windows paths.
514 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
515 pub(crate) fn url_from_abs_path(path: &Path) -> lsp_types::Url {
516 assert!(path.is_absolute());
517 let url = lsp_types::Url::from_file_path(path).unwrap();
518 match path.components().next() {
519 Some(path::Component::Prefix(prefix)) if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
521 // Need to lowercase driver letter
526 let driver_letter_range = {
527 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
531 let start = scheme.len() + ':'.len_utf8();
532 start..(start + drive_letter.len())
535 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
536 // machinery *also* canonicalizes the drive letter. So, just massage the
538 let mut url = url.into_string();
539 url[driver_letter_range].make_ascii_lowercase();
540 lsp_types::Url::parse(&url).unwrap()
543 pub(crate) fn optional_versioned_text_document_identifier(
544 snap: &GlobalStateSnapshot,
546 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
547 let url = url(snap, file_id);
548 let version = snap.url_file_version(&url);
549 lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
552 pub(crate) fn location(
553 snap: &GlobalStateSnapshot,
555 ) -> Result<lsp_types::Location> {
556 let url = url(snap, frange.file_id);
557 let line_index = snap.analysis.file_line_index(frange.file_id)?;
558 let range = range(&line_index, frange.range);
559 let loc = lsp_types::Location::new(url, range);
563 /// Perefer using `location_link`, if the client has the cap.
564 pub(crate) fn location_from_nav(
565 snap: &GlobalStateSnapshot,
566 nav: NavigationTarget,
567 ) -> Result<lsp_types::Location> {
568 let url = url(snap, nav.file_id);
569 let line_index = snap.analysis.file_line_index(nav.file_id)?;
570 let range = range(&line_index, nav.full_range);
571 let loc = lsp_types::Location::new(url, range);
575 pub(crate) fn location_link(
576 snap: &GlobalStateSnapshot,
577 src: Option<FileRange>,
578 target: NavigationTarget,
579 ) -> Result<lsp_types::LocationLink> {
580 let origin_selection_range = match src {
582 let line_index = snap.analysis.file_line_index(src.file_id)?;
583 let range = range(&line_index, src.range);
588 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
589 let res = lsp_types::LocationLink {
590 origin_selection_range,
593 target_selection_range,
599 snap: &GlobalStateSnapshot,
600 target: NavigationTarget,
601 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
602 let line_index = snap.analysis.file_line_index(target.file_id)?;
604 let target_uri = url(snap, target.file_id);
605 let target_range = range(&line_index, target.full_range);
606 let target_selection_range =
607 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
608 Ok((target_uri, target_range, target_selection_range))
611 pub(crate) fn goto_definition_response(
612 snap: &GlobalStateSnapshot,
613 src: Option<FileRange>,
614 targets: Vec<NavigationTarget>,
615 ) -> Result<lsp_types::GotoDefinitionResponse> {
616 if snap.config.location_link() {
619 .map(|nav| location_link(snap, src, nav))
620 .collect::<Result<Vec<_>>>()?;
623 let locations = targets
626 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
628 .collect::<Result<Vec<_>>>()?;
633 pub(crate) fn snippet_text_document_edit(
634 snap: &GlobalStateSnapshot,
638 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
639 let text_document = optional_versioned_text_document_identifier(snap, file_id);
640 let line_index = snap.analysis.file_line_index(file_id)?;
641 let line_endings = snap.file_line_endings(file_id);
644 .map(|it| snippet_text_edit(&line_index, line_endings, is_snippet, it))
646 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
649 pub(crate) fn snippet_text_document_ops(
650 snap: &GlobalStateSnapshot,
651 file_system_edit: FileSystemEdit,
652 ) -> Vec<lsp_ext::SnippetDocumentChangeOperation> {
653 let mut ops = Vec::new();
654 match file_system_edit {
655 FileSystemEdit::CreateFile { dst, initial_contents } => {
656 let uri = snap.anchored_path(&dst);
657 let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
662 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
663 if !initial_contents.is_empty() {
665 lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
666 let range = range(&LineIndex::new(""), TextRange::empty(TextSize::from(0)));
667 let text_edit = lsp_ext::SnippetTextEdit {
669 new_text: initial_contents,
670 insert_text_format: Some(lsp_types::InsertTextFormat::PlainText),
673 lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
674 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
677 FileSystemEdit::MoveFile { src, dst } => {
678 let old_uri = snap.file_id_to_url(src);
679 let new_uri = snap.anchored_path(&dst);
680 let rename_file = lsp_types::ResourceOp::Rename(lsp_types::RenameFile {
686 ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(rename_file))
692 pub(crate) fn snippet_workspace_edit(
693 snap: &GlobalStateSnapshot,
694 source_change: SourceChange,
695 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
696 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
697 for op in source_change.file_system_edits {
698 let ops = snippet_text_document_ops(snap, op);
699 document_changes.extend_from_slice(&ops);
701 for (file_id, edit) in source_change.source_file_edits {
702 let edit = snippet_text_document_edit(&snap, source_change.is_snippet, file_id, edit)?;
703 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
706 lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
710 pub(crate) fn workspace_edit(
711 snap: &GlobalStateSnapshot,
712 source_change: SourceChange,
713 ) -> Result<lsp_types::WorkspaceEdit> {
714 assert!(!source_change.is_snippet);
715 snippet_workspace_edit(snap, source_change).map(|it| it.into())
718 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
719 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
720 lsp_types::WorkspaceEdit {
722 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
723 lsp_types::DocumentChanges::Operations(
726 .map(|change| match change {
727 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
728 lsp_types::DocumentChangeOperation::Op(op)
730 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
731 lsp_types::DocumentChangeOperation::Edit(
732 lsp_types::TextDocumentEdit {
733 text_document: edit.text_document,
738 lsp_types::OneOf::Left(lsp_types::TextEdit {
740 new_text: edit.new_text,
751 change_annotations: None,
756 pub(crate) fn call_hierarchy_item(
757 snap: &GlobalStateSnapshot,
758 target: NavigationTarget,
759 ) -> Result<lsp_types::CallHierarchyItem> {
760 let name = target.name.to_string();
761 let detail = target.description.clone();
762 let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::Function);
763 let (uri, range, selection_range) = location_info(snap, target)?;
764 Ok(lsp_types::CallHierarchyItem {
776 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
778 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
779 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
780 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
781 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
782 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
783 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
787 pub(crate) fn unresolved_code_action(
788 snap: &GlobalStateSnapshot,
789 code_action_params: lsp_types::CodeActionParams,
792 ) -> Result<lsp_ext::CodeAction> {
793 assert!(assist.source_change.is_none());
794 let res = lsp_ext::CodeAction {
795 title: assist.label.to_string(),
796 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
797 kind: Some(code_action_kind(assist.id.1)),
800 data: Some(lsp_ext::CodeActionData {
801 id: format!("{}:{}", assist.id.0, index.to_string()),
808 pub(crate) fn resolved_code_action(
809 snap: &GlobalStateSnapshot,
811 ) -> Result<lsp_ext::CodeAction> {
812 let change = assist.source_change.unwrap();
813 let res = lsp_ext::CodeAction {
814 edit: Some(snippet_workspace_edit(snap, change)?),
815 title: assist.label.to_string(),
816 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
817 kind: Some(code_action_kind(assist.id.1)),
824 pub(crate) fn runnable(
825 snap: &GlobalStateSnapshot,
828 ) -> Result<lsp_ext::Runnable> {
829 let config = snap.config.runnables();
830 let spec = CargoTargetSpec::for_file(snap, file_id)?;
831 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
832 let target = spec.as_ref().map(|s| s.target.clone());
833 let (cargo_args, executable_args) =
834 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
835 let label = runnable.label(target);
836 let location = location_link(snap, None, runnable.nav)?;
838 Ok(lsp_ext::Runnable {
840 location: Some(location),
841 kind: lsp_ext::RunnableKind::Cargo,
842 args: lsp_ext::CargoRunnable {
843 workspace_root: workspace_root.map(|it| it.into()),
844 override_cargo: config.override_cargo,
846 cargo_extra_args: config.cargo_extra_args,
853 pub(crate) fn markup_content(markup: Markup) -> lsp_types::MarkupContent {
854 let value = crate::markdown::format_docs(markup.as_str());
855 lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value }
858 pub(crate) fn rename_error(err: RenameError) -> crate::LspError {
859 crate::LspError { code: lsp_server::ErrorCode::InvalidParams as i32, message: err.to_string() }
866 use ide_db::helpers::{insert_use::InsertUseConfig, SnippetCap};
871 fn test_completion_with_ref() {
880 let (offset, text) = test_utils::extract_offset(fixture);
881 let line_index = LineIndex::new(&text);
882 let (analysis, file_id) = Analysis::from_single_file(text);
883 let completions: Vec<(String, Option<String>)> = analysis
885 &ide::CompletionConfig {
886 enable_postfix_completions: true,
887 enable_autoimport_completions: true,
888 add_call_parenthesis: true,
889 add_call_argument_snippets: true,
890 snippet_cap: SnippetCap::new(true),
891 insert_use: InsertUseConfig { merge: None, prefix_kind: PrefixKind::Plain },
893 ide_db::base_db::FilePosition { file_id, offset },
898 .filter(|c| c.label().ends_with("arg"))
899 .map(|c| completion_item(&line_index, LineEndings::Unix, c))
900 .flat_map(|comps| comps.into_iter().map(|c| (c.label, c.sort_text)))
902 expect_test::expect![[r#"
916 .assert_debug_eq(&completions);
920 fn conv_fold_line_folding_only_fixup() {
933 let (analysis, file_id) = Analysis::from_single_file(text.to_string());
934 let folds = analysis.folding_ranges(file_id).unwrap();
935 assert_eq!(folds.len(), 4);
937 let line_index = LineIndex::new(&text);
938 let converted: Vec<lsp_types::FoldingRange> =
939 folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
941 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
942 assert_eq!(converted.len(), expected_lines.len());
943 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
944 assert_eq!(folding_range.start_line, *start_line);
945 assert_eq!(folding_range.start_character, None);
946 assert_eq!(folding_range.end_line, *end_line);
947 assert_eq!(folding_range.end_character, None);
951 // `Url` is not able to parse windows paths on unix machines.
953 #[cfg(target_os = "windows")]
954 fn test_lowercase_drive_letter_with_drive() {
955 let url = url_from_abs_path(Path::new("C:\\Test"));
956 assert_eq!(url.to_string(), "file:///c:/Test");
960 #[cfg(target_os = "windows")]
961 fn test_drive_without_colon_passthrough() {
962 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#));
963 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");