1use std::{
3 iter::once,
4 mem,
5 ops::Not as _,
6 sync::atomic::{AtomicU32, Ordering},
7};
8
9use base64::{Engine, prelude::BASE64_STANDARD};
10use ide::{
11 Annotation, AnnotationKind, Assist, AssistKind, Cancellable, CompletionFieldsToResolve,
12 CompletionItem, CompletionItemKind, CompletionRelevance, Documentation, FileId, FileRange,
13 FileSystemEdit, Fold, FoldKind, Highlight, HlMod, HlOperator, HlPunct, HlRange, HlTag, Indel,
14 InlayFieldsToResolve, InlayHint, InlayHintLabel, InlayHintLabelPart, InlayKind, LazyProperty,
15 Markup, NavigationTarget, ReferenceCategory, RenameError, Runnable, Severity, SignatureHelp,
16 SnippetEdit, SourceChange, StructureNodeKind, SymbolKind, TextEdit, TextRange, TextSize,
17 UpdateTest,
18};
19use ide_db::{
20 FxHasher, MiniCore, assists, base_db::TargetKind, rust_doc::format_docs,
21 source_change::ChangeAnnotationId,
22};
23use itertools::Itertools;
24use paths::{Utf8Component, Utf8Prefix};
25use semver::VersionReq;
26use serde_json::to_value;
27use vfs::{AbsPath, LineEndings};
28
29use crate::{
30 config::{CallInfoConfig, ClientCommandsConfig, Config},
31 global_state::GlobalStateSnapshot,
32 line_index::{LineIndex, PositionEncoding},
33 lsp::{
34 LspError, completion_item_hash,
35 ext::ShellRunnableArgs,
36 semantic_tokens::{self, standard_fallback_type},
37 utils::invalid_params_error,
38 },
39 lsp_ext::{self, SnippetTextEdit},
40 target_spec::{CargoTargetSpec, TargetSpec},
41};
42
43pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position {
44 let line_col = line_index.index.line_col(offset);
45 match line_index.encoding {
46 PositionEncoding::Utf8 => lsp_types::Position::new(line_col.line, line_col.col),
47 PositionEncoding::Wide(enc) => {
48 let line_col = line_index.index.to_wide(enc, line_col).unwrap();
49 lsp_types::Position::new(line_col.line, line_col.col)
50 }
51 }
52}
53
54pub(crate) fn range(line_index: &LineIndex, range: TextRange) -> lsp_types::Range {
55 let start = position(line_index, range.start());
56 let end = position(line_index, range.end());
57 lsp_types::Range::new(start, end)
58}
59
60pub(crate) fn symbol_kind(symbol_kind: SymbolKind) -> lsp_types::SymbolKind {
61 match symbol_kind {
62 SymbolKind::Function => lsp_types::SymbolKind::Function,
63 SymbolKind::Method => lsp_types::SymbolKind::Method,
64 SymbolKind::Struct => lsp_types::SymbolKind::Struct,
65 SymbolKind::Enum => lsp_types::SymbolKind::Enum,
66 SymbolKind::Variant => lsp_types::SymbolKind::EnumMember,
67 SymbolKind::Trait => lsp_types::SymbolKind::Interface,
68 SymbolKind::Macro
69 | SymbolKind::ProcMacro
70 | SymbolKind::BuiltinAttr
71 | SymbolKind::Attribute
72 | SymbolKind::Derive
73 | SymbolKind::DeriveHelper => lsp_types::SymbolKind::Function,
74 SymbolKind::CrateRoot => lsp_types::SymbolKind::Package,
75 SymbolKind::Module | SymbolKind::ToolModule => lsp_types::SymbolKind::Module,
76 SymbolKind::TypeAlias | SymbolKind::TypeParam | SymbolKind::SelfType => {
77 lsp_types::SymbolKind::TypeParameter
78 }
79 SymbolKind::Field => lsp_types::SymbolKind::Field,
80 SymbolKind::Static => lsp_types::SymbolKind::Constant,
81 SymbolKind::Const => lsp_types::SymbolKind::Constant,
82 SymbolKind::ConstParam => lsp_types::SymbolKind::Constant,
83 SymbolKind::Impl => lsp_types::SymbolKind::Object,
84 SymbolKind::Local
85 | SymbolKind::SelfParam
86 | SymbolKind::LifetimeParam
87 | SymbolKind::ValueParam
88 | SymbolKind::Label => lsp_types::SymbolKind::Variable,
89 SymbolKind::Union => lsp_types::SymbolKind::Struct,
90 SymbolKind::InlineAsmRegOrRegClass => lsp_types::SymbolKind::Variable,
91 }
92}
93
94pub(crate) fn structure_node_kind(kind: StructureNodeKind) -> lsp_types::SymbolKind {
95 match kind {
96 StructureNodeKind::SymbolKind(symbol) => symbol_kind(symbol),
97 StructureNodeKind::Region => lsp_types::SymbolKind::Namespace,
98 StructureNodeKind::ExternBlock => lsp_types::SymbolKind::Namespace,
99 }
100}
101
102pub(crate) fn document_highlight_kind(
103 category: ReferenceCategory,
104) -> Option<lsp_types::DocumentHighlightKind> {
105 if category.contains(ReferenceCategory::WRITE) {
106 return Some(lsp_types::DocumentHighlightKind::Write);
107 }
108 if category.contains(ReferenceCategory::READ) {
109 return Some(lsp_types::DocumentHighlightKind::Read);
110 }
111 None
112}
113
114pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
115 match severity {
116 Severity::Error => lsp_types::DiagnosticSeverity::Error,
117 Severity::Warning => lsp_types::DiagnosticSeverity::Warning,
118 Severity::WeakWarning => lsp_types::DiagnosticSeverity::Hint,
119 Severity::Allow => lsp_types::DiagnosticSeverity::Information,
121 }
122}
123
124pub(crate) fn documentation(documentation: Documentation<'_>) -> lsp_types::Documentation {
125 let value = format_docs(&documentation);
126 let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
127 lsp_types::Documentation::MarkupContent(markup_content)
128}
129
130pub(crate) fn completion_item_kind(
131 completion_item_kind: CompletionItemKind,
132) -> lsp_types::CompletionItemKind {
133 match completion_item_kind {
134 CompletionItemKind::Binding => lsp_types::CompletionItemKind::Variable,
135 CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::Struct,
136 CompletionItemKind::InferredType => lsp_types::CompletionItemKind::Snippet,
137 CompletionItemKind::Keyword => lsp_types::CompletionItemKind::Keyword,
138 CompletionItemKind::Snippet => lsp_types::CompletionItemKind::Snippet,
139 CompletionItemKind::UnresolvedReference => lsp_types::CompletionItemKind::Reference,
140 CompletionItemKind::Expression => lsp_types::CompletionItemKind::Snippet,
141 CompletionItemKind::SymbolKind(symbol) => match symbol {
142 SymbolKind::Attribute => lsp_types::CompletionItemKind::Function,
143 SymbolKind::Method => lsp_types::CompletionItemKind::Method,
144 SymbolKind::Const => lsp_types::CompletionItemKind::Constant,
145 SymbolKind::ConstParam => lsp_types::CompletionItemKind::TypeParameter,
146 SymbolKind::CrateRoot => lsp_types::CompletionItemKind::Module,
147 SymbolKind::Derive => lsp_types::CompletionItemKind::Function,
148 SymbolKind::DeriveHelper => lsp_types::CompletionItemKind::Function,
149 SymbolKind::Enum => lsp_types::CompletionItemKind::Enum,
150 SymbolKind::Field => lsp_types::CompletionItemKind::Field,
151 SymbolKind::Function => lsp_types::CompletionItemKind::Function,
152 SymbolKind::Impl => lsp_types::CompletionItemKind::Text,
153 SymbolKind::Label => lsp_types::CompletionItemKind::Variable,
154 SymbolKind::LifetimeParam => lsp_types::CompletionItemKind::TypeParameter,
155 SymbolKind::Local => lsp_types::CompletionItemKind::Variable,
156 SymbolKind::Macro => lsp_types::CompletionItemKind::Function,
157 SymbolKind::ProcMacro => lsp_types::CompletionItemKind::Function,
158 SymbolKind::Module => lsp_types::CompletionItemKind::Module,
159 SymbolKind::SelfParam => lsp_types::CompletionItemKind::Value,
160 SymbolKind::SelfType => lsp_types::CompletionItemKind::TypeParameter,
161 SymbolKind::Static => lsp_types::CompletionItemKind::Value,
162 SymbolKind::Struct => lsp_types::CompletionItemKind::Struct,
163 SymbolKind::Trait => lsp_types::CompletionItemKind::Interface,
164 SymbolKind::TypeAlias => lsp_types::CompletionItemKind::Struct,
165 SymbolKind::TypeParam => lsp_types::CompletionItemKind::TypeParameter,
166 SymbolKind::Union => lsp_types::CompletionItemKind::Struct,
167 SymbolKind::ValueParam => lsp_types::CompletionItemKind::Value,
168 SymbolKind::Variant => lsp_types::CompletionItemKind::EnumMember,
169 SymbolKind::BuiltinAttr => lsp_types::CompletionItemKind::Function,
170 SymbolKind::ToolModule => lsp_types::CompletionItemKind::Module,
171 SymbolKind::InlineAsmRegOrRegClass => lsp_types::CompletionItemKind::Keyword,
172 },
173 }
174}
175
176pub(crate) fn text_edit(line_index: &LineIndex, indel: Indel) -> lsp_types::TextEdit {
177 let range = range(line_index, indel.delete);
178 let new_text = match line_index.endings {
179 LineEndings::Unix => indel.insert,
180 LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
181 };
182 lsp_types::TextEdit { range, new_text }
183}
184
185pub(crate) fn completion_text_edit(
186 line_index: &LineIndex,
187 cursor_position: lsp_types::Position,
188 insert_replace_support: bool,
189 indel: Indel,
190) -> lsp_types::CompletionItemTextEdit {
191 let text_edit = text_edit(line_index, indel);
192 let insert = lsp_types::Range { start: text_edit.range.start, end: cursor_position };
193 if insert_replace_support {
194 lsp_types::InsertReplaceEdit {
195 new_text: text_edit.new_text,
196 insert,
197 replace: text_edit.range,
198 }
199 .into()
200 } else {
201 lsp_types::TextEdit { range: insert, new_text: text_edit.new_text }.into()
202 }
203}
204
205pub(crate) fn snippet_text_edit(
206 line_index: &LineIndex,
207 is_snippet: bool,
208 indel: Indel,
209 annotation: Option<ChangeAnnotationId>,
210 client_supports_annotations: bool,
211) -> lsp_ext::SnippetTextEdit {
212 let annotation_id = annotation.filter(|_| client_supports_annotations).map(|it| it.to_string());
213 let text_edit = text_edit(line_index, indel);
214 let insert_text_format =
215 if is_snippet { Some(lsp_types::InsertTextFormat::Snippet) } else { None };
216 lsp_ext::SnippetTextEdit {
217 range: text_edit.range,
218 new_text: text_edit.new_text,
219 insert_text_format,
220 annotation_id,
221 }
222}
223
224pub(crate) fn text_edit_vec(
225 line_index: &LineIndex,
226 text_edit: TextEdit,
227) -> Vec<lsp_types::TextEdit> {
228 text_edit.into_iter().map(|indel| self::text_edit(line_index, indel)).collect()
229}
230
231pub(crate) fn snippet_text_edit_vec(
232 line_index: &LineIndex,
233 is_snippet: bool,
234 text_edit: TextEdit,
235 clients_support_annotations: bool,
236) -> Vec<lsp_ext::SnippetTextEdit> {
237 let annotation = text_edit.change_annotation();
238 text_edit
239 .into_iter()
240 .map(|indel| {
241 self::snippet_text_edit(
242 line_index,
243 is_snippet,
244 indel,
245 annotation,
246 clients_support_annotations,
247 )
248 })
249 .collect()
250}
251
252pub(crate) fn completion_items(
253 config: &Config,
254 fields_to_resolve: &CompletionFieldsToResolve,
255 line_index: &LineIndex,
256 version: Option<i32>,
257 tdpp: &lsp_types::TextDocumentPositionParams,
258 completion_trigger_character: Option<char>,
259 mut items: Vec<CompletionItem>,
260) -> Vec<lsp_types::CompletionItem> {
261 if config.completion_hide_deprecated() {
262 items.retain(|item| !item.deprecated);
263 }
264
265 let max_relevance = items.iter().map(|it| it.relevance.score()).max().unwrap_or_default();
266 let mut res = Vec::with_capacity(items.len());
267 let client_commands = config.client_commands();
268 for item in items {
269 completion_item(
270 &mut res,
271 config,
272 &client_commands,
273 fields_to_resolve,
274 line_index,
275 version,
276 tdpp,
277 max_relevance,
278 completion_trigger_character,
279 item,
280 );
281 }
282
283 if let Some(limit) = config.completion(None, MiniCore::default()).limit {
284 res.sort_by(|item1, item2| item1.sort_text.cmp(&item2.sort_text));
285 res.truncate(limit);
286 }
287
288 res
289}
290
291fn completion_item(
292 acc: &mut Vec<lsp_types::CompletionItem>,
293 config: &Config,
294 client_commands: &ClientCommandsConfig,
295 fields_to_resolve: &CompletionFieldsToResolve,
296 line_index: &LineIndex,
297 version: Option<i32>,
298 tdpp: &lsp_types::TextDocumentPositionParams,
299 max_relevance: u32,
300 completion_trigger_character: Option<char>,
301 item: CompletionItem,
302) {
303 let insert_replace_support = config.insert_replace_support();
304 let ref_match = item.ref_match();
305
306 let mut additional_text_edits = Vec::new();
307 let mut something_to_resolve = false;
308
309 let filter_text = if fields_to_resolve.resolve_filter_text {
310 something_to_resolve |= !item.lookup().is_empty();
311 None
312 } else {
313 Some(item.lookup().to_owned())
314 };
315
316 let text_edit = if fields_to_resolve.resolve_text_edit {
317 something_to_resolve |= true;
318 None
319 } else {
320 let mut text_edit = None;
323 let source_range = item.source_range;
324 for indel in &item.text_edit {
325 if indel.delete.contains_range(source_range) {
326 text_edit = Some(if indel.delete == source_range {
328 self::completion_text_edit(
329 line_index,
330 tdpp.position,
331 insert_replace_support,
332 indel.clone(),
333 )
334 } else {
335 assert!(source_range.end() == indel.delete.end());
336 let range1 = TextRange::new(indel.delete.start(), source_range.start());
337 let range2 = source_range;
338 let indel1 = Indel::delete(range1);
339 let indel2 = Indel::replace(range2, indel.insert.clone());
340 additional_text_edits.push(self::text_edit(line_index, indel1));
341 self::completion_text_edit(
342 line_index,
343 tdpp.position,
344 insert_replace_support,
345 indel2,
346 )
347 })
348 } else {
349 assert!(source_range.intersect(indel.delete).is_none());
350 let text_edit = self::text_edit(line_index, indel.clone());
351 additional_text_edits.push(text_edit);
352 }
353 }
354 Some(text_edit.unwrap())
355 };
356
357 let insert_text_format = item.is_snippet.then_some(lsp_types::InsertTextFormat::Snippet);
358 let tags = if fields_to_resolve.resolve_tags {
359 something_to_resolve |= item.deprecated;
360 None
361 } else {
362 item.deprecated.then(|| vec![lsp_types::CompletionItemTag::Deprecated])
363 };
364 let command = if item.trigger_call_info && client_commands.trigger_parameter_hints {
365 if fields_to_resolve.resolve_command {
366 something_to_resolve |= true;
367 None
368 } else {
369 Some(command::trigger_parameter_hints())
370 }
371 } else {
372 None
373 };
374
375 let detail = if fields_to_resolve.resolve_detail {
376 something_to_resolve |= item.detail.is_some();
377 None
378 } else {
379 item.detail.clone()
380 };
381
382 let documentation = if fields_to_resolve.resolve_documentation {
383 something_to_resolve |= item.documentation.is_some();
384 None
385 } else {
386 item.documentation.clone().map(documentation)
387 };
388
389 let mut lsp_item = lsp_types::CompletionItem {
390 label: item.label.primary.to_string(),
391 detail,
392 filter_text,
393 kind: Some(completion_item_kind(item.kind)),
394 text_edit,
395 additional_text_edits: additional_text_edits
396 .is_empty()
397 .not()
398 .then_some(additional_text_edits),
399 documentation,
400 #[expect(deprecated, reason = "we do use tags")]
401 deprecated: item.deprecated.then_some(item.deprecated),
402 tags,
403 command,
404 insert_text_format,
405 ..Default::default()
406 };
407
408 if config.completion_label_details_support() {
409 let has_label_details =
410 item.label.detail_left.is_some() || item.label.detail_right.is_some();
411 if fields_to_resolve.resolve_label_details {
412 something_to_resolve |= has_label_details;
413 } else if has_label_details {
414 lsp_item.label_details = Some(lsp_types::CompletionItemLabelDetails {
415 detail: item.label.detail_left.clone(),
416 description: item.label.detail_right.clone(),
417 });
418 }
419 } else if let Some(label_detail) = &item.label.detail_left {
420 lsp_item.label.push_str(label_detail.as_str());
421 }
422
423 set_score(&mut lsp_item, max_relevance, item.relevance);
424
425 let imports = if config.completion(None, MiniCore::default()).enable_imports_on_the_fly
426 && !item.import_to_add.is_empty()
427 {
428 item.import_to_add
429 .clone()
430 .into_iter()
431 .map(|import| lsp_ext::CompletionImport {
432 full_import_path: import.path,
433 as_underscore: import.as_underscore,
434 })
435 .collect()
436 } else {
437 Vec::new()
438 };
439 let (ref_resolve_data, resolve_data) = if something_to_resolve || !imports.is_empty() {
440 let ref_resolve_data = if ref_match.is_some() {
441 let ref_resolve_data = lsp_ext::CompletionResolveData {
442 position: tdpp.clone(),
443 imports: Vec::new(),
444 version,
445 trigger_character: completion_trigger_character,
446 for_ref: true,
447 hash: BASE64_STANDARD.encode(completion_item_hash(&item, true)),
448 };
449 Some(to_value(ref_resolve_data).unwrap())
450 } else {
451 None
452 };
453 let resolve_data = lsp_ext::CompletionResolveData {
454 position: tdpp.clone(),
455 imports,
456 version,
457 trigger_character: completion_trigger_character,
458 for_ref: false,
459 hash: BASE64_STANDARD.encode(completion_item_hash(&item, false)),
460 };
461 (ref_resolve_data, Some(to_value(resolve_data).unwrap()))
462 } else {
463 (None, None)
464 };
465
466 if let Some((label, indel, relevance)) = ref_match {
467 let mut lsp_item_with_ref =
468 lsp_types::CompletionItem { label, data: ref_resolve_data, ..lsp_item.clone() };
469 lsp_item_with_ref
470 .additional_text_edits
471 .get_or_insert_with(Default::default)
472 .push(self::text_edit(line_index, indel));
473 set_score(&mut lsp_item_with_ref, max_relevance, relevance);
474 acc.push(lsp_item_with_ref);
475 };
476
477 lsp_item.data = resolve_data;
478 acc.push(lsp_item);
479
480 fn set_score(
481 res: &mut lsp_types::CompletionItem,
482 max_relevance: u32,
483 relevance: CompletionRelevance,
484 ) {
485 if relevance.is_relevant() && relevance.score() == max_relevance {
486 res.preselect = Some(true);
487 }
488 let sort_score = relevance.score() ^ 0xFF_FF_FF_FF;
491 res.sort_text = Some(format!("{sort_score:08x}"));
496 }
497}
498
499pub(crate) fn signature_help(
500 call_info: SignatureHelp,
501 config: CallInfoConfig,
502 label_offsets: bool,
503) -> lsp_types::SignatureHelp {
504 let (label, parameters) = match (config.params_only, label_offsets) {
505 (concise, false) => {
506 let params = call_info
507 .parameter_labels()
508 .map(|label| lsp_types::ParameterInformation {
509 label: lsp_types::ParameterInformationLabel::String(label.to_owned()),
510 documentation: None,
511 })
512 .collect::<Vec<_>>();
513 let label =
514 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
515 (label, params)
516 }
517 (false, true) => {
518 let params = call_info
519 .parameter_ranges()
520 .iter()
521 .map(|it| {
522 let start = call_info.signature[..it.start().into()]
523 .chars()
524 .map(|c| c.len_utf16())
525 .sum::<usize>() as u32;
526 let end = start
527 + call_info.signature[it.start().into()..it.end().into()]
528 .chars()
529 .map(|c| c.len_utf16())
530 .sum::<usize>() as u32;
531 (start, end)
532 })
533 .map(|label_offsets| lsp_types::ParameterInformation {
534 label: lsp_types::ParameterInformationLabel::Tuple(label_offsets),
535 documentation: None,
536 })
537 .collect::<Vec<_>>();
538 (call_info.signature, params)
539 }
540 (true, true) => {
541 let mut params = Vec::new();
542 let mut label = String::new();
543 let mut first = true;
544 for param in call_info.parameter_labels() {
545 if !first {
546 label.push_str(", ");
547 }
548 first = false;
549 let start = label.len() as u32;
550 label.push_str(param);
551 let end = label.len() as u32;
552 params.push(lsp_types::ParameterInformation {
553 label: lsp_types::ParameterInformationLabel::Tuple((start, end)),
554 documentation: None,
555 });
556 }
557
558 (label, params)
559 }
560 };
561
562 let documentation = call_info.doc.filter(|_| config.docs).map(|doc| {
563 lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
564 kind: lsp_types::MarkupKind::Markdown,
565 value: format_docs(&doc),
566 })
567 });
568
569 let active_parameter =
570 call_info.active_parameter.map(|it| lsp_types::ActiveParameter::Int(it as u32));
571
572 let signature = lsp_types::SignatureInformation {
573 label,
574 documentation,
575 parameters: Some(parameters),
576 active_parameter,
577 };
578 lsp_types::SignatureHelp {
579 signatures: vec![signature],
580 active_signature: Some(0),
581 active_parameter,
582 }
583}
584
585pub(crate) fn inlay_hint(
586 snap: &GlobalStateSnapshot,
587 fields_to_resolve: &InlayFieldsToResolve,
588 line_index: &LineIndex,
589 file_id: FileId,
590 mut inlay_hint: InlayHint,
591) -> Cancellable<lsp_types::InlayHint> {
592 let hint_needs_resolve = |hint: &InlayHint| -> Option<TextRange> {
593 hint.resolve_parent.filter(|_| {
594 hint.text_edit.as_ref().is_some_and(LazyProperty::is_lazy)
595 || hint.label.parts.iter().any(|part| {
596 part.linked_location.as_ref().is_some_and(LazyProperty::is_lazy)
597 || part.tooltip.as_ref().is_some_and(LazyProperty::is_lazy)
598 })
599 })
600 };
601
602 let resolve_range_and_hash = hint_needs_resolve(&inlay_hint).map(|range| {
603 (
604 range,
605 std::hash::BuildHasher::hash_one(
606 &std::hash::BuildHasherDefault::<FxHasher>::default(),
607 &inlay_hint,
608 ),
609 )
610 });
611
612 let mut something_to_resolve = false;
613 let text_edits = inlay_hint
614 .text_edit
615 .take()
616 .and_then(|it| match it {
617 LazyProperty::Computed(it) => Some(it),
618 LazyProperty::Lazy => {
619 something_to_resolve |=
620 snap.config.visual_studio_code_version().is_none_or(|version| {
621 VersionReq::parse(">=1.86.0").unwrap().matches(version)
622 }) && resolve_range_and_hash.is_some()
623 && fields_to_resolve.resolve_text_edits;
624 None
625 }
626 })
627 .map(|it| text_edit_vec(line_index, it));
628 let (label, tooltip) = inlay_hint_label(
629 snap,
630 fields_to_resolve,
631 &mut something_to_resolve,
632 resolve_range_and_hash.is_some(),
633 inlay_hint.label,
634 )?;
635
636 let data = match resolve_range_and_hash {
637 Some((resolve_range, hash)) if something_to_resolve => Some(
638 to_value(lsp_ext::InlayHintResolveData {
639 file_id: file_id.index(),
640 hash: hash.to_string(),
641 version: snap.file_version(file_id),
642 resolve_range: range(line_index, resolve_range),
643 })
644 .unwrap(),
645 ),
646 _ => None,
647 };
648
649 Ok(lsp_types::InlayHint {
650 position: match inlay_hint.position {
651 ide::InlayHintPosition::Before => position(line_index, inlay_hint.range.start()),
652 ide::InlayHintPosition::After => position(line_index, inlay_hint.range.end()),
653 },
654 padding_left: Some(inlay_hint.pad_left),
655 padding_right: Some(inlay_hint.pad_right),
656 kind: match inlay_hint.kind {
657 InlayKind::Parameter | InlayKind::GenericParameter => {
658 Some(lsp_types::InlayHintKind::Parameter)
659 }
660 InlayKind::Type | InlayKind::Chaining => Some(lsp_types::InlayHintKind::Type),
661 _ => None,
662 },
663 text_edits,
664 data,
665 tooltip,
666 label,
667 })
668}
669
670fn inlay_hint_label(
671 snap: &GlobalStateSnapshot,
672 fields_to_resolve: &InlayFieldsToResolve,
673 something_to_resolve: &mut bool,
674 needs_resolve: bool,
675 mut label: InlayHintLabel,
676) -> Cancellable<(lsp_types::Label, Option<lsp_types::Tooltip>)> {
677 let (label, tooltip) = match &*label.parts {
678 [InlayHintLabelPart { linked_location: None, .. }] => {
679 let InlayHintLabelPart { text, tooltip, .. } = label.parts.pop().unwrap();
680 let tooltip = tooltip.and_then(|it| match it {
681 LazyProperty::Computed(it) => Some(it),
682 LazyProperty::Lazy => {
683 *something_to_resolve |=
684 needs_resolve && fields_to_resolve.resolve_hint_tooltip;
685 None
686 }
687 });
688 let hint_tooltip = match tooltip {
689 Some(ide::InlayTooltip::String(s)) => Some(lsp_types::Tooltip::String(s)),
690 Some(ide::InlayTooltip::Markdown(s)) => {
691 Some(lsp_types::Tooltip::MarkupContent(lsp_types::MarkupContent {
692 kind: lsp_types::MarkupKind::Markdown,
693 value: s,
694 }))
695 }
696 None => None,
697 };
698 (lsp_types::Label::String(text), hint_tooltip)
699 }
700 _ => {
701 let parts = label
702 .parts
703 .into_iter()
704 .map(|part| {
705 let tooltip = part.tooltip.and_then(|it| match it {
706 LazyProperty::Computed(it) => Some(it),
707 LazyProperty::Lazy => {
708 *something_to_resolve |= fields_to_resolve.resolve_label_tooltip;
709 None
710 }
711 });
712 let tooltip = match tooltip {
713 Some(ide::InlayTooltip::String(s)) => Some(lsp_types::Tooltip::String(s)),
714 Some(ide::InlayTooltip::Markdown(s)) => {
715 Some(lsp_types::Tooltip::MarkupContent(lsp_types::MarkupContent {
716 kind: lsp_types::MarkupKind::Markdown,
717 value: s,
718 }))
719 }
720 None => None,
721 };
722 let location = part
723 .linked_location
724 .and_then(|it| match it {
725 LazyProperty::Computed(it) => Some(it),
726 LazyProperty::Lazy => {
727 *something_to_resolve |= fields_to_resolve.resolve_label_location;
728 None
729 }
730 })
731 .map(|range| location(snap, range))
732 .transpose()?;
733 Ok(lsp_types::InlayHintLabelPart {
734 value: part.text,
735 tooltip,
736 location,
737 command: None,
738 })
739 })
740 .collect::<Cancellable<_>>()?;
741 (lsp_types::Label::InlayHintLabelPartList(parts), None)
742 }
743 };
744 Ok((label, tooltip))
745}
746
747static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
748
749pub(crate) fn semantic_tokens(
750 text: &str,
751 line_index: &LineIndex,
752 highlights: Vec<HlRange>,
753 semantics_tokens_augments_syntax_tokens: bool,
754 non_standard_tokens: bool,
755) -> lsp_types::SemanticTokens {
756 let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
757 let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
758
759 for highlight_range in highlights {
760 if highlight_range.highlight.is_empty() {
761 continue;
762 }
763
764 if semantics_tokens_augments_syntax_tokens {
765 match highlight_range.highlight.tag {
766 HlTag::BoolLiteral
767 | HlTag::ByteLiteral
768 | HlTag::CharLiteral
769 | HlTag::Comment
770 | HlTag::Keyword
771 | HlTag::NumericLiteral
772 | HlTag::Operator(_)
773 | HlTag::Punctuation(_)
774 | HlTag::StringLiteral
775 | HlTag::None
776 if highlight_range.highlight.mods.is_empty() =>
777 {
778 continue;
779 }
780 _ => (),
781 }
782 }
783
784 let (mut ty, mut mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
785
786 if !non_standard_tokens {
787 ty = match standard_fallback_type(ty) {
788 Some(fallback) => fallback,
789 None => continue,
790 };
791 mods.standard_fallback();
792 };
793 let token_index = semantic_tokens::type_index(ty);
794 let modifier_bitset = mods.0;
795
796 for mut text_range in line_index.index.lines(highlight_range.range) {
797 if text[text_range].ends_with('\n') {
798 text_range =
799 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
800 }
801 let range = range(line_index, text_range);
802 builder.push(range, token_index, modifier_bitset);
803 }
804 }
805
806 builder.build()
807}
808
809pub(crate) fn semantic_token_delta(
810 previous: &lsp_types::SemanticTokens,
811 current: &lsp_types::SemanticTokens,
812) -> lsp_types::SemanticTokensDelta {
813 let result_id = current.result_id.clone();
814 let edits = semantic_tokens::diff_tokens(&previous.data, ¤t.data);
815 lsp_types::SemanticTokensDelta { result_id, edits }
816}
817
818fn semantic_token_type_and_modifiers(
819 highlight: Highlight,
820) -> (semantic_tokens::SupportedType, semantic_tokens::ModifierSet) {
821 use semantic_tokens::{SupportedModifiers, SupportedType};
822
823 let mut mods = semantic_tokens::ModifierSet::default();
824 let ty = match highlight.tag {
825 HlTag::Symbol(symbol) => match symbol {
826 SymbolKind::Attribute => SupportedType::Decorator,
827 SymbolKind::Derive => SupportedType::Derive,
828 SymbolKind::DeriveHelper => SupportedType::DeriveHelper,
829 SymbolKind::CrateRoot => {
830 mods |= SupportedModifiers::CrateRoot;
831 SupportedType::Namespace
832 }
833 SymbolKind::Module => SupportedType::Namespace,
834 SymbolKind::Impl => SupportedType::TypeAlias,
835 SymbolKind::Field => SupportedType::Property,
836 SymbolKind::TypeParam => SupportedType::TypeParameter,
837 SymbolKind::ConstParam => SupportedType::ConstParameter,
838 SymbolKind::LifetimeParam => SupportedType::Lifetime,
839 SymbolKind::Label => SupportedType::Label,
840 SymbolKind::ValueParam => SupportedType::Parameter,
841 SymbolKind::SelfParam => SupportedType::SelfKeyword,
842 SymbolKind::SelfType => SupportedType::SelfTypeKeyword,
843 SymbolKind::Local => SupportedType::Variable,
844 SymbolKind::Method => SupportedType::Method,
845 SymbolKind::Function => SupportedType::Function,
846 SymbolKind::Const => SupportedType::Const,
847 SymbolKind::Static => SupportedType::Static,
848 SymbolKind::Struct => SupportedType::Struct,
849 SymbolKind::Enum => SupportedType::Enum,
850 SymbolKind::Variant => SupportedType::EnumMember,
851 SymbolKind::Union => SupportedType::Union,
852 SymbolKind::TypeAlias => SupportedType::TypeAlias,
853 SymbolKind::Trait => SupportedType::Interface,
854 SymbolKind::Macro => SupportedType::Macro,
855 SymbolKind::ProcMacro => SupportedType::ProcMacro,
856 SymbolKind::BuiltinAttr => SupportedType::BuiltinAttribute,
857 SymbolKind::ToolModule => SupportedType::ToolModule,
858 SymbolKind::InlineAsmRegOrRegClass => SupportedType::Keyword,
859 },
860 HlTag::AttributeBracket => SupportedType::AttributeBracket,
861 HlTag::BoolLiteral => SupportedType::Boolean,
862 HlTag::BuiltinType => SupportedType::BuiltinType,
863 HlTag::ByteLiteral | HlTag::NumericLiteral => SupportedType::Number,
864 HlTag::CharLiteral => SupportedType::Char,
865 HlTag::Comment => SupportedType::Comment,
866 HlTag::EscapeSequence => SupportedType::EscapeSequence,
867 HlTag::InvalidEscapeSequence => SupportedType::InvalidEscapeSequence,
868 HlTag::FormatSpecifier => SupportedType::FormatSpecifier,
869 HlTag::Keyword => SupportedType::Keyword,
870 HlTag::None => SupportedType::Generic,
871 HlTag::Operator(op) => match op {
872 HlOperator::Bitwise => SupportedType::Bitwise,
873 HlOperator::Arithmetic => SupportedType::Arithmetic,
874 HlOperator::Logical => SupportedType::Logical,
875 HlOperator::Negation => SupportedType::Negation,
876 HlOperator::Comparison => SupportedType::Comparison,
877 HlOperator::Other => SupportedType::Operator,
878 },
879 HlTag::StringLiteral => SupportedType::String,
880 HlTag::UnresolvedReference => SupportedType::UnresolvedReference,
881 HlTag::Punctuation(punct) => match punct {
882 HlPunct::Bracket => SupportedType::Bracket,
883 HlPunct::Brace => SupportedType::Brace,
884 HlPunct::Parenthesis => SupportedType::Parenthesis,
885 HlPunct::Angle => SupportedType::Angle,
886 HlPunct::Comma => SupportedType::Comma,
887 HlPunct::Dot => SupportedType::Dot,
888 HlPunct::Colon => SupportedType::Colon,
889 HlPunct::Semi => SupportedType::Semicolon,
890 HlPunct::Other => SupportedType::Punctuation,
891 HlPunct::MacroBang => SupportedType::MacroBang,
892 },
893 };
894
895 for modifier in highlight.mods.iter() {
896 let modifier = match modifier {
897 HlMod::Associated => SupportedModifiers::Associated,
898 HlMod::Async => SupportedModifiers::Async,
899 HlMod::Attribute => SupportedModifiers::AttributeModifier,
900 HlMod::Callable => SupportedModifiers::Callable,
901 HlMod::Const => SupportedModifiers::Constant,
902 HlMod::Consuming => SupportedModifiers::Consuming,
903 HlMod::ControlFlow => SupportedModifiers::ControlFlow,
904 HlMod::CrateRoot => SupportedModifiers::CrateRoot,
905 HlMod::DefaultLibrary => SupportedModifiers::DefaultLibrary,
906 HlMod::Deprecated => SupportedModifiers::Deprecated,
907 HlMod::Definition => SupportedModifiers::Declaration,
908 HlMod::Documentation => SupportedModifiers::Documentation,
909 HlMod::Injected => SupportedModifiers::Injected,
910 HlMod::IntraDocLink => SupportedModifiers::IntraDocLink,
911 HlMod::Library => SupportedModifiers::Library,
912 HlMod::Macro => SupportedModifiers::MacroModifier,
913 HlMod::ProcMacro => SupportedModifiers::ProcMacroModifier,
914 HlMod::Mutable => SupportedModifiers::Mutable,
915 HlMod::Public => SupportedModifiers::Public,
916 HlMod::Reference => SupportedModifiers::Reference,
917 HlMod::Static => SupportedModifiers::Static,
918 HlMod::Trait => SupportedModifiers::TraitModifier,
919 HlMod::Unsafe => SupportedModifiers::Unsafe,
920 };
921 mods |= modifier;
922 }
923
924 (ty, mods)
925}
926
927pub(crate) fn folding_range(
928 text: &str,
929 line_index: &LineIndex,
930 line_folding_only: bool,
931 Fold { range: text_range, kind, collapsed_text }: Fold,
932) -> lsp_types::FoldingRange {
933 let kind = match kind {
934 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
935 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
936 FoldKind::Region => Some(lsp_types::FoldingRangeKind::Region),
937 FoldKind::Modules
938 | FoldKind::Block
939 | FoldKind::ArgList
940 | FoldKind::Consts
941 | FoldKind::Statics
942 | FoldKind::TypeAliases
943 | FoldKind::WhereClause
944 | FoldKind::ReturnType
945 | FoldKind::Array
946 | FoldKind::ExternCrates
947 | FoldKind::MatchArm
948 | FoldKind::Function
949 | FoldKind::Stmt
950 | FoldKind::TailExpr => None,
951 };
952
953 let range = range(line_index, text_range);
954
955 if line_folding_only {
956 let has_more_text_on_end_line = text[TextRange::new(text_range.end(), TextSize::of(text))]
961 .chars()
962 .take_while(|it| *it != '\n')
963 .any(|it| !it.is_whitespace());
964
965 let end_line = if has_more_text_on_end_line {
966 range.end.line.saturating_sub(1)
967 } else {
968 range.end.line
969 };
970
971 let collapsed_text = collapsed_text.map(|collapsed_text| {
972 let range_start = text_range.start();
973 let line_start = range_start - TextSize::from(range.start.character);
974 let text_before_range = &text[TextRange::new(line_start, range_start)];
975 format!("{text_before_range}{collapsed_text}")
976 });
977
978 lsp_types::FoldingRange {
979 start_line: range.start.line,
980 start_character: None,
981 end_line,
982 end_character: None,
983 kind,
984 collapsed_text,
985 }
986 } else {
987 lsp_types::FoldingRange {
988 start_line: range.start.line,
989 start_character: Some(range.start.character),
990 end_line: range.end.line,
991 end_character: Some(range.end.character),
992 kind,
993 collapsed_text,
994 }
995 }
996}
997
998pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Uri {
999 snap.file_id_to_url(file_id)
1000}
1001
1002pub(crate) fn url_from_abs_path(path: &AbsPath) -> lsp_types::Uri {
1007 let url = lsp_types::Uri::from_file_path(path).unwrap();
1008 match path.components().next() {
1009 Some(Utf8Component::Prefix(prefix))
1010 if matches!(prefix.kind(), Utf8Prefix::Disk(_) | Utf8Prefix::VerbatimDisk(_)) =>
1011 {
1012 }
1014 _ => return url,
1015 }
1016
1017 let driver_letter_range = {
1018 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
1019 Some(it) => it,
1020 None => return url,
1021 };
1022 let start = scheme.len() + ':'.len_utf8();
1023 start..(start + drive_letter.len())
1024 };
1025
1026 let mut url: String = url.into();
1030 url[driver_letter_range].make_ascii_lowercase();
1031 lsp_types::Uri::parse(&url).unwrap()
1032}
1033
1034pub(crate) fn optional_versioned_text_document_identifier(
1035 snap: &GlobalStateSnapshot,
1036 file_id: FileId,
1037) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
1038 let uri = url(snap, file_id);
1039 let version = snap.url_file_version(&uri);
1040 lsp_types::OptionalVersionedTextDocumentIdentifier {
1041 text_document_identifier: lsp_types::TextDocumentIdentifier { uri },
1042 version,
1043 }
1044}
1045
1046pub(crate) fn location(
1047 snap: &GlobalStateSnapshot,
1048 frange: FileRange,
1049) -> Cancellable<lsp_types::Location> {
1050 let url = url(snap, frange.file_id);
1051 let line_index = snap.file_line_index(frange.file_id)?;
1052 let range = range(&line_index, frange.range);
1053 let loc = lsp_types::Location::new(url, range);
1054 Ok(loc)
1055}
1056
1057pub(crate) fn location_from_nav(
1059 snap: &GlobalStateSnapshot,
1060 nav: &NavigationTarget,
1061) -> Cancellable<lsp_types::Location> {
1062 let url = url(snap, nav.file_id);
1063 let line_index = snap.file_line_index(nav.file_id)?;
1064 let range = range(&line_index, nav.focus_or_full_range());
1065 let loc = lsp_types::Location::new(url, range);
1066 Ok(loc)
1067}
1068
1069pub(crate) fn location_link(
1070 snap: &GlobalStateSnapshot,
1071 src: Option<FileRange>,
1072 target: NavigationTarget,
1073) -> Cancellable<lsp_types::LocationLink> {
1074 let origin_selection_range = match src {
1075 Some(src) => {
1076 let line_index = snap.file_line_index(src.file_id)?;
1077 let range = range(&line_index, src.range);
1078 Some(range)
1079 }
1080 None => None,
1081 };
1082 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
1083 let res = lsp_types::LocationLink {
1084 origin_selection_range,
1085 target_uri,
1086 target_range,
1087 target_selection_range,
1088 };
1089 Ok(res)
1090}
1091
1092fn location_info(
1093 snap: &GlobalStateSnapshot,
1094 target: NavigationTarget,
1095) -> Cancellable<(lsp_types::Uri, lsp_types::Range, lsp_types::Range)> {
1096 let line_index = snap.file_line_index(target.file_id)?;
1097
1098 let target_uri = url(snap, target.file_id);
1099 let target_range = range(&line_index, target.full_range);
1100 let target_selection_range =
1101 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
1102 Ok((target_uri, target_range, target_selection_range))
1103}
1104
1105pub(crate) fn goto_definition_response(
1106 snap: &GlobalStateSnapshot,
1107 src: Option<FileRange>,
1108 targets: Vec<NavigationTarget>,
1109) -> Cancellable<lsp_types::DefinitionResponse> {
1110 if snap.config.location_link() {
1111 let links = targets_to_links(snap, src, targets)?;
1112 Ok(links.into())
1113 } else {
1114 let locations = targets_to_locations(snap, targets)?;
1115 Ok(lsp_types::DefinitionResponse::Definition(lsp_types::Definition::LocationList(
1116 locations,
1117 )))
1118 }
1119}
1120
1121pub(crate) fn goto_declaration_response(
1122 snap: &GlobalStateSnapshot,
1123 src: Option<FileRange>,
1124 targets: Vec<NavigationTarget>,
1125) -> Cancellable<lsp_types::DeclarationResponse> {
1126 if snap.config.location_link() {
1127 let links = targets_to_links(snap, src, targets)?;
1128 Ok(links.into())
1129 } else {
1130 let locations = targets_to_locations(snap, targets)?;
1131 Ok(lsp_types::DeclarationResponse::Declaration(lsp_types::Declaration::LocationList(
1132 locations,
1133 )))
1134 }
1135}
1136
1137pub(crate) fn goto_implementation_response(
1138 snap: &GlobalStateSnapshot,
1139 src: Option<FileRange>,
1140 targets: Vec<NavigationTarget>,
1141) -> Cancellable<lsp_types::ImplementationResponse> {
1142 if snap.config.location_link() {
1143 let links = targets_to_links(snap, src, targets)?;
1144 Ok(links.into())
1145 } else {
1146 let locations = targets_to_locations(snap, targets)?;
1147 Ok(lsp_types::ImplementationResponse::Definition(lsp_types::Definition::LocationList(
1148 locations,
1149 )))
1150 }
1151}
1152
1153pub(crate) fn goto_type_definition_response(
1154 snap: &GlobalStateSnapshot,
1155 src: Option<FileRange>,
1156 targets: Vec<NavigationTarget>,
1157) -> Cancellable<lsp_types::TypeDefinitionResponse> {
1158 if snap.config.location_link() {
1159 let links = targets_to_links(snap, src, targets)?;
1160 Ok(links.into())
1161 } else {
1162 let locations = targets_to_locations(snap, targets)?;
1163 Ok(lsp_types::TypeDefinitionResponse::Definition(lsp_types::Definition::LocationList(
1164 locations,
1165 )))
1166 }
1167}
1168
1169fn targets_to_links(
1170 snap: &GlobalStateSnapshot,
1171 src: Option<hir::FileRangeWrapper<FileId>>,
1172 targets: Vec<NavigationTarget>,
1173) -> Result<Vec<lsp_types::LocationLink>, ide_db::base_db::salsa::Cancelled> {
1174 targets
1175 .into_iter()
1176 .unique_by(|nav| (nav.file_id, nav.full_range, nav.focus_range))
1177 .map(|nav| location_link(snap, src, nav))
1178 .collect::<Cancellable<Vec<_>>>()
1179}
1180
1181fn targets_to_locations(
1182 snap: &GlobalStateSnapshot,
1183 targets: Vec<NavigationTarget>,
1184) -> Result<Vec<lsp_types::Location>, ide_db::base_db::salsa::Cancelled> {
1185 targets
1186 .into_iter()
1187 .map(|nav| FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
1188 .unique()
1189 .map(|range| location(snap, range))
1190 .collect::<Cancellable<Vec<_>>>()
1191}
1192
1193fn outside_workspace_annotation_id() -> String {
1194 String::from("OutsideWorkspace")
1195}
1196
1197fn merge_text_and_snippet_edits(
1198 line_index: &LineIndex,
1199 edit: TextEdit,
1200 snippet_edit: SnippetEdit,
1201 client_supports_annotations: bool,
1202) -> Vec<SnippetTextEdit> {
1203 let mut edits: Vec<SnippetTextEdit> = vec![];
1204 let mut snippets = snippet_edit.into_edit_ranges().into_iter().peekable();
1205 let annotation = edit.change_annotation();
1206 let text_edits = edit.into_iter();
1207 let mut source_text_offset = 0i32;
1209
1210 let offset_range = |range: TextRange, offset: i32| -> TextRange {
1211 let start = u32::from(range.start()).checked_add_signed(offset).unwrap_or(0);
1213 let end = u32::from(range.end()).checked_add_signed(offset).unwrap_or(0);
1214
1215 TextRange::new(start.into(), end.into())
1216 };
1217
1218 for current_indel in text_edits {
1219 let new_range = {
1220 let insert_len =
1221 TextSize::try_from(current_indel.insert.len()).unwrap_or(TextSize::from(u32::MAX));
1222 TextRange::at(current_indel.delete.start(), insert_len)
1223 };
1224
1225 let offset_adjustment =
1227 u32::from(current_indel.delete.len()) as i32 - u32::from(new_range.len()) as i32;
1228
1229 for (snippet_index, snippet_range) in snippets.peeking_take_while(|(_, range)| {
1231 offset_range(*range, source_text_offset).end() < new_range.start()
1232 }) {
1233 let snippet_range = offset_range(snippet_range, source_text_offset);
1235
1236 let snippet_range = if !stdx::always!(
1237 snippet_range.is_empty(),
1238 "placeholder range {:?} is before current text edit range {:?}",
1239 snippet_range,
1240 new_range
1241 ) {
1242 TextRange::empty(snippet_range.start())
1244 } else {
1245 snippet_range
1246 };
1247
1248 edits.push(snippet_text_edit(
1249 line_index,
1250 true,
1251 Indel { insert: format!("${snippet_index}"), delete: snippet_range },
1252 annotation,
1253 client_supports_annotations,
1254 ))
1255 }
1256
1257 if snippets.peek().is_some_and(|(_, range)| {
1258 new_range.intersect(offset_range(*range, source_text_offset)).is_some()
1259 }) {
1260 let mut all_snippets = snippets
1263 .peeking_take_while(|(_, range)| {
1264 new_range.intersect(offset_range(*range, source_text_offset)).is_some()
1265 })
1266 .map(|(tabstop, range)| (tabstop, offset_range(range, source_text_offset)))
1267 .collect_vec();
1268
1269 all_snippets.retain(|(_, range)| {
1271 stdx::always!(
1272 new_range.contains_range(*range),
1273 "found placeholder range {:?} which wasn't fully inside of text edit's new range {:?}", range, new_range
1274 )
1275 });
1276
1277 let mut new_text = current_indel.insert;
1278
1279 let escape_places =
1281 new_text.rmatch_indices(['\\', '$', '}']).map(|(insert, _)| insert).collect_vec();
1282 let mut escape_places = escape_places.into_iter().peekable();
1283 let mut escape_prior_bits = |new_text: &mut String, up_to: usize| {
1284 for before in escape_places.peeking_take_while(|insert| *insert >= up_to) {
1285 new_text.insert(before, '\\');
1286 }
1287 };
1288
1289 for (index, range) in all_snippets.iter().rev() {
1291 let text_range = range - new_range.start();
1292 let (start, end) = (text_range.start().into(), text_range.end().into());
1293
1294 if range.is_empty() {
1295 escape_prior_bits(&mut new_text, start);
1296 new_text.insert_str(start, &format!("${index}"));
1297 } else {
1298 escape_prior_bits(&mut new_text, end);
1299 new_text.insert(end, '}');
1300 escape_prior_bits(&mut new_text, start);
1301 new_text.insert_str(start, &format!("${{{index}:"));
1302 }
1303 }
1304
1305 escape_prior_bits(&mut new_text, 0);
1307
1308 edits.push(snippet_text_edit(
1309 line_index,
1310 true,
1311 Indel { insert: new_text, delete: current_indel.delete },
1312 annotation,
1313 client_supports_annotations,
1314 ))
1315 } else {
1316 edits.push(snippet_text_edit(
1319 line_index,
1320 false,
1321 current_indel,
1322 annotation,
1323 client_supports_annotations,
1324 ));
1325 }
1326
1327 source_text_offset += offset_adjustment;
1329 }
1330
1331 edits.extend(snippets.map(|(snippet_index, snippet_range)| {
1333 let snippet_range = offset_range(snippet_range, source_text_offset);
1335
1336 let snippet_range = if !stdx::always!(
1337 snippet_range.is_empty(),
1338 "found placeholder snippet {:?} without a text edit",
1339 snippet_range
1340 ) {
1341 TextRange::empty(snippet_range.start())
1342 } else {
1343 snippet_range
1344 };
1345
1346 snippet_text_edit(
1347 line_index,
1348 true,
1349 Indel { insert: format!("${snippet_index}"), delete: snippet_range },
1350 annotation,
1351 client_supports_annotations,
1352 )
1353 }));
1354
1355 edits
1356}
1357
1358pub(crate) fn snippet_text_document_edit(
1359 snap: &GlobalStateSnapshot,
1360 is_snippet: bool,
1361 file_id: FileId,
1362 edit: TextEdit,
1363 snippet_edit: Option<SnippetEdit>,
1364) -> Cancellable<lsp_ext::SnippetTextDocumentEdit> {
1365 let text_document = optional_versioned_text_document_identifier(snap, file_id);
1366 let line_index = snap.file_line_index(file_id)?;
1367 let client_supports_annotations = snap.config.change_annotation_support();
1368 let mut edits = if let Some(snippet_edit) = snippet_edit {
1369 merge_text_and_snippet_edits(&line_index, edit, snippet_edit, client_supports_annotations)
1370 } else {
1371 let annotation = edit.change_annotation();
1372 edit.into_iter()
1373 .map(|it| {
1374 snippet_text_edit(
1375 &line_index,
1376 is_snippet,
1377 it,
1378 annotation,
1379 client_supports_annotations,
1380 )
1381 })
1382 .collect()
1383 };
1384
1385 if snap.analysis.is_library_file(file_id)? && snap.config.change_annotation_support() {
1386 for edit in &mut edits {
1387 edit.annotation_id = Some(outside_workspace_annotation_id())
1388 }
1389 }
1390 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
1391}
1392
1393pub(crate) fn snippet_text_document_ops(
1394 snap: &GlobalStateSnapshot,
1395 file_system_edit: FileSystemEdit,
1396) -> Cancellable<Vec<lsp_ext::SnippetDocumentChangeOperation>> {
1397 let mut ops = Vec::new();
1398 match file_system_edit {
1399 FileSystemEdit::CreateFile { dst, initial_contents } => {
1400 let uri = snap.anchored_path(&dst);
1401 let create_file = lsp_types::DocumentChange::CreateFile(lsp_types::CreateFile {
1402 uri: uri.clone(),
1403 options: None,
1404 annotation_id: None,
1405 });
1406 ops.push(lsp_ext::SnippetDocumentChangeOperation::Change(create_file));
1407 if !initial_contents.is_empty() {
1408 let text_document = lsp_types::OptionalVersionedTextDocumentIdentifier {
1409 text_document_identifier: lsp_types::TextDocumentIdentifier { uri },
1410 version: None,
1411 };
1412 let text_edit = lsp_ext::SnippetTextEdit {
1413 range: lsp_types::Range::default(),
1414 new_text: initial_contents,
1415 insert_text_format: Some(lsp_types::InsertTextFormat::PlainText),
1416 annotation_id: None,
1417 };
1418 let edit_file =
1419 lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
1420 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
1421 }
1422 }
1423 FileSystemEdit::MoveFile { src, dst } => {
1424 let old_uri = snap.file_id_to_url(src);
1425 let new_uri = snap.anchored_path(&dst);
1426 let mut rename_file =
1427 lsp_types::RenameFile { old_uri, new_uri, options: None, annotation_id: None };
1428 if snap.analysis.is_library_file(src).ok() == Some(true)
1429 && snap.config.change_annotation_support()
1430 {
1431 rename_file.annotation_id = Some(outside_workspace_annotation_id())
1432 }
1433 ops.push(lsp_ext::SnippetDocumentChangeOperation::Change(
1434 lsp_types::DocumentChange::RenameFile(rename_file),
1435 ))
1436 }
1437 FileSystemEdit::MoveDir { src, src_id, dst } => {
1438 let old_uri = snap.anchored_path(&src);
1439 let new_uri = snap.anchored_path(&dst);
1440 let mut rename_file =
1441 lsp_types::RenameFile { old_uri, new_uri, options: None, annotation_id: None };
1442 if snap.analysis.is_library_file(src_id).ok() == Some(true)
1443 && snap.config.change_annotation_support()
1444 {
1445 rename_file.annotation_id = Some(outside_workspace_annotation_id())
1446 }
1447 ops.push(lsp_ext::SnippetDocumentChangeOperation::Change(
1448 lsp_types::DocumentChange::RenameFile(rename_file),
1449 ))
1450 }
1451 }
1452 Ok(ops)
1453}
1454
1455pub(crate) fn snippet_workspace_edit(
1456 snap: &GlobalStateSnapshot,
1457 mut source_change: SourceChange,
1458) -> Cancellable<lsp_ext::SnippetWorkspaceEdit> {
1459 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
1460
1461 for op in &mut source_change.file_system_edits {
1462 if let FileSystemEdit::CreateFile { dst, initial_contents } = op {
1463 let op = FileSystemEdit::CreateFile {
1465 dst: dst.clone(),
1466 initial_contents: mem::take(initial_contents),
1467 };
1468 let ops = snippet_text_document_ops(snap, op)?;
1469 document_changes.extend_from_slice(&ops);
1470 }
1471 }
1472 for (file_id, (edit, snippet_edit)) in source_change.source_file_edits {
1473 let edit = snippet_text_document_edit(
1474 snap,
1475 source_change.is_snippet,
1476 file_id,
1477 edit,
1478 snippet_edit,
1479 )?;
1480 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
1481 }
1482 for op in source_change.file_system_edits {
1483 if !matches!(op, FileSystemEdit::CreateFile { .. }) {
1484 let ops = snippet_text_document_ops(snap, op)?;
1485 document_changes.extend_from_slice(&ops);
1486 }
1487 }
1488 let mut workspace_edit = lsp_ext::SnippetWorkspaceEdit {
1489 changes: None,
1490 document_changes: Some(document_changes),
1491 change_annotations: None,
1492 };
1493 if snap.config.change_annotation_support() {
1494 workspace_edit.change_annotations = Some(
1495 once((
1496 outside_workspace_annotation_id(),
1497 lsp_types::ChangeAnnotation {
1498 label: String::from("Edit outside of the workspace"),
1499 needs_confirmation: Some(true),
1500 description: Some(String::from(
1501 "This edit lies outside of the workspace and may affect dependencies",
1502 )),
1503 },
1504 ))
1505 .chain(source_change.annotations.into_iter().map(|(id, annotation)| {
1506 (
1507 id.to_string(),
1508 lsp_types::ChangeAnnotation {
1509 label: annotation.label,
1510 description: annotation.description,
1511 needs_confirmation: Some(annotation.needs_confirmation),
1512 },
1513 )
1514 }))
1515 .collect(),
1516 )
1517 }
1518 Ok(workspace_edit)
1519}
1520
1521pub(crate) fn workspace_edit(
1522 snap: &GlobalStateSnapshot,
1523 source_change: SourceChange,
1524) -> Cancellable<lsp_types::WorkspaceEdit> {
1525 assert!(!source_change.is_snippet);
1526 snippet_workspace_edit(snap, source_change).map(|it| it.into())
1527}
1528
1529impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
1530 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
1531 lsp_types::WorkspaceEdit {
1532 changes: None,
1533 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
1534 changes
1535 .into_iter()
1536 .map(|change| match change {
1537 lsp_ext::SnippetDocumentChangeOperation::Change(op) => op,
1538 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
1539 lsp_types::DocumentChange::TextDocumentEdit(
1540 lsp_types::TextDocumentEdit {
1541 text_document: edit.text_document,
1542 edits: edit.edits.into_iter().map(From::from).collect(),
1543 },
1544 )
1545 }
1546 })
1547 .collect()
1548 }),
1549 change_annotations: snippet_workspace_edit.change_annotations,
1550 }
1551 }
1552}
1553
1554impl From<lsp_ext::SnippetTextEdit> for lsp_types::Edit {
1555 fn from(
1556 lsp_ext::SnippetTextEdit { annotation_id, insert_text_format:_, new_text, range }: lsp_ext::SnippetTextEdit,
1557 ) -> Self {
1558 match annotation_id {
1559 Some(annotation_id) => {
1560 lsp_types::Edit::AnnotatedTextEdit(lsp_types::AnnotatedTextEdit {
1561 text_edit: lsp_types::TextEdit { range, new_text },
1562 annotation_id,
1563 })
1564 }
1565 None => lsp_types::Edit::TextEdit(lsp_types::TextEdit { range, new_text }),
1566 }
1567 }
1568}
1569
1570pub(crate) fn call_hierarchy_item(
1571 snap: &GlobalStateSnapshot,
1572 target: NavigationTarget,
1573) -> Cancellable<lsp_types::CallHierarchyItem> {
1574 let name = target.name.to_string();
1575 let detail = target.description.clone();
1576 let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::Function);
1577 let (uri, range, selection_range) = location_info(snap, target)?;
1578 Ok(lsp_types::CallHierarchyItem {
1579 name,
1580 kind,
1581 tags: None,
1582 detail,
1583 uri,
1584 range,
1585 selection_range,
1586 data: None,
1587 })
1588}
1589
1590pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
1591 match kind {
1592 AssistKind::Generate => lsp_types::CodeActionKind::Empty,
1593 AssistKind::QuickFix => lsp_types::CodeActionKind::QuickFix,
1594 AssistKind::Refactor => lsp_types::CodeActionKind::Refactor,
1595 AssistKind::RefactorExtract => lsp_types::CodeActionKind::RefactorExtract,
1596 AssistKind::RefactorInline => lsp_types::CodeActionKind::RefactorInline,
1597 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::RefactorRewrite,
1598 }
1599}
1600
1601pub(crate) fn code_action(
1602 snap: &GlobalStateSnapshot,
1603 commands: &ClientCommandsConfig,
1604 assist: Assist,
1605 resolve_data: Option<(usize, lsp_types::CodeActionParams, Option<i32>)>,
1606) -> Cancellable<lsp_ext::CodeAction> {
1607 let mut res = lsp_ext::CodeAction {
1608 title: assist.label.to_string(),
1609 group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
1610 kind: Some(code_action_kind(assist.id.1)),
1611 edit: None,
1612 is_preferred: None,
1613 data: None,
1614 command: None,
1615 };
1616
1617 res.command = match assist.command {
1618 Some(assists::Command::TriggerParameterHints) if commands.trigger_parameter_hints => {
1619 Some(command::trigger_parameter_hints())
1620 }
1621 Some(assists::Command::Rename) if commands.rename => Some(command::rename()),
1622 _ => None,
1623 };
1624
1625 match (assist.source_change, resolve_data) {
1626 (Some(it), _) => res.edit = Some(snippet_workspace_edit(snap, it)?),
1627 (None, Some((index, code_action_params, version))) => {
1628 res.data = Some(lsp_ext::CodeActionData {
1629 id: format!(
1630 "{}:{}:{index}:{}",
1631 assist.id.0,
1632 assist.id.1.name(),
1633 assist.id.2.map(|x| x.to_string()).unwrap_or("".to_owned())
1634 ),
1635 code_action_params,
1636 version,
1637 });
1638 }
1639 (None, None) => {
1640 stdx::never!("assist should always be resolved if client can't do lazy resolving")
1641 }
1642 };
1643 Ok(res)
1644}
1645
1646pub(crate) fn runnable(
1647 snap: &GlobalStateSnapshot,
1648 runnable: Runnable,
1649) -> Cancellable<Option<lsp_ext::Runnable>> {
1650 let target_spec = TargetSpec::for_file(snap, runnable.nav.file_id)?;
1651 let source_root = snap.analysis.source_root_id(runnable.nav.file_id).ok();
1652 let config = snap.config.runnables(source_root);
1653
1654 match target_spec {
1655 Some(TargetSpec::Cargo(spec)) => {
1656 let workspace_root = spec.workspace_root.clone();
1657
1658 let target = spec.target.clone();
1659
1660 let override_command =
1661 CargoTargetSpec::override_command(snap, Some(spec.clone()), &runnable.kind);
1662
1663 let (cargo_args, executable_args) = CargoTargetSpec::runnable_args(
1664 snap,
1665 Some(spec.clone()),
1666 &runnable.kind,
1667 &runnable.cfg,
1668 );
1669
1670 let cwd = match runnable.kind {
1671 ide::RunnableKind::Bin => workspace_root.clone(),
1672 _ => spec.cargo_toml.parent().to_owned(),
1673 };
1674
1675 let label = runnable.label(Some(&target));
1676 let location = location_link(snap, None, runnable.nav)?;
1677
1678 let environment = spec
1679 .sysroot_root
1680 .map(|root| ("RUSTC_TOOLCHAIN".to_owned(), root.to_string()))
1681 .into_iter()
1682 .collect();
1683
1684 Ok(match override_command {
1685 Some(override_command) => match override_command.split_first() {
1686 Some((program, args)) => Some(lsp_ext::Runnable {
1687 label,
1688 location: Some(location),
1689 args: lsp_ext::RunnableArgs::Shell(lsp_ext::ShellRunnableArgs {
1690 environment,
1691 cwd: cwd.into(),
1692 program: program.to_string(),
1693 args: args.to_vec(),
1694 }),
1695 }),
1696 _ => None,
1697 },
1698 None => Some(lsp_ext::Runnable {
1699 label,
1700 location: Some(location),
1701 args: lsp_ext::RunnableArgs::Cargo(lsp_ext::CargoRunnableArgs {
1702 workspace_root: Some(workspace_root.into()),
1703 override_cargo: config.override_cargo,
1704 cargo_args,
1705 cwd: cwd.into(),
1706 executable_args,
1707 environment,
1708 }),
1709 }),
1710 })
1711 }
1712 Some(TargetSpec::ProjectJson(spec)) => {
1713 let label = runnable.label(Some(&spec.label));
1714 let location = location_link(snap, None, runnable.nav)?;
1715
1716 match spec.runnable_args(&runnable.kind) {
1717 Some(json_shell_runnable_args) => {
1718 let runnable_args = ShellRunnableArgs {
1719 program: json_shell_runnable_args.program,
1720 args: json_shell_runnable_args.args,
1721 cwd: json_shell_runnable_args.cwd,
1722 environment: Default::default(),
1723 };
1724 Ok(Some(lsp_ext::Runnable {
1725 label,
1726 location: Some(location),
1727 args: lsp_ext::RunnableArgs::Shell(runnable_args),
1728 }))
1729 }
1730 None => Ok(None),
1731 }
1732 }
1733 None => {
1734 let Some(path) = snap.file_id_to_file_path(runnable.nav.file_id).parent() else {
1735 return Ok(None);
1736 };
1737 let (cargo_args, executable_args) =
1738 CargoTargetSpec::runnable_args(snap, None, &runnable.kind, &runnable.cfg);
1739
1740 let label = runnable.label(None);
1741 let location = location_link(snap, None, runnable.nav)?;
1742
1743 Ok(Some(lsp_ext::Runnable {
1744 label,
1745 location: Some(location),
1746 args: lsp_ext::RunnableArgs::Cargo(lsp_ext::CargoRunnableArgs {
1747 workspace_root: None,
1748 override_cargo: config.override_cargo,
1749 cargo_args,
1750 cwd: path.as_path().unwrap().to_path_buf().into(),
1751 executable_args,
1752 environment: Default::default(),
1753 }),
1754 }))
1755 }
1756 }
1757}
1758
1759pub(crate) fn code_lens(
1760 acc: &mut Vec<lsp_types::CodeLens>,
1761 snap: &GlobalStateSnapshot,
1762 annotation: Annotation,
1763) -> Cancellable<()> {
1764 let client_commands_config = snap.config.client_commands();
1765 match annotation.kind {
1766 AnnotationKind::Runnable(run) => {
1767 let line_index = snap.file_line_index(run.nav.file_id)?;
1768 let annotation_range = range(&line_index, annotation.range);
1769
1770 let update_test = run.update_test;
1771 let title = run.title();
1772 let can_debug = match run.kind {
1773 ide::RunnableKind::DocTest { .. } => false,
1774 ide::RunnableKind::TestMod { .. }
1775 | ide::RunnableKind::Test { .. }
1776 | ide::RunnableKind::Bench { .. }
1777 | ide::RunnableKind::Bin => true,
1778 };
1779 let r = runnable(snap, run)?;
1780
1781 if let Some(r) = r {
1782 let has_root = match &r.args {
1783 lsp_ext::RunnableArgs::Cargo(c) => c.workspace_root.is_some(),
1784 lsp_ext::RunnableArgs::Shell(_) => true,
1785 };
1786
1787 let lens_config = snap.config.lens();
1788
1789 if has_root {
1790 if lens_config.run && client_commands_config.run_single {
1791 let command = command::run_single(&r, &title);
1792 acc.push(lsp_types::CodeLens {
1793 range: annotation_range,
1794 command: Some(command),
1795 data: None,
1796 })
1797 }
1798 if lens_config.debug && can_debug && client_commands_config.debug_single {
1799 let command = command::debug_single(&r);
1800 acc.push(lsp_types::CodeLens {
1801 range: annotation_range,
1802 command: Some(command),
1803 data: None,
1804 })
1805 }
1806 if lens_config.update_test && client_commands_config.run_single {
1807 let label = update_test.label();
1808 if let Some(r) = make_update_runnable(&r, update_test) {
1809 let command = command::run_single(&r, label.unwrap().as_str());
1810 acc.push(lsp_types::CodeLens {
1811 range: annotation_range,
1812 command: Some(command),
1813 data: None,
1814 })
1815 }
1816 }
1817 }
1818
1819 if lens_config.interpret {
1820 let command = command::interpret_single(&r);
1821 acc.push(lsp_types::CodeLens {
1822 range: annotation_range,
1823 command: Some(command),
1824 data: None,
1825 })
1826 }
1827 }
1828 }
1829 AnnotationKind::HasImpls { pos, data } => {
1830 if !client_commands_config.show_reference {
1831 return Ok(());
1832 }
1833 let line_index = snap.file_line_index(pos.file_id)?;
1834 let annotation_range = range(&line_index, annotation.range);
1835 let url = url(snap, pos.file_id);
1836 let pos = position(&line_index, pos.offset);
1837
1838 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1839
1840 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, pos);
1841
1842 let goto_params = lsp_types::ImplementationParams {
1843 text_document_position_params: doc_pos,
1844 work_done_progress_params: Default::default(),
1845 partial_result_params: Default::default(),
1846 };
1847
1848 let command = data.map(|ranges| {
1849 let locations: Vec<lsp_types::Location> = ranges
1850 .into_iter()
1851 .filter_map(|target| {
1852 location(
1853 snap,
1854 FileRange { file_id: target.file_id, range: target.full_range },
1855 )
1856 .ok()
1857 })
1858 .collect();
1859
1860 command::show_references(
1861 implementation_title(locations.len()),
1862 &url,
1863 pos,
1864 locations,
1865 )
1866 });
1867
1868 acc.push(lsp_types::CodeLens {
1869 range: annotation_range,
1870 command,
1871 data: (|| {
1872 let version = snap.url_file_version(&url)?;
1873 Some(
1874 to_value(lsp_ext::CodeLensResolveData {
1875 version,
1876 kind: lsp_ext::CodeLensResolveDataKind::Impls(goto_params),
1877 })
1878 .unwrap(),
1879 )
1880 })(),
1881 })
1882 }
1883 AnnotationKind::HasReferences { pos, data } => {
1884 if !client_commands_config.show_reference {
1885 return Ok(());
1886 }
1887 let line_index = snap.file_line_index(pos.file_id)?;
1888 let annotation_range = range(&line_index, annotation.range);
1889 let url = url(snap, pos.file_id);
1890 let pos = position(&line_index, pos.offset);
1891
1892 let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1893
1894 let doc_pos = lsp_types::TextDocumentPositionParams::new(id, pos);
1895
1896 let command = data.map(|ranges| {
1897 let locations: Vec<lsp_types::Location> =
1898 ranges.into_iter().filter_map(|range| location(snap, range).ok()).collect();
1899
1900 command::show_references(reference_title(locations.len()), &url, pos, locations)
1901 });
1902
1903 acc.push(lsp_types::CodeLens {
1904 range: annotation_range,
1905 command,
1906 data: (|| {
1907 let version = snap.url_file_version(&url)?;
1908 Some(
1909 to_value(lsp_ext::CodeLensResolveData {
1910 version,
1911 kind: lsp_ext::CodeLensResolveDataKind::References(doc_pos),
1912 })
1913 .unwrap(),
1914 )
1915 })(),
1916 })
1917 }
1918 }
1919 Ok(())
1920}
1921
1922pub(crate) fn test_item(
1923 snap: &GlobalStateSnapshot,
1924 test_item: ide::TestItem,
1925 line_index: Option<&LineIndex>,
1926) -> Option<lsp_ext::TestItem> {
1927 Some(lsp_ext::TestItem {
1928 id: test_item.id,
1929 label: test_item.label,
1930 kind: match test_item.kind {
1931 ide::TestItemKind::Crate(id) => match snap.target_spec_for_crate(id) {
1932 Some(target_spec) => match target_spec.target_kind() {
1933 TargetKind::Bin
1934 | TargetKind::Lib { .. }
1935 | TargetKind::Example
1936 | TargetKind::BuildScript
1937 | TargetKind::Other => lsp_ext::TestItemKind::Package,
1938 TargetKind::Test => lsp_ext::TestItemKind::Test,
1939 TargetKind::Bench => return None,
1941 },
1942 None => lsp_ext::TestItemKind::Package,
1943 },
1944 ide::TestItemKind::Module => lsp_ext::TestItemKind::Module,
1945 ide::TestItemKind::Function => lsp_ext::TestItemKind::Test,
1946 },
1947 can_resolve_children: matches!(
1948 test_item.kind,
1949 ide::TestItemKind::Crate(_) | ide::TestItemKind::Module
1950 ),
1951 parent: test_item.parent,
1952 text_document: test_item
1953 .file
1954 .map(|f| lsp_types::TextDocumentIdentifier { uri: url(snap, f) }),
1955 range: line_index.and_then(|l| Some(range(l, test_item.text_range?))),
1956 runnable: test_item.runnable.and_then(|r| runnable(snap, r).ok()).flatten(),
1957 })
1958}
1959
1960pub(crate) mod command {
1961 use ide::{FileRange, NavigationTarget};
1962 use serde_json::to_value;
1963
1964 use crate::{
1965 global_state::GlobalStateSnapshot,
1966 lsp::to_proto::{location, location_link},
1967 lsp_ext,
1968 };
1969
1970 pub(crate) fn show_references(
1971 title: String,
1972 uri: &lsp_types::Uri,
1973 position: lsp_types::Position,
1974 locations: Vec<lsp_types::Location>,
1975 ) -> lsp_types::Command {
1976 lsp_types::Command {
1981 title,
1982 command: "rust-analyzer.showReferences".into(),
1983 arguments: Some(vec![
1984 to_value(uri).unwrap(),
1985 to_value(position).unwrap(),
1986 to_value(locations).unwrap(),
1987 ]),
1988 tooltip: None,
1989 }
1990 }
1991
1992 pub(crate) fn run_single(runnable: &lsp_ext::Runnable, title: &str) -> lsp_types::Command {
1993 lsp_types::Command {
1994 title: title.to_owned(),
1995 command: "rust-analyzer.runSingle".into(),
1996 arguments: Some(vec![to_value(runnable).unwrap()]),
1997 tooltip: None,
1998 }
1999 }
2000
2001 pub(crate) fn debug_single(runnable: &lsp_ext::Runnable) -> lsp_types::Command {
2002 lsp_types::Command {
2003 title: "âš™\u{fe0e} Debug".into(),
2004 command: "rust-analyzer.debugSingle".into(),
2005 arguments: Some(vec![to_value(runnable).unwrap()]),
2006 tooltip: None,
2007 }
2008 }
2009
2010 pub(crate) fn interpret_single(_runnable: &lsp_ext::Runnable) -> lsp_types::Command {
2011 lsp_types::Command {
2012 title: "Interpret".into(),
2013 command: "rust-analyzer.interpretFunction".into(),
2014 arguments: Some(vec![]),
2016 tooltip: None,
2017 }
2018 }
2019
2020 pub(crate) fn goto_location(
2021 snap: &GlobalStateSnapshot,
2022 nav: &NavigationTarget,
2023 ) -> Option<lsp_types::Command> {
2024 let value = if snap.config.location_link() {
2025 let link = location_link(snap, None, nav.clone()).ok()?;
2026 to_value(link).ok()?
2027 } else {
2028 let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
2029 let location = location(snap, range).ok()?;
2030 to_value(location).ok()?
2031 };
2032
2033 Some(lsp_types::Command {
2034 title: nav.name.to_string(),
2035 command: "rust-analyzer.gotoLocation".into(),
2036 arguments: Some(vec![value]),
2037 tooltip: None,
2038 })
2039 }
2040
2041 pub(crate) fn trigger_parameter_hints() -> lsp_types::Command {
2042 lsp_types::Command {
2043 title: "triggerParameterHints".into(),
2044 command: "rust-analyzer.triggerParameterHints".into(),
2045 arguments: None,
2046 tooltip: None,
2047 }
2048 }
2049
2050 pub(crate) fn rename() -> lsp_types::Command {
2051 lsp_types::Command {
2052 title: "rename".into(),
2053 command: "rust-analyzer.rename".into(),
2054 arguments: None,
2055 tooltip: None,
2056 }
2057 }
2058}
2059
2060pub(crate) fn make_update_runnable(
2061 runnable: &lsp_ext::Runnable,
2062 update_test: UpdateTest,
2063) -> Option<lsp_ext::Runnable> {
2064 let label = update_test.label()?;
2065
2066 let mut runnable = runnable.clone();
2067 runnable.label = format!("{} + {}", runnable.label, label);
2068
2069 let lsp_ext::RunnableArgs::Cargo(r) = &mut runnable.args else {
2070 return None;
2071 };
2072
2073 r.environment.extend(update_test.env().iter().map(|(k, v)| (k.to_string(), v.to_string())));
2074
2075 if update_test.insta {
2076 r.cargo_args.insert(0, "insta".to_owned());
2077 }
2078
2079 Some(runnable)
2080}
2081
2082pub(crate) fn implementation_title(count: usize) -> String {
2083 if count == 1 { "1 implementation".into() } else { format!("{count} implementations") }
2084}
2085
2086pub(crate) fn reference_title(count: usize) -> String {
2087 if count == 1 { "1 reference".into() } else { format!("{count} references") }
2088}
2089
2090pub(crate) fn markup_content(
2091 markup: Markup,
2092 kind: ide::HoverDocFormat,
2093) -> lsp_types::MarkupContent {
2094 let kind = match kind {
2095 ide::HoverDocFormat::Markdown => lsp_types::MarkupKind::Markdown,
2096 ide::HoverDocFormat::PlainText => lsp_types::MarkupKind::PlainText,
2097 };
2098 let value = format_docs(&Documentation::new_owned(markup.into()));
2099 lsp_types::MarkupContent { kind, value }
2100}
2101
2102pub(crate) fn rename_error(err: RenameError) -> LspError {
2103 invalid_params_error(err.to_string())
2106}
2107
2108#[cfg(test)]
2109mod tests {
2110 use expect_test::{Expect, expect};
2111 use ide::{Analysis, FilePosition};
2112 use ide_db::base_db::AbsPathBuf;
2113 use ide_db::source_change::Snippet;
2114 use test_utils::extract_offset;
2115 use triomphe::Arc;
2116
2117 use super::*;
2118
2119 #[test]
2120 fn conv_fold_line_folding_only_fixup() {
2121 let text = r#"mod a;
2122mod b;
2123mod c;
2124
2125fn main() {
2126 if cond {
2127 a::do_a();
2128 } else {
2129 b::do_b();
2130 }
2131}"#;
2132
2133 let (analysis, file_id) = Analysis::from_single_file(
2134 text.to_owned(),
2135 Arc::new(AbsPathBuf::assert_utf8(std::env::current_dir().unwrap())),
2136 );
2137 let folds = analysis.folding_ranges(file_id, true).unwrap();
2138 assert_eq!(folds.len(), 5);
2139
2140 let line_index = LineIndex {
2141 index: Arc::new(ide::LineIndex::new(text)),
2142 endings: LineEndings::Unix,
2143 encoding: PositionEncoding::Utf8,
2144 };
2145 let converted: Vec<lsp_types::FoldingRange> =
2146 folds.into_iter().map(|it| folding_range(text, &line_index, true, it)).collect();
2147
2148 let expected_lines = [(0, 2), (4, 10), (5, 9), (5, 6), (7, 9)];
2149 assert_eq!(converted.len(), expected_lines.len());
2150 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
2151 assert_eq!(folding_range.start_line, *start_line);
2152 assert_eq!(folding_range.start_character, None);
2153 assert_eq!(folding_range.end_line, *end_line);
2154 assert_eq!(folding_range.end_character, None);
2155 }
2156 }
2157
2158 #[test]
2159 fn calling_function_with_ignored_code_in_signature() {
2160 let text = r#"
2161fn foo() {
2162 bar($0);
2163}
2164/// ```
2165/// # use crate::bar;
2166/// bar(5);
2167/// ```
2168fn bar(_: usize) {}
2169"#;
2170
2171 let (offset, text) = extract_offset(text);
2172 let (analysis, file_id) = Analysis::from_single_file(
2173 text,
2174 Arc::new(AbsPathBuf::assert_utf8(std::env::current_dir().unwrap())),
2175 );
2176 let help = signature_help(
2177 analysis.signature_help(FilePosition { file_id, offset }).unwrap().unwrap(),
2178 CallInfoConfig { params_only: false, docs: true },
2179 false,
2180 );
2181 let docs = match &help.signatures[help.active_signature.unwrap() as usize].documentation {
2182 Some(lsp_types::Documentation::MarkupContent(content)) => &content.value,
2183 _ => panic!("documentation contains markup"),
2184 };
2185 assert!(docs.contains("bar(5)"));
2186 assert!(!docs.contains("use crate::bar"));
2187 }
2188
2189 #[track_caller]
2190 fn check_rendered_snippets(edit: TextEdit, snippets: SnippetEdit, expect: Expect) {
2191 check_rendered_snippets_in_source(
2192 r"/* place to put all ranges in */",
2193 edit,
2194 snippets,
2195 expect,
2196 );
2197 }
2198
2199 #[track_caller]
2200 fn check_rendered_snippets_in_source(
2201 #[rust_analyzer::rust_fixture] ra_fixture: &str,
2202 edit: TextEdit,
2203 snippets: SnippetEdit,
2204 expect: Expect,
2205 ) {
2206 let source = stdx::trim_indent(ra_fixture);
2207 let endings = if source.contains('\r') { LineEndings::Dos } else { LineEndings::Unix };
2208 let line_index = LineIndex {
2209 index: Arc::new(ide::LineIndex::new(&source)),
2210 endings,
2211 encoding: PositionEncoding::Utf8,
2212 };
2213
2214 let res = merge_text_and_snippet_edits(&line_index, edit, snippets, true);
2215
2216 {
2218 let mut sorted = res.clone();
2219 sorted.sort_by_key(|edit| (edit.range.start, edit.range.end));
2220 let disjoint_ranges = sorted
2221 .iter()
2222 .zip(sorted.iter().skip(1))
2223 .all(|(l, r)| l.range.end <= r.range.start || l == r);
2224 assert!(disjoint_ranges, "ranges overlap for {res:#?}");
2225 }
2226
2227 expect.assert_debug_eq(&res);
2228 }
2229
2230 #[test]
2231 fn snippet_rendering_only_tabstops() {
2232 let edit = TextEdit::builder().finish();
2233 let snippets = SnippetEdit::new(vec![
2234 Snippet::Tabstop(0.into()),
2235 Snippet::Tabstop(0.into()),
2236 Snippet::Tabstop(1.into()),
2237 Snippet::Tabstop(1.into()),
2238 ]);
2239
2240 check_rendered_snippets(
2241 edit,
2242 snippets,
2243 expect![[r#"
2244 [
2245 SnippetTextEdit {
2246 range: Range {
2247 start: Position {
2248 line: 0,
2249 character: 0,
2250 },
2251 end: Position {
2252 line: 0,
2253 character: 0,
2254 },
2255 },
2256 new_text: "$1",
2257 insert_text_format: Some(
2258 Snippet,
2259 ),
2260 annotation_id: None,
2261 },
2262 SnippetTextEdit {
2263 range: Range {
2264 start: Position {
2265 line: 0,
2266 character: 0,
2267 },
2268 end: Position {
2269 line: 0,
2270 character: 0,
2271 },
2272 },
2273 new_text: "$2",
2274 insert_text_format: Some(
2275 Snippet,
2276 ),
2277 annotation_id: None,
2278 },
2279 SnippetTextEdit {
2280 range: Range {
2281 start: Position {
2282 line: 0,
2283 character: 1,
2284 },
2285 end: Position {
2286 line: 0,
2287 character: 1,
2288 },
2289 },
2290 new_text: "$3",
2291 insert_text_format: Some(
2292 Snippet,
2293 ),
2294 annotation_id: None,
2295 },
2296 SnippetTextEdit {
2297 range: Range {
2298 start: Position {
2299 line: 0,
2300 character: 1,
2301 },
2302 end: Position {
2303 line: 0,
2304 character: 1,
2305 },
2306 },
2307 new_text: "$0",
2308 insert_text_format: Some(
2309 Snippet,
2310 ),
2311 annotation_id: None,
2312 },
2313 ]
2314 "#]],
2315 );
2316 }
2317
2318 #[test]
2319 fn snippet_rendering_only_text_edits() {
2320 let mut edit = TextEdit::builder();
2321 edit.insert(0.into(), "abc".to_owned());
2322 edit.insert(3.into(), "def".to_owned());
2323 let edit = edit.finish();
2324 let snippets = SnippetEdit::new(vec![]);
2325
2326 check_rendered_snippets(
2327 edit,
2328 snippets,
2329 expect![[r#"
2330 [
2331 SnippetTextEdit {
2332 range: Range {
2333 start: Position {
2334 line: 0,
2335 character: 0,
2336 },
2337 end: Position {
2338 line: 0,
2339 character: 0,
2340 },
2341 },
2342 new_text: "abc",
2343 insert_text_format: None,
2344 annotation_id: None,
2345 },
2346 SnippetTextEdit {
2347 range: Range {
2348 start: Position {
2349 line: 0,
2350 character: 3,
2351 },
2352 end: Position {
2353 line: 0,
2354 character: 3,
2355 },
2356 },
2357 new_text: "def",
2358 insert_text_format: None,
2359 annotation_id: None,
2360 },
2361 ]
2362 "#]],
2363 );
2364 }
2365
2366 #[test]
2367 fn snippet_rendering_tabstop_after_text_edit() {
2368 let mut edit = TextEdit::builder();
2369 edit.insert(0.into(), "abc".to_owned());
2370 let edit = edit.finish();
2371 let snippets = SnippetEdit::new(vec![Snippet::Tabstop(10.into())]);
2373
2374 check_rendered_snippets(
2375 edit,
2376 snippets,
2377 expect![[r#"
2378 [
2379 SnippetTextEdit {
2380 range: Range {
2381 start: Position {
2382 line: 0,
2383 character: 0,
2384 },
2385 end: Position {
2386 line: 0,
2387 character: 0,
2388 },
2389 },
2390 new_text: "abc",
2391 insert_text_format: None,
2392 annotation_id: None,
2393 },
2394 SnippetTextEdit {
2395 range: Range {
2396 start: Position {
2397 line: 0,
2398 character: 7,
2399 },
2400 end: Position {
2401 line: 0,
2402 character: 7,
2403 },
2404 },
2405 new_text: "$0",
2406 insert_text_format: Some(
2407 Snippet,
2408 ),
2409 annotation_id: None,
2410 },
2411 ]
2412 "#]],
2413 );
2414 }
2415
2416 #[test]
2417 fn snippet_rendering_tabstops_before_text_edit() {
2418 let mut edit = TextEdit::builder();
2419 edit.insert(2.into(), "abc".to_owned());
2420 let edit = edit.finish();
2421 let snippets =
2422 SnippetEdit::new(vec![Snippet::Tabstop(0.into()), Snippet::Tabstop(0.into())]);
2423
2424 check_rendered_snippets(
2425 edit,
2426 snippets,
2427 expect![[r#"
2428 [
2429 SnippetTextEdit {
2430 range: Range {
2431 start: Position {
2432 line: 0,
2433 character: 0,
2434 },
2435 end: Position {
2436 line: 0,
2437 character: 0,
2438 },
2439 },
2440 new_text: "$1",
2441 insert_text_format: Some(
2442 Snippet,
2443 ),
2444 annotation_id: None,
2445 },
2446 SnippetTextEdit {
2447 range: Range {
2448 start: Position {
2449 line: 0,
2450 character: 0,
2451 },
2452 end: Position {
2453 line: 0,
2454 character: 0,
2455 },
2456 },
2457 new_text: "$0",
2458 insert_text_format: Some(
2459 Snippet,
2460 ),
2461 annotation_id: None,
2462 },
2463 SnippetTextEdit {
2464 range: Range {
2465 start: Position {
2466 line: 0,
2467 character: 2,
2468 },
2469 end: Position {
2470 line: 0,
2471 character: 2,
2472 },
2473 },
2474 new_text: "abc",
2475 insert_text_format: None,
2476 annotation_id: None,
2477 },
2478 ]
2479 "#]],
2480 );
2481 }
2482
2483 #[test]
2484 fn snippet_rendering_tabstops_between_text_edits() {
2485 let mut edit = TextEdit::builder();
2486 edit.insert(0.into(), "abc".to_owned());
2487 edit.insert(7.into(), "abc".to_owned());
2488 let edit = edit.finish();
2489 let snippets =
2491 SnippetEdit::new(vec![Snippet::Tabstop(7.into()), Snippet::Tabstop(7.into())]);
2492
2493 check_rendered_snippets(
2494 edit,
2495 snippets,
2496 expect![[r#"
2497 [
2498 SnippetTextEdit {
2499 range: Range {
2500 start: Position {
2501 line: 0,
2502 character: 0,
2503 },
2504 end: Position {
2505 line: 0,
2506 character: 0,
2507 },
2508 },
2509 new_text: "abc",
2510 insert_text_format: None,
2511 annotation_id: None,
2512 },
2513 SnippetTextEdit {
2514 range: Range {
2515 start: Position {
2516 line: 0,
2517 character: 4,
2518 },
2519 end: Position {
2520 line: 0,
2521 character: 4,
2522 },
2523 },
2524 new_text: "$1",
2525 insert_text_format: Some(
2526 Snippet,
2527 ),
2528 annotation_id: None,
2529 },
2530 SnippetTextEdit {
2531 range: Range {
2532 start: Position {
2533 line: 0,
2534 character: 4,
2535 },
2536 end: Position {
2537 line: 0,
2538 character: 4,
2539 },
2540 },
2541 new_text: "$0",
2542 insert_text_format: Some(
2543 Snippet,
2544 ),
2545 annotation_id: None,
2546 },
2547 SnippetTextEdit {
2548 range: Range {
2549 start: Position {
2550 line: 0,
2551 character: 7,
2552 },
2553 end: Position {
2554 line: 0,
2555 character: 7,
2556 },
2557 },
2558 new_text: "abc",
2559 insert_text_format: None,
2560 annotation_id: None,
2561 },
2562 ]
2563 "#]],
2564 );
2565 }
2566
2567 #[test]
2568 fn snippet_rendering_multiple_tabstops_in_text_edit() {
2569 let mut edit = TextEdit::builder();
2570 edit.insert(0.into(), "abcdefghijkl".to_owned());
2571 let edit = edit.finish();
2572 let snippets = SnippetEdit::new(vec![
2573 Snippet::Tabstop(0.into()),
2574 Snippet::Tabstop(5.into()),
2575 Snippet::Tabstop(12.into()),
2576 ]);
2577
2578 check_rendered_snippets(
2579 edit,
2580 snippets,
2581 expect![[r#"
2582 [
2583 SnippetTextEdit {
2584 range: Range {
2585 start: Position {
2586 line: 0,
2587 character: 0,
2588 },
2589 end: Position {
2590 line: 0,
2591 character: 0,
2592 },
2593 },
2594 new_text: "$1abcde$2fghijkl$0",
2595 insert_text_format: Some(
2596 Snippet,
2597 ),
2598 annotation_id: None,
2599 },
2600 ]
2601 "#]],
2602 );
2603 }
2604
2605 #[test]
2606 fn snippet_rendering_multiple_placeholders_in_text_edit() {
2607 let mut edit = TextEdit::builder();
2608 edit.insert(0.into(), "abcdefghijkl".to_owned());
2609 let edit = edit.finish();
2610 let snippets = SnippetEdit::new(vec![
2611 Snippet::Placeholder(TextRange::new(0.into(), 3.into())),
2612 Snippet::Placeholder(TextRange::new(5.into(), 7.into())),
2613 Snippet::Placeholder(TextRange::new(10.into(), 12.into())),
2614 ]);
2615
2616 check_rendered_snippets(
2617 edit,
2618 snippets,
2619 expect![[r#"
2620 [
2621 SnippetTextEdit {
2622 range: Range {
2623 start: Position {
2624 line: 0,
2625 character: 0,
2626 },
2627 end: Position {
2628 line: 0,
2629 character: 0,
2630 },
2631 },
2632 new_text: "${1:abc}de${2:fg}hij${0:kl}",
2633 insert_text_format: Some(
2634 Snippet,
2635 ),
2636 annotation_id: None,
2637 },
2638 ]
2639 "#]],
2640 );
2641 }
2642
2643 #[test]
2644 fn snippet_rendering_escape_snippet_bits() {
2645 let mut edit = TextEdit::builder();
2647 edit.insert(0.into(), r"$ab{}$c\def".to_owned());
2648 edit.insert(8.into(), r"ghi\jk<-check_insert_here$".to_owned());
2649 edit.insert(10.into(), r"a\\b\\c{}$".to_owned());
2650 let edit = edit.finish();
2651 let snippets = SnippetEdit::new(vec![
2652 Snippet::Placeholder(TextRange::new(1.into(), 9.into())),
2653 Snippet::Tabstop(25.into()),
2654 ]);
2655
2656 check_rendered_snippets(
2657 edit,
2658 snippets,
2659 expect![[r#"
2660 [
2661 SnippetTextEdit {
2662 range: Range {
2663 start: Position {
2664 line: 0,
2665 character: 0,
2666 },
2667 end: Position {
2668 line: 0,
2669 character: 0,
2670 },
2671 },
2672 new_text: "\\$${1:ab{\\}\\$c\\\\d}ef",
2673 insert_text_format: Some(
2674 Snippet,
2675 ),
2676 annotation_id: None,
2677 },
2678 SnippetTextEdit {
2679 range: Range {
2680 start: Position {
2681 line: 0,
2682 character: 8,
2683 },
2684 end: Position {
2685 line: 0,
2686 character: 8,
2687 },
2688 },
2689 new_text: "ghi\\\\jk$0<-check_insert_here\\$",
2690 insert_text_format: Some(
2691 Snippet,
2692 ),
2693 annotation_id: None,
2694 },
2695 SnippetTextEdit {
2696 range: Range {
2697 start: Position {
2698 line: 0,
2699 character: 10,
2700 },
2701 end: Position {
2702 line: 0,
2703 character: 10,
2704 },
2705 },
2706 new_text: "a\\\\b\\\\c{}$",
2707 insert_text_format: None,
2708 annotation_id: None,
2709 },
2710 ]
2711 "#]],
2712 );
2713 }
2714
2715 #[test]
2716 fn snippet_rendering_tabstop_adjust_offset_deleted() {
2717 let mut edit = TextEdit::builder();
2719 edit.replace(TextRange::new(47.into(), 56.into()), "let".to_owned());
2720 edit.replace(
2721 TextRange::new(57.into(), 89.into()),
2722 "disabled = false;\n ProcMacro {\n disabled,\n }".to_owned(),
2723 );
2724 let edit = edit.finish();
2725 let snippets = SnippetEdit::new(vec![Snippet::Tabstop(51.into())]);
2726
2727 check_rendered_snippets_in_source(
2728 r"
2729fn expander_to_proc_macro() -> ProcMacro {
2730 ProcMacro {
2731 disabled: false,
2732 }
2733}
2734
2735struct ProcMacro {
2736 disabled: bool,
2737}",
2738 edit,
2739 snippets,
2740 expect![[r#"
2741 [
2742 SnippetTextEdit {
2743 range: Range {
2744 start: Position {
2745 line: 1,
2746 character: 4,
2747 },
2748 end: Position {
2749 line: 1,
2750 character: 13,
2751 },
2752 },
2753 new_text: "let",
2754 insert_text_format: None,
2755 annotation_id: None,
2756 },
2757 SnippetTextEdit {
2758 range: Range {
2759 start: Position {
2760 line: 1,
2761 character: 14,
2762 },
2763 end: Position {
2764 line: 3,
2765 character: 5,
2766 },
2767 },
2768 new_text: "$0disabled = false;\n ProcMacro {\n disabled,\n \\}",
2769 insert_text_format: Some(
2770 Snippet,
2771 ),
2772 annotation_id: None,
2773 },
2774 ]
2775 "#]],
2776 );
2777 }
2778
2779 #[test]
2780 fn snippet_rendering_tabstop_adjust_offset_added() {
2781 let mut edit = TextEdit::builder();
2783 edit.replace(TextRange::new(39.into(), 40.into()), "let".to_owned());
2784 edit.replace(
2785 TextRange::new(41.into(), 73.into()),
2786 "disabled = false;\n ProcMacro {\n disabled,\n }".to_owned(),
2787 );
2788 let edit = edit.finish();
2789 let snippets = SnippetEdit::new(vec![Snippet::Tabstop(43.into())]);
2790
2791 check_rendered_snippets_in_source(
2792 r"
2793fn expander_to_proc_macro() -> P {
2794 P {
2795 disabled: false,
2796 }
2797}
2798
2799struct P {
2800 disabled: bool,
2801}",
2802 edit,
2803 snippets,
2804 expect![[r#"
2805 [
2806 SnippetTextEdit {
2807 range: Range {
2808 start: Position {
2809 line: 1,
2810 character: 4,
2811 },
2812 end: Position {
2813 line: 1,
2814 character: 5,
2815 },
2816 },
2817 new_text: "let",
2818 insert_text_format: None,
2819 annotation_id: None,
2820 },
2821 SnippetTextEdit {
2822 range: Range {
2823 start: Position {
2824 line: 1,
2825 character: 6,
2826 },
2827 end: Position {
2828 line: 3,
2829 character: 5,
2830 },
2831 },
2832 new_text: "$0disabled = false;\n ProcMacro {\n disabled,\n \\}",
2833 insert_text_format: Some(
2834 Snippet,
2835 ),
2836 annotation_id: None,
2837 },
2838 ]
2839 "#]],
2840 );
2841 }
2842
2843 #[test]
2844 fn snippet_rendering_placeholder_adjust_offset_deleted() {
2845 let mut edit = TextEdit::builder();
2847 edit.replace(TextRange::new(47.into(), 56.into()), "let".to_owned());
2848 edit.replace(
2849 TextRange::new(57.into(), 89.into()),
2850 "disabled = false;\n ProcMacro {\n disabled,\n }".to_owned(),
2851 );
2852 let edit = edit.finish();
2853 let snippets =
2854 SnippetEdit::new(vec![Snippet::Placeholder(TextRange::new(51.into(), 59.into()))]);
2855
2856 check_rendered_snippets_in_source(
2857 r"
2858fn expander_to_proc_macro() -> ProcMacro {
2859 ProcMacro {
2860 disabled: false,
2861 }
2862}
2863
2864struct ProcMacro {
2865 disabled: bool,
2866}",
2867 edit,
2868 snippets,
2869 expect![[r#"
2870 [
2871 SnippetTextEdit {
2872 range: Range {
2873 start: Position {
2874 line: 1,
2875 character: 4,
2876 },
2877 end: Position {
2878 line: 1,
2879 character: 13,
2880 },
2881 },
2882 new_text: "let",
2883 insert_text_format: None,
2884 annotation_id: None,
2885 },
2886 SnippetTextEdit {
2887 range: Range {
2888 start: Position {
2889 line: 1,
2890 character: 14,
2891 },
2892 end: Position {
2893 line: 3,
2894 character: 5,
2895 },
2896 },
2897 new_text: "${0:disabled} = false;\n ProcMacro {\n disabled,\n \\}",
2898 insert_text_format: Some(
2899 Snippet,
2900 ),
2901 annotation_id: None,
2902 },
2903 ]
2904 "#]],
2905 );
2906 }
2907
2908 #[test]
2909 fn snippet_rendering_placeholder_adjust_offset_added() {
2910 let mut edit = TextEdit::builder();
2912 edit.replace(TextRange::new(39.into(), 40.into()), "let".to_owned());
2913 edit.replace(
2914 TextRange::new(41.into(), 73.into()),
2915 "disabled = false;\n ProcMacro {\n disabled,\n }".to_owned(),
2916 );
2917 let edit = edit.finish();
2918 let snippets =
2919 SnippetEdit::new(vec![Snippet::Placeholder(TextRange::new(43.into(), 51.into()))]);
2920
2921 check_rendered_snippets_in_source(
2922 r"
2923fn expander_to_proc_macro() -> P {
2924 P {
2925 disabled: false,
2926 }
2927}
2928
2929struct P {
2930 disabled: bool,
2931}",
2932 edit,
2933 snippets,
2934 expect![[r#"
2935 [
2936 SnippetTextEdit {
2937 range: Range {
2938 start: Position {
2939 line: 1,
2940 character: 4,
2941 },
2942 end: Position {
2943 line: 1,
2944 character: 5,
2945 },
2946 },
2947 new_text: "let",
2948 insert_text_format: None,
2949 annotation_id: None,
2950 },
2951 SnippetTextEdit {
2952 range: Range {
2953 start: Position {
2954 line: 1,
2955 character: 6,
2956 },
2957 end: Position {
2958 line: 3,
2959 character: 5,
2960 },
2961 },
2962 new_text: "${0:disabled} = false;\n ProcMacro {\n disabled,\n \\}",
2963 insert_text_format: Some(
2964 Snippet,
2965 ),
2966 annotation_id: None,
2967 },
2968 ]
2969 "#]],
2970 );
2971 }
2972
2973 #[test]
2974 fn snippet_rendering_tabstop_adjust_offset_between_text_edits() {
2975 let mut edit = TextEdit::builder();
2977 edit.replace(TextRange::new(47.into(), 56.into()), "let".to_owned());
2978 edit.replace(
2979 TextRange::new(58.into(), 90.into()),
2980 "disabled = false;\n ProcMacro {\n disabled,\n }".to_owned(),
2981 );
2982 let edit = edit.finish();
2983 let snippets = SnippetEdit::new(vec![Snippet::Tabstop(51.into())]);
2984
2985 check_rendered_snippets_in_source(
2987 r"
2988fn expander_to_proc_macro() -> ProcMacro {
2989 ProcMacro {
2990 disabled: false,
2991 }
2992}
2993
2994struct ProcMacro {
2995 disabled: bool,
2996}",
2997 edit,
2998 snippets,
2999 expect![[r#"
3000 [
3001 SnippetTextEdit {
3002 range: Range {
3003 start: Position {
3004 line: 1,
3005 character: 4,
3006 },
3007 end: Position {
3008 line: 1,
3009 character: 13,
3010 },
3011 },
3012 new_text: "let",
3013 insert_text_format: None,
3014 annotation_id: None,
3015 },
3016 SnippetTextEdit {
3017 range: Range {
3018 start: Position {
3019 line: 1,
3020 character: 14,
3021 },
3022 end: Position {
3023 line: 1,
3024 character: 14,
3025 },
3026 },
3027 new_text: "$0",
3028 insert_text_format: Some(
3029 Snippet,
3030 ),
3031 annotation_id: None,
3032 },
3033 SnippetTextEdit {
3034 range: Range {
3035 start: Position {
3036 line: 1,
3037 character: 15,
3038 },
3039 end: Position {
3040 line: 3,
3041 character: 5,
3042 },
3043 },
3044 new_text: "disabled = false;\n ProcMacro {\n disabled,\n }",
3045 insert_text_format: None,
3046 annotation_id: None,
3047 },
3048 ]
3049"#]],
3050 );
3051 }
3052
3053 #[test]
3054 fn snippet_rendering_tabstop_adjust_offset_after_text_edits() {
3055 let mut edit = TextEdit::builder();
3057 edit.replace(TextRange::new(47.into(), 56.into()), "let".to_owned());
3058 edit.replace(
3059 TextRange::new(57.into(), 89.into()),
3060 "disabled = false;\n ProcMacro {\n disabled,\n }".to_owned(),
3061 );
3062 let edit = edit.finish();
3063 let snippets = SnippetEdit::new(vec![Snippet::Tabstop(109.into())]);
3064
3065 check_rendered_snippets_in_source(
3066 r"
3067fn expander_to_proc_macro() -> ProcMacro {
3068 ProcMacro {
3069 disabled: false,
3070 }
3071}
3072
3073struct ProcMacro {
3074 disabled: bool,
3075}",
3076 edit,
3077 snippets,
3078 expect![[r#"
3079 [
3080 SnippetTextEdit {
3081 range: Range {
3082 start: Position {
3083 line: 1,
3084 character: 4,
3085 },
3086 end: Position {
3087 line: 1,
3088 character: 13,
3089 },
3090 },
3091 new_text: "let",
3092 insert_text_format: None,
3093 annotation_id: None,
3094 },
3095 SnippetTextEdit {
3096 range: Range {
3097 start: Position {
3098 line: 1,
3099 character: 14,
3100 },
3101 end: Position {
3102 line: 3,
3103 character: 5,
3104 },
3105 },
3106 new_text: "disabled = false;\n ProcMacro {\n disabled,\n }",
3107 insert_text_format: None,
3108 annotation_id: None,
3109 },
3110 SnippetTextEdit {
3111 range: Range {
3112 start: Position {
3113 line: 4,
3114 character: 0,
3115 },
3116 end: Position {
3117 line: 4,
3118 character: 0,
3119 },
3120 },
3121 new_text: "$0",
3122 insert_text_format: Some(
3123 Snippet,
3124 ),
3125 annotation_id: None,
3126 },
3127 ]
3128"#]],
3129 );
3130 }
3131
3132 #[test]
3133 fn snippet_rendering_handle_dos_line_endings() {
3134 let mut edit = TextEdit::builder();
3136 edit.insert(6.into(), "\n\n->".to_owned());
3137
3138 let edit = edit.finish();
3139 let snippets = SnippetEdit::new(vec![Snippet::Tabstop(10.into())]);
3140
3141 check_rendered_snippets_in_source(
3142 "yeah\r\n<-tabstop here",
3143 edit,
3144 snippets,
3145 expect![[r#"
3146 [
3147 SnippetTextEdit {
3148 range: Range {
3149 start: Position {
3150 line: 1,
3151 character: 0,
3152 },
3153 end: Position {
3154 line: 1,
3155 character: 0,
3156 },
3157 },
3158 new_text: "\r\n\r\n->$0",
3159 insert_text_format: Some(
3160 Snippet,
3161 ),
3162 annotation_id: None,
3163 },
3164 ]
3165 "#]],
3166 )
3167 }
3168
3169 #[test]
3171 #[cfg(target_os = "windows")]
3172 fn test_lowercase_drive_letter() {
3173 use paths::Utf8Path;
3174
3175 let url = url_from_abs_path(Utf8Path::new("C:\\Test").try_into().unwrap());
3176 assert_eq!(url.to_string(), "file:///c:/Test");
3177
3178 let url = url_from_abs_path(Utf8Path::new(r#"\\localhost\C$\my_dir"#).try_into().unwrap());
3179 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");
3180 }
3181}