1 //! Convenience module responsible for translating between rust-analyzer's types
5 self, CreateFile, DiagnosticSeverity, DocumentChangeOperation, DocumentChanges, Documentation,
6 Location, LocationLink, MarkupContent, MarkupKind, ParameterInformation, ParameterLabel,
7 Position, Range, RenameFile, ResourceOp, SemanticTokenModifier, SemanticTokenType,
8 SignatureInformation, SymbolKind, TextDocumentEdit, TextDocumentIdentifier, TextDocumentItem,
9 TextDocumentPositionParams, Url, VersionedTextDocumentIdentifier, WorkspaceEdit,
12 translate_offset_with_edit, CompletionItem, CompletionItemKind, CompletionScore, FileId,
13 FilePosition, FileRange, FileSystemEdit, Fold, FoldKind, Highlight, HighlightModifier,
14 HighlightTag, InlayHint, InlayKind, InsertTextFormat, LineCol, LineIndex, NavigationTarget,
15 RangeInfo, ReferenceAccess, Severity, SourceChange, SourceFileEdit,
17 use ra_syntax::{SyntaxKind, TextRange, TextUnit};
18 use ra_text_edit::{AtomTextEdit, TextEdit};
19 use ra_vfs::LineEndings;
23 semantic_tokens::{self, ModifierSet, CONSTANT, CONTROL_FLOW, MUTABLE, UNSAFE},
27 use semantic_tokens::{
28 ATTRIBUTE, BUILTIN_TYPE, ENUM_MEMBER, LIFETIME, TYPE_ALIAS, UNION, UNRESOLVED_REFERENCE,
33 fn conv(self) -> Self::Output;
36 pub trait ConvWith<CTX> {
38 fn conv_with(self, ctx: CTX) -> Self::Output;
41 pub trait TryConvWith<CTX> {
43 fn try_conv_with(self, ctx: CTX) -> Result<Self::Output>;
46 impl Conv for SyntaxKind {
47 type Output = SymbolKind;
49 fn conv(self) -> <Self as Conv>::Output {
51 SyntaxKind::FN_DEF => SymbolKind::Function,
52 SyntaxKind::STRUCT_DEF => SymbolKind::Struct,
53 SyntaxKind::ENUM_DEF => SymbolKind::Enum,
54 SyntaxKind::ENUM_VARIANT => SymbolKind::EnumMember,
55 SyntaxKind::TRAIT_DEF => SymbolKind::Interface,
56 SyntaxKind::MACRO_CALL => SymbolKind::Function,
57 SyntaxKind::MODULE => SymbolKind::Module,
58 SyntaxKind::TYPE_ALIAS_DEF => SymbolKind::TypeParameter,
59 SyntaxKind::RECORD_FIELD_DEF => SymbolKind::Field,
60 SyntaxKind::STATIC_DEF => SymbolKind::Constant,
61 SyntaxKind::CONST_DEF => SymbolKind::Constant,
62 SyntaxKind::IMPL_DEF => SymbolKind::Object,
63 _ => SymbolKind::Variable,
68 impl Conv for ReferenceAccess {
69 type Output = ::lsp_types::DocumentHighlightKind;
71 fn conv(self) -> Self::Output {
72 use lsp_types::DocumentHighlightKind;
74 ReferenceAccess::Read => DocumentHighlightKind::Read,
75 ReferenceAccess::Write => DocumentHighlightKind::Write,
80 impl Conv for CompletionItemKind {
81 type Output = ::lsp_types::CompletionItemKind;
83 fn conv(self) -> <Self as Conv>::Output {
84 use lsp_types::CompletionItemKind::*;
86 CompletionItemKind::Keyword => Keyword,
87 CompletionItemKind::Snippet => Snippet,
88 CompletionItemKind::Module => Module,
89 CompletionItemKind::Function => Function,
90 CompletionItemKind::Struct => Struct,
91 CompletionItemKind::Enum => Enum,
92 CompletionItemKind::EnumVariant => EnumMember,
93 CompletionItemKind::BuiltinType => Struct,
94 CompletionItemKind::Binding => Variable,
95 CompletionItemKind::Field => Field,
96 CompletionItemKind::Trait => Interface,
97 CompletionItemKind::TypeAlias => Struct,
98 CompletionItemKind::Const => Constant,
99 CompletionItemKind::Static => Value,
100 CompletionItemKind::Method => Method,
101 CompletionItemKind::TypeParam => TypeParameter,
102 CompletionItemKind::Macro => Method,
107 impl Conv for Severity {
108 type Output = DiagnosticSeverity;
109 fn conv(self) -> DiagnosticSeverity {
111 Severity::Error => DiagnosticSeverity::Error,
112 Severity::WeakWarning => DiagnosticSeverity::Hint,
117 impl ConvWith<(&LineIndex, LineEndings, usize)> for CompletionItem {
118 type Output = ::lsp_types::CompletionItem;
120 fn conv_with(self, ctx: (&LineIndex, LineEndings, usize)) -> ::lsp_types::CompletionItem {
121 let mut additional_text_edits = Vec::new();
122 let mut text_edit = None;
123 // LSP does not allow arbitrary edits in completion, so we have to do a
124 // non-trivial mapping here.
125 for atom_edit in self.text_edit().as_atoms() {
126 if self.source_range().is_subrange(&atom_edit.delete) {
127 text_edit = Some(if atom_edit.delete == self.source_range() {
128 atom_edit.conv_with((ctx.0, ctx.1))
130 assert!(self.source_range().end() == atom_edit.delete.end());
132 TextRange::from_to(atom_edit.delete.start(), self.source_range().start());
133 let range2 = self.source_range();
134 let edit1 = AtomTextEdit::replace(range1, String::new());
135 let edit2 = AtomTextEdit::replace(range2, atom_edit.insert.clone());
136 additional_text_edits.push(edit1.conv_with((ctx.0, ctx.1)));
137 edit2.conv_with((ctx.0, ctx.1))
140 assert!(self.source_range().intersection(&atom_edit.delete).is_none());
141 additional_text_edits.push(atom_edit.conv_with((ctx.0, ctx.1)));
144 let text_edit = text_edit.unwrap();
146 let mut res = lsp_types::CompletionItem {
147 label: self.label().to_string(),
148 detail: self.detail().map(|it| it.to_string()),
149 filter_text: Some(self.lookup().to_string()),
150 kind: self.kind().map(|it| it.conv()),
151 text_edit: Some(text_edit),
152 additional_text_edits: Some(additional_text_edits),
153 documentation: self.documentation().map(|it| it.conv()),
154 deprecated: Some(self.deprecated()),
155 command: if self.trigger_call_info() {
156 let cmd = lsp_types::Command {
157 title: "triggerParameterHints".into(),
158 command: "editor.action.triggerParameterHints".into(),
168 if let Some(score) = self.score() {
170 CompletionScore::TypeAndNameMatch => res.preselect = Some(true),
171 CompletionScore::TypeMatch => {}
173 res.sort_text = Some(format!("{:02}", ctx.2));
176 if self.deprecated() {
177 res.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
180 res.insert_text_format = Some(match self.insert_text_format() {
181 InsertTextFormat::Snippet => lsp_types::InsertTextFormat::Snippet,
182 InsertTextFormat::PlainText => lsp_types::InsertTextFormat::PlainText,
189 impl ConvWith<&LineIndex> for Position {
190 type Output = TextUnit;
192 fn conv_with(self, line_index: &LineIndex) -> TextUnit {
193 let line_col = LineCol { line: self.line as u32, col_utf16: self.character as u32 };
194 line_index.offset(line_col)
198 impl ConvWith<&LineIndex> for TextUnit {
199 type Output = Position;
201 fn conv_with(self, line_index: &LineIndex) -> Position {
202 let line_col = line_index.line_col(self);
203 Position::new(u64::from(line_col.line), u64::from(line_col.col_utf16))
207 impl ConvWith<&LineIndex> for TextRange {
210 fn conv_with(self, line_index: &LineIndex) -> Range {
211 Range::new(self.start().conv_with(line_index), self.end().conv_with(line_index))
215 impl ConvWith<&LineIndex> for Range {
216 type Output = TextRange;
218 fn conv_with(self, line_index: &LineIndex) -> TextRange {
219 TextRange::from_to(self.start.conv_with(line_index), self.end.conv_with(line_index))
223 impl Conv for ra_ide::Documentation {
224 type Output = lsp_types::Documentation;
225 fn conv(self) -> Documentation {
226 Documentation::MarkupContent(MarkupContent {
227 kind: MarkupKind::Markdown,
228 value: crate::markdown::format_docs(self.as_str()),
233 impl ConvWith<bool> for ra_ide::FunctionSignature {
234 type Output = lsp_types::SignatureInformation;
235 fn conv_with(self, concise: bool) -> Self::Output {
236 let (label, documentation, params) = if concise {
237 let mut params = self.parameters;
238 if self.has_self_param {
241 (params.join(", "), None, params)
243 (self.to_string(), self.doc.map(|it| it.conv()), self.parameters)
246 let parameters: Vec<ParameterInformation> = params
248 .map(|param| ParameterInformation {
249 label: ParameterLabel::Simple(param),
254 SignatureInformation { label, documentation, parameters: Some(parameters) }
258 impl ConvWith<(&LineIndex, LineEndings)> for TextEdit {
259 type Output = Vec<lsp_types::TextEdit>;
261 fn conv_with(self, ctx: (&LineIndex, LineEndings)) -> Vec<lsp_types::TextEdit> {
262 self.as_atoms().iter().map_conv_with(ctx).collect()
266 impl ConvWith<(&LineIndex, LineEndings)> for &AtomTextEdit {
267 type Output = lsp_types::TextEdit;
271 (line_index, line_endings): (&LineIndex, LineEndings),
272 ) -> lsp_types::TextEdit {
273 let mut new_text = self.insert.clone();
274 if line_endings == LineEndings::Dos {
275 new_text = new_text.replace('\n', "\r\n");
277 lsp_types::TextEdit { range: self.delete.conv_with(line_index), new_text }
281 pub(crate) struct FoldConvCtx<'a> {
282 pub(crate) text: &'a str,
283 pub(crate) line_index: &'a LineIndex,
284 pub(crate) line_folding_only: bool,
287 impl ConvWith<&FoldConvCtx<'_>> for Fold {
288 type Output = lsp_types::FoldingRange;
290 fn conv_with(self, ctx: &FoldConvCtx) -> lsp_types::FoldingRange {
291 let kind = match self.kind {
292 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
293 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
294 FoldKind::Mods => None,
295 FoldKind::Block => None,
298 let range = self.range.conv_with(&ctx.line_index);
300 if ctx.line_folding_only {
301 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
302 // even if it contains text not in the folding range. To prevent that we exclude
303 // range.end.line from the folding region if there is more text after range.end
305 let has_more_text_on_end_line = ctx.text
306 [TextRange::from_to(self.range.end(), TextUnit::of_str(ctx.text))]
308 .take_while(|it| *it != '\n')
309 .any(|it| !it.is_whitespace());
311 let end_line = if has_more_text_on_end_line {
312 range.end.line.saturating_sub(1)
317 lsp_types::FoldingRange {
318 start_line: range.start.line,
319 start_character: None,
325 lsp_types::FoldingRange {
326 start_line: range.start.line,
327 start_character: Some(range.start.character),
328 end_line: range.end.line,
329 end_character: Some(range.end.character),
336 impl ConvWith<&LineIndex> for InlayHint {
337 type Output = req::InlayHint;
338 fn conv_with(self, line_index: &LineIndex) -> Self::Output {
340 label: self.label.to_string(),
341 range: self.range.conv_with(line_index),
342 kind: match self.kind {
343 InlayKind::ParameterHint => req::InlayKind::ParameterHint,
344 InlayKind::TypeHint => req::InlayKind::TypeHint,
345 InlayKind::ChainingHint => req::InlayKind::ChainingHint,
351 impl Conv for Highlight {
352 type Output = (u32, u32);
354 fn conv(self) -> Self::Output {
355 let mut mods = ModifierSet::default();
356 let type_ = match self.tag {
357 HighlightTag::Struct => SemanticTokenType::STRUCT,
358 HighlightTag::Enum => SemanticTokenType::ENUM,
359 HighlightTag::Union => UNION,
360 HighlightTag::TypeAlias => TYPE_ALIAS,
361 HighlightTag::Trait => SemanticTokenType::INTERFACE,
362 HighlightTag::BuiltinType => BUILTIN_TYPE,
363 HighlightTag::SelfType => SemanticTokenType::TYPE,
364 HighlightTag::Field => SemanticTokenType::MEMBER,
365 HighlightTag::Function => SemanticTokenType::FUNCTION,
366 HighlightTag::Module => SemanticTokenType::NAMESPACE,
367 HighlightTag::Constant => {
369 mods |= SemanticTokenModifier::STATIC;
370 SemanticTokenType::VARIABLE
372 HighlightTag::Static => {
373 mods |= SemanticTokenModifier::STATIC;
374 SemanticTokenType::VARIABLE
376 HighlightTag::EnumVariant => ENUM_MEMBER,
377 HighlightTag::Macro => SemanticTokenType::MACRO,
378 HighlightTag::Local => SemanticTokenType::VARIABLE,
379 HighlightTag::TypeParam => SemanticTokenType::TYPE_PARAMETER,
380 HighlightTag::Lifetime => LIFETIME,
381 HighlightTag::ByteLiteral | HighlightTag::NumericLiteral => SemanticTokenType::NUMBER,
382 HighlightTag::CharLiteral | HighlightTag::StringLiteral => SemanticTokenType::STRING,
383 HighlightTag::Comment => SemanticTokenType::COMMENT,
384 HighlightTag::Attribute => ATTRIBUTE,
385 HighlightTag::Keyword => SemanticTokenType::KEYWORD,
386 HighlightTag::UnresolvedReference => UNRESOLVED_REFERENCE,
389 for modifier in self.modifiers.iter() {
390 let modifier = match modifier {
391 HighlightModifier::Definition => SemanticTokenModifier::DECLARATION,
392 HighlightModifier::ControlFlow => CONTROL_FLOW,
393 HighlightModifier::Mutable => MUTABLE,
394 HighlightModifier::Unsafe => UNSAFE,
399 (semantic_tokens::type_index(type_), mods.0)
403 impl<T: ConvWith<CTX>, CTX> ConvWith<CTX> for Option<T> {
404 type Output = Option<T::Output>;
406 fn conv_with(self, ctx: CTX) -> Self::Output {
407 self.map(|x| ConvWith::conv_with(x, ctx))
411 impl TryConvWith<&WorldSnapshot> for &Url {
412 type Output = FileId;
413 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
414 world.uri_to_file_id(self)
418 impl TryConvWith<&WorldSnapshot> for FileId {
420 fn try_conv_with(self, world: &WorldSnapshot) -> Result<Url> {
421 world.file_id_to_uri(self)
425 impl TryConvWith<&WorldSnapshot> for &TextDocumentItem {
426 type Output = FileId;
427 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
428 self.uri.try_conv_with(world)
432 impl TryConvWith<&WorldSnapshot> for &VersionedTextDocumentIdentifier {
433 type Output = FileId;
434 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
435 self.uri.try_conv_with(world)
439 impl TryConvWith<&WorldSnapshot> for &TextDocumentIdentifier {
440 type Output = FileId;
441 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
442 world.uri_to_file_id(&self.uri)
446 impl TryConvWith<&WorldSnapshot> for &TextDocumentPositionParams {
447 type Output = FilePosition;
448 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FilePosition> {
449 let file_id = self.text_document.try_conv_with(world)?;
450 let line_index = world.analysis().file_line_index(file_id)?;
451 let offset = self.position.conv_with(&line_index);
452 Ok(FilePosition { file_id, offset })
456 impl TryConvWith<&WorldSnapshot> for (&TextDocumentIdentifier, Range) {
457 type Output = FileRange;
458 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileRange> {
459 let file_id = self.0.try_conv_with(world)?;
460 let line_index = world.analysis().file_line_index(file_id)?;
461 let range = self.1.conv_with(&line_index);
462 Ok(FileRange { file_id, range })
466 impl<T: TryConvWith<CTX>, CTX: Copy> TryConvWith<CTX> for Vec<T> {
467 type Output = Vec<<T as TryConvWith<CTX>>::Output>;
468 fn try_conv_with(self, ctx: CTX) -> Result<Self::Output> {
469 let mut res = Vec::with_capacity(self.len());
471 res.push(item.try_conv_with(ctx)?);
477 impl TryConvWith<&WorldSnapshot> for SourceChange {
478 type Output = req::SourceChange;
479 fn try_conv_with(self, world: &WorldSnapshot) -> Result<req::SourceChange> {
480 let cursor_position = match self.cursor_position {
483 let line_index = world.analysis().file_line_index(pos.file_id)?;
487 .find(|it| it.file_id == pos.file_id)
489 let line_col = match edit {
490 Some(edit) => translate_offset_with_edit(&*line_index, pos.offset, edit),
491 None => line_index.line_col(pos.offset),
494 Position::new(u64::from(line_col.line), u64::from(line_col.col_utf16));
495 Some(TextDocumentPositionParams {
496 text_document: TextDocumentIdentifier::new(pos.file_id.try_conv_with(world)?),
501 let mut document_changes: Vec<DocumentChangeOperation> = Vec::new();
502 for resource_op in self.file_system_edits.try_conv_with(world)? {
503 document_changes.push(DocumentChangeOperation::Op(resource_op));
505 for text_document_edit in self.source_file_edits.try_conv_with(world)? {
506 document_changes.push(DocumentChangeOperation::Edit(text_document_edit));
508 let workspace_edit = WorkspaceEdit {
510 document_changes: Some(DocumentChanges::Operations(document_changes)),
512 Ok(req::SourceChange { label: self.label, workspace_edit, cursor_position })
516 impl TryConvWith<&WorldSnapshot> for SourceFileEdit {
517 type Output = TextDocumentEdit;
518 fn try_conv_with(self, world: &WorldSnapshot) -> Result<TextDocumentEdit> {
519 let text_document = VersionedTextDocumentIdentifier {
520 uri: self.file_id.try_conv_with(world)?,
523 let line_index = world.analysis().file_line_index(self.file_id)?;
524 let line_endings = world.file_line_endings(self.file_id);
526 self.edit.as_atoms().iter().map_conv_with((&line_index, line_endings)).collect();
527 Ok(TextDocumentEdit { text_document, edits })
531 impl TryConvWith<&WorldSnapshot> for FileSystemEdit {
532 type Output = ResourceOp;
533 fn try_conv_with(self, world: &WorldSnapshot) -> Result<ResourceOp> {
534 let res = match self {
535 FileSystemEdit::CreateFile { source_root, path } => {
536 let uri = world.path_to_uri(source_root, &path)?;
537 ResourceOp::Create(CreateFile { uri, options: None })
539 FileSystemEdit::MoveFile { src, dst_source_root, dst_path } => {
540 let old_uri = world.file_id_to_uri(src)?;
541 let new_uri = world.path_to_uri(dst_source_root, &dst_path)?;
542 ResourceOp::Rename(RenameFile { old_uri, new_uri, options: None })
549 impl TryConvWith<&WorldSnapshot> for &NavigationTarget {
550 type Output = Location;
551 fn try_conv_with(self, world: &WorldSnapshot) -> Result<Location> {
552 let line_index = world.analysis().file_line_index(self.file_id())?;
553 let range = self.range();
554 to_location(self.file_id(), range, &world, &line_index)
558 impl TryConvWith<&WorldSnapshot> for (FileId, RangeInfo<NavigationTarget>) {
559 type Output = LocationLink;
560 fn try_conv_with(self, world: &WorldSnapshot) -> Result<LocationLink> {
561 let (src_file_id, target) = self;
563 let target_uri = target.info.file_id().try_conv_with(world)?;
564 let src_line_index = world.analysis().file_line_index(src_file_id)?;
565 let tgt_line_index = world.analysis().file_line_index(target.info.file_id())?;
567 let target_range = target.info.full_range().conv_with(&tgt_line_index);
569 let target_selection_range = target
572 .map(|it| it.conv_with(&tgt_line_index))
573 .unwrap_or(target_range);
575 let res = LocationLink {
576 origin_selection_range: Some(target.range.conv_with(&src_line_index)),
579 target_selection_range,
585 impl TryConvWith<&WorldSnapshot> for (FileId, RangeInfo<Vec<NavigationTarget>>) {
586 type Output = req::GotoDefinitionResponse;
587 fn try_conv_with(self, world: &WorldSnapshot) -> Result<req::GotoTypeDefinitionResponse> {
588 let (file_id, RangeInfo { range, info: navs }) = self;
591 .map(|nav| (file_id, RangeInfo::new(range, nav)))
592 .try_conv_with_to_vec(world)?;
593 if world.config.client_caps.location_link {
596 let locations: Vec<Location> = links
598 .map(|link| Location { uri: link.target_uri, range: link.target_selection_range })
605 pub fn to_call_hierarchy_item(
608 world: &WorldSnapshot,
609 line_index: &LineIndex,
610 nav: NavigationTarget,
611 ) -> Result<lsp_types::CallHierarchyItem> {
612 Ok(lsp_types::CallHierarchyItem {
613 name: nav.name().to_string(),
614 kind: nav.kind().conv(),
616 detail: nav.description().map(|it| it.to_string()),
617 uri: file_id.try_conv_with(&world)?,
618 range: nav.range().conv_with(&line_index),
619 selection_range: range.conv_with(&line_index),
626 world: &WorldSnapshot,
627 line_index: &LineIndex,
628 ) -> Result<Location> {
629 let url = file_id.try_conv_with(world)?;
630 let loc = Location::new(url, range.conv_with(line_index));
634 pub trait MapConvWith<CTX>: Sized {
637 fn map_conv_with(self, ctx: CTX) -> ConvWithIter<Self, CTX> {
638 ConvWithIter { iter: self, ctx }
642 impl<CTX, I> MapConvWith<CTX> for I
645 I::Item: ConvWith<CTX>,
647 type Output = <I::Item as ConvWith<CTX>>::Output;
650 pub struct ConvWithIter<I, CTX> {
655 impl<I, CTX> Iterator for ConvWithIter<I, CTX>
658 I::Item: ConvWith<CTX>,
661 type Item = <I::Item as ConvWith<CTX>>::Output;
663 fn next(&mut self) -> Option<Self::Item> {
664 self.iter.next().map(|item| item.conv_with(self.ctx))
668 pub trait TryConvWithToVec<CTX>: Sized {
671 fn try_conv_with_to_vec(self, ctx: CTX) -> Result<Vec<Self::Output>>;
674 impl<I, CTX> TryConvWithToVec<CTX> for I
677 I::Item: TryConvWith<CTX>,
680 type Output = <I::Item as TryConvWith<CTX>>::Output;
682 fn try_conv_with_to_vec(self, ctx: CTX) -> Result<Vec<Self::Output>> {
683 self.map(|it| it.try_conv_with(ctx)).collect()
690 use test_utils::extract_ranges;
693 fn conv_fold_line_folding_only_fixup() {
694 let text = r#"<fold>mod a;
701 }</fold> else <fold>{
706 let (ranges, text) = extract_ranges(text, "fold");
707 assert_eq!(ranges.len(), 4);
709 Fold { range: ranges[0], kind: FoldKind::Mods },
710 Fold { range: ranges[1], kind: FoldKind::Block },
711 Fold { range: ranges[2], kind: FoldKind::Block },
712 Fold { range: ranges[3], kind: FoldKind::Block },
715 let line_index = LineIndex::new(&text);
716 let ctx = FoldConvCtx { text: &text, line_index: &line_index, line_folding_only: true };
717 let converted: Vec<_> = folds.into_iter().map_conv_with(&ctx).collect();
719 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
720 assert_eq!(converted.len(), expected_lines.len());
721 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
722 assert_eq!(folding_range.start_line, *start_line);
723 assert_eq!(folding_range.start_character, None);
724 assert_eq!(folding_range.end_line, *end_line);
725 assert_eq!(folding_range.end_character, None);