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::{ATTRIBUTE, BUILTIN_TYPE, ENUM_MEMBER, LIFETIME, TYPE_ALIAS, UNION};
31 fn conv(self) -> Self::Output;
34 pub trait ConvWith<CTX> {
36 fn conv_with(self, ctx: CTX) -> Self::Output;
39 pub trait TryConvWith<CTX> {
41 fn try_conv_with(self, ctx: CTX) -> Result<Self::Output>;
44 impl Conv for SyntaxKind {
45 type Output = SymbolKind;
47 fn conv(self) -> <Self as Conv>::Output {
49 SyntaxKind::FN_DEF => SymbolKind::Function,
50 SyntaxKind::STRUCT_DEF => SymbolKind::Struct,
51 SyntaxKind::ENUM_DEF => SymbolKind::Enum,
52 SyntaxKind::ENUM_VARIANT => SymbolKind::EnumMember,
53 SyntaxKind::TRAIT_DEF => SymbolKind::Interface,
54 SyntaxKind::MACRO_CALL => SymbolKind::Function,
55 SyntaxKind::MODULE => SymbolKind::Module,
56 SyntaxKind::TYPE_ALIAS_DEF => SymbolKind::TypeParameter,
57 SyntaxKind::RECORD_FIELD_DEF => SymbolKind::Field,
58 SyntaxKind::STATIC_DEF => SymbolKind::Constant,
59 SyntaxKind::CONST_DEF => SymbolKind::Constant,
60 SyntaxKind::IMPL_DEF => SymbolKind::Object,
61 _ => SymbolKind::Variable,
66 impl Conv for ReferenceAccess {
67 type Output = ::lsp_types::DocumentHighlightKind;
69 fn conv(self) -> Self::Output {
70 use lsp_types::DocumentHighlightKind;
72 ReferenceAccess::Read => DocumentHighlightKind::Read,
73 ReferenceAccess::Write => DocumentHighlightKind::Write,
78 impl Conv for CompletionItemKind {
79 type Output = ::lsp_types::CompletionItemKind;
81 fn conv(self) -> <Self as Conv>::Output {
82 use lsp_types::CompletionItemKind::*;
84 CompletionItemKind::Keyword => Keyword,
85 CompletionItemKind::Snippet => Snippet,
86 CompletionItemKind::Module => Module,
87 CompletionItemKind::Function => Function,
88 CompletionItemKind::Struct => Struct,
89 CompletionItemKind::Enum => Enum,
90 CompletionItemKind::EnumVariant => EnumMember,
91 CompletionItemKind::BuiltinType => Struct,
92 CompletionItemKind::Binding => Variable,
93 CompletionItemKind::Field => Field,
94 CompletionItemKind::Trait => Interface,
95 CompletionItemKind::TypeAlias => Struct,
96 CompletionItemKind::Const => Constant,
97 CompletionItemKind::Static => Value,
98 CompletionItemKind::Method => Method,
99 CompletionItemKind::TypeParam => TypeParameter,
100 CompletionItemKind::Macro => Method,
105 impl Conv for Severity {
106 type Output = DiagnosticSeverity;
107 fn conv(self) -> DiagnosticSeverity {
109 Severity::Error => DiagnosticSeverity::Error,
110 Severity::WeakWarning => DiagnosticSeverity::Hint,
115 impl ConvWith<(&LineIndex, LineEndings, usize)> for CompletionItem {
116 type Output = ::lsp_types::CompletionItem;
118 fn conv_with(self, ctx: (&LineIndex, LineEndings, usize)) -> ::lsp_types::CompletionItem {
119 let mut additional_text_edits = Vec::new();
120 let mut text_edit = None;
121 // LSP does not allow arbitrary edits in completion, so we have to do a
122 // non-trivial mapping here.
123 for atom_edit in self.text_edit().as_atoms() {
124 if self.source_range().is_subrange(&atom_edit.delete) {
125 text_edit = Some(if atom_edit.delete == self.source_range() {
126 atom_edit.conv_with((ctx.0, ctx.1))
128 assert!(self.source_range().end() == atom_edit.delete.end());
130 TextRange::from_to(atom_edit.delete.start(), self.source_range().start());
131 let range2 = self.source_range();
132 let edit1 = AtomTextEdit::replace(range1, String::new());
133 let edit2 = AtomTextEdit::replace(range2, atom_edit.insert.clone());
134 additional_text_edits.push(edit1.conv_with((ctx.0, ctx.1)));
135 edit2.conv_with((ctx.0, ctx.1))
138 assert!(self.source_range().intersection(&atom_edit.delete).is_none());
139 additional_text_edits.push(atom_edit.conv_with((ctx.0, ctx.1)));
142 let text_edit = text_edit.unwrap();
144 let mut res = lsp_types::CompletionItem {
145 label: self.label().to_string(),
146 detail: self.detail().map(|it| it.to_string()),
147 filter_text: Some(self.lookup().to_string()),
148 kind: self.kind().map(|it| it.conv()),
149 text_edit: Some(text_edit),
150 additional_text_edits: Some(additional_text_edits),
151 documentation: self.documentation().map(|it| it.conv()),
152 deprecated: Some(self.deprecated()),
153 command: if self.trigger_call_info() {
154 let cmd = lsp_types::Command {
155 title: "triggerParameterHints".into(),
156 command: "editor.action.triggerParameterHints".into(),
166 if let Some(score) = self.score() {
168 CompletionScore::TypeAndNameMatch => res.preselect = Some(true),
169 CompletionScore::TypeMatch => {}
171 res.sort_text = Some(format!("{:02}", ctx.2));
174 if self.deprecated() {
175 res.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
178 res.insert_text_format = Some(match self.insert_text_format() {
179 InsertTextFormat::Snippet => lsp_types::InsertTextFormat::Snippet,
180 InsertTextFormat::PlainText => lsp_types::InsertTextFormat::PlainText,
187 impl ConvWith<&LineIndex> for Position {
188 type Output = TextUnit;
190 fn conv_with(self, line_index: &LineIndex) -> TextUnit {
191 let line_col = LineCol { line: self.line as u32, col_utf16: self.character as u32 };
192 line_index.offset(line_col)
196 impl ConvWith<&LineIndex> for TextUnit {
197 type Output = Position;
199 fn conv_with(self, line_index: &LineIndex) -> Position {
200 let line_col = line_index.line_col(self);
201 Position::new(u64::from(line_col.line), u64::from(line_col.col_utf16))
205 impl ConvWith<&LineIndex> for TextRange {
208 fn conv_with(self, line_index: &LineIndex) -> Range {
209 Range::new(self.start().conv_with(line_index), self.end().conv_with(line_index))
213 impl ConvWith<&LineIndex> for Range {
214 type Output = TextRange;
216 fn conv_with(self, line_index: &LineIndex) -> TextRange {
217 TextRange::from_to(self.start.conv_with(line_index), self.end.conv_with(line_index))
221 impl Conv for ra_ide::Documentation {
222 type Output = lsp_types::Documentation;
223 fn conv(self) -> Documentation {
224 Documentation::MarkupContent(MarkupContent {
225 kind: MarkupKind::Markdown,
226 value: crate::markdown::format_docs(self.as_str()),
231 impl ConvWith<bool> for ra_ide::FunctionSignature {
232 type Output = lsp_types::SignatureInformation;
233 fn conv_with(self, concise: bool) -> Self::Output {
234 let (label, documentation, params) = if concise {
235 let mut params = self.parameters;
236 if self.has_self_param {
239 (params.join(", "), None, params)
241 (self.to_string(), self.doc.map(|it| it.conv()), self.parameters)
244 let parameters: Vec<ParameterInformation> = params
246 .map(|param| ParameterInformation {
247 label: ParameterLabel::Simple(param),
252 SignatureInformation { label, documentation, parameters: Some(parameters) }
256 impl ConvWith<(&LineIndex, LineEndings)> for TextEdit {
257 type Output = Vec<lsp_types::TextEdit>;
259 fn conv_with(self, ctx: (&LineIndex, LineEndings)) -> Vec<lsp_types::TextEdit> {
260 self.as_atoms().iter().map_conv_with(ctx).collect()
264 impl ConvWith<(&LineIndex, LineEndings)> for &AtomTextEdit {
265 type Output = lsp_types::TextEdit;
269 (line_index, line_endings): (&LineIndex, LineEndings),
270 ) -> lsp_types::TextEdit {
271 let mut new_text = self.insert.clone();
272 if line_endings == LineEndings::Dos {
273 new_text = new_text.replace('\n', "\r\n");
275 lsp_types::TextEdit { range: self.delete.conv_with(line_index), new_text }
279 pub(crate) struct FoldConvCtx<'a> {
280 pub(crate) text: &'a str,
281 pub(crate) line_index: &'a LineIndex,
282 pub(crate) line_folding_only: bool,
285 impl ConvWith<&FoldConvCtx<'_>> for Fold {
286 type Output = lsp_types::FoldingRange;
288 fn conv_with(self, ctx: &FoldConvCtx) -> lsp_types::FoldingRange {
289 let kind = match self.kind {
290 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
291 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
292 FoldKind::Mods => None,
293 FoldKind::Block => None,
296 let range = self.range.conv_with(&ctx.line_index);
298 if ctx.line_folding_only {
299 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
300 // even if it contains text not in the folding range. To prevent that we exclude
301 // range.end.line from the folding region if there is more text after range.end
303 let has_more_text_on_end_line = ctx.text
304 [TextRange::from_to(self.range.end(), TextUnit::of_str(ctx.text))]
306 .take_while(|it| *it != '\n')
307 .any(|it| !it.is_whitespace());
309 let end_line = if has_more_text_on_end_line {
310 range.end.line.saturating_sub(1)
315 lsp_types::FoldingRange {
316 start_line: range.start.line,
317 start_character: None,
323 lsp_types::FoldingRange {
324 start_line: range.start.line,
325 start_character: Some(range.start.character),
326 end_line: range.end.line,
327 end_character: Some(range.end.character),
334 impl ConvWith<&LineIndex> for InlayHint {
335 type Output = req::InlayHint;
336 fn conv_with(self, line_index: &LineIndex) -> Self::Output {
338 label: self.label.to_string(),
339 range: self.range.conv_with(line_index),
340 kind: match self.kind {
341 InlayKind::ParameterHint => req::InlayKind::ParameterHint,
342 InlayKind::TypeHint => req::InlayKind::TypeHint,
343 InlayKind::ChainingHint => req::InlayKind::ChainingHint,
349 impl Conv for Highlight {
350 type Output = (u32, u32);
352 fn conv(self) -> Self::Output {
353 let mut mods = ModifierSet::default();
354 let type_ = match self.tag {
355 HighlightTag::Struct => SemanticTokenType::STRUCT,
356 HighlightTag::Enum => SemanticTokenType::ENUM,
357 HighlightTag::Union => UNION,
358 HighlightTag::TypeAlias => TYPE_ALIAS,
359 HighlightTag::Trait => SemanticTokenType::INTERFACE,
360 HighlightTag::BuiltinType => BUILTIN_TYPE,
361 HighlightTag::SelfType => SemanticTokenType::TYPE,
362 HighlightTag::Field => SemanticTokenType::MEMBER,
363 HighlightTag::Function => SemanticTokenType::FUNCTION,
364 HighlightTag::Module => SemanticTokenType::NAMESPACE,
365 HighlightTag::Constant => {
367 mods |= SemanticTokenModifier::STATIC;
368 SemanticTokenType::VARIABLE
370 HighlightTag::Static => {
371 mods |= SemanticTokenModifier::STATIC;
372 SemanticTokenType::VARIABLE
374 HighlightTag::EnumVariant => ENUM_MEMBER,
375 HighlightTag::Macro => SemanticTokenType::MACRO,
376 HighlightTag::Local => SemanticTokenType::VARIABLE,
377 HighlightTag::TypeParam => SemanticTokenType::TYPE_PARAMETER,
378 HighlightTag::Lifetime => LIFETIME,
379 HighlightTag::ByteLiteral | HighlightTag::NumericLiteral => SemanticTokenType::NUMBER,
380 HighlightTag::CharLiteral | HighlightTag::StringLiteral => SemanticTokenType::STRING,
381 HighlightTag::Comment => SemanticTokenType::COMMENT,
382 HighlightTag::Attribute => ATTRIBUTE,
383 HighlightTag::Keyword => SemanticTokenType::KEYWORD,
386 for modifier in self.modifiers.iter() {
387 let modifier = match modifier {
388 HighlightModifier::Definition => SemanticTokenModifier::DECLARATION,
389 HighlightModifier::ControlFlow => CONTROL_FLOW,
390 HighlightModifier::Mutable => MUTABLE,
391 HighlightModifier::Unsafe => UNSAFE,
396 (semantic_tokens::type_index(type_), mods.0)
400 impl<T: ConvWith<CTX>, CTX> ConvWith<CTX> for Option<T> {
401 type Output = Option<T::Output>;
403 fn conv_with(self, ctx: CTX) -> Self::Output {
404 self.map(|x| ConvWith::conv_with(x, ctx))
408 impl TryConvWith<&WorldSnapshot> for &Url {
409 type Output = FileId;
410 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
411 world.uri_to_file_id(self)
415 impl TryConvWith<&WorldSnapshot> for FileId {
417 fn try_conv_with(self, world: &WorldSnapshot) -> Result<Url> {
418 world.file_id_to_uri(self)
422 impl TryConvWith<&WorldSnapshot> for &TextDocumentItem {
423 type Output = FileId;
424 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
425 self.uri.try_conv_with(world)
429 impl TryConvWith<&WorldSnapshot> for &VersionedTextDocumentIdentifier {
430 type Output = FileId;
431 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
432 self.uri.try_conv_with(world)
436 impl TryConvWith<&WorldSnapshot> for &TextDocumentIdentifier {
437 type Output = FileId;
438 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
439 world.uri_to_file_id(&self.uri)
443 impl TryConvWith<&WorldSnapshot> for &TextDocumentPositionParams {
444 type Output = FilePosition;
445 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FilePosition> {
446 let file_id = self.text_document.try_conv_with(world)?;
447 let line_index = world.analysis().file_line_index(file_id)?;
448 let offset = self.position.conv_with(&line_index);
449 Ok(FilePosition { file_id, offset })
453 impl TryConvWith<&WorldSnapshot> for (&TextDocumentIdentifier, Range) {
454 type Output = FileRange;
455 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileRange> {
456 let file_id = self.0.try_conv_with(world)?;
457 let line_index = world.analysis().file_line_index(file_id)?;
458 let range = self.1.conv_with(&line_index);
459 Ok(FileRange { file_id, range })
463 impl<T: TryConvWith<CTX>, CTX: Copy> TryConvWith<CTX> for Vec<T> {
464 type Output = Vec<<T as TryConvWith<CTX>>::Output>;
465 fn try_conv_with(self, ctx: CTX) -> Result<Self::Output> {
466 let mut res = Vec::with_capacity(self.len());
468 res.push(item.try_conv_with(ctx)?);
474 impl TryConvWith<&WorldSnapshot> for SourceChange {
475 type Output = req::SourceChange;
476 fn try_conv_with(self, world: &WorldSnapshot) -> Result<req::SourceChange> {
477 let cursor_position = match self.cursor_position {
480 let line_index = world.analysis().file_line_index(pos.file_id)?;
484 .find(|it| it.file_id == pos.file_id)
486 let line_col = match edit {
487 Some(edit) => translate_offset_with_edit(&*line_index, pos.offset, edit),
488 None => line_index.line_col(pos.offset),
491 Position::new(u64::from(line_col.line), u64::from(line_col.col_utf16));
492 Some(TextDocumentPositionParams {
493 text_document: TextDocumentIdentifier::new(pos.file_id.try_conv_with(world)?),
498 let mut document_changes: Vec<DocumentChangeOperation> = Vec::new();
499 for resource_op in self.file_system_edits.try_conv_with(world)? {
500 document_changes.push(DocumentChangeOperation::Op(resource_op));
502 for text_document_edit in self.source_file_edits.try_conv_with(world)? {
503 document_changes.push(DocumentChangeOperation::Edit(text_document_edit));
505 let workspace_edit = WorkspaceEdit {
507 document_changes: Some(DocumentChanges::Operations(document_changes)),
509 Ok(req::SourceChange { label: self.label, workspace_edit, cursor_position })
513 impl TryConvWith<&WorldSnapshot> for SourceFileEdit {
514 type Output = TextDocumentEdit;
515 fn try_conv_with(self, world: &WorldSnapshot) -> Result<TextDocumentEdit> {
516 let text_document = VersionedTextDocumentIdentifier {
517 uri: self.file_id.try_conv_with(world)?,
520 let line_index = world.analysis().file_line_index(self.file_id)?;
521 let line_endings = world.file_line_endings(self.file_id);
523 self.edit.as_atoms().iter().map_conv_with((&line_index, line_endings)).collect();
524 Ok(TextDocumentEdit { text_document, edits })
528 impl TryConvWith<&WorldSnapshot> for FileSystemEdit {
529 type Output = ResourceOp;
530 fn try_conv_with(self, world: &WorldSnapshot) -> Result<ResourceOp> {
531 let res = match self {
532 FileSystemEdit::CreateFile { source_root, path } => {
533 let uri = world.path_to_uri(source_root, &path)?;
534 ResourceOp::Create(CreateFile { uri, options: None })
536 FileSystemEdit::MoveFile { src, dst_source_root, dst_path } => {
537 let old_uri = world.file_id_to_uri(src)?;
538 let new_uri = world.path_to_uri(dst_source_root, &dst_path)?;
539 ResourceOp::Rename(RenameFile { old_uri, new_uri, options: None })
546 impl TryConvWith<&WorldSnapshot> for &NavigationTarget {
547 type Output = Location;
548 fn try_conv_with(self, world: &WorldSnapshot) -> Result<Location> {
549 let line_index = world.analysis().file_line_index(self.file_id())?;
550 let range = self.range();
551 to_location(self.file_id(), range, &world, &line_index)
555 impl TryConvWith<&WorldSnapshot> for (FileId, RangeInfo<NavigationTarget>) {
556 type Output = LocationLink;
557 fn try_conv_with(self, world: &WorldSnapshot) -> Result<LocationLink> {
558 let (src_file_id, target) = self;
560 let target_uri = target.info.file_id().try_conv_with(world)?;
561 let src_line_index = world.analysis().file_line_index(src_file_id)?;
562 let tgt_line_index = world.analysis().file_line_index(target.info.file_id())?;
564 let target_range = target.info.full_range().conv_with(&tgt_line_index);
566 let target_selection_range = target
569 .map(|it| it.conv_with(&tgt_line_index))
570 .unwrap_or(target_range);
572 let res = LocationLink {
573 origin_selection_range: Some(target.range.conv_with(&src_line_index)),
576 target_selection_range,
582 impl TryConvWith<&WorldSnapshot> for (FileId, RangeInfo<Vec<NavigationTarget>>) {
583 type Output = req::GotoDefinitionResponse;
584 fn try_conv_with(self, world: &WorldSnapshot) -> Result<req::GotoTypeDefinitionResponse> {
585 let (file_id, RangeInfo { range, info: navs }) = self;
588 .map(|nav| (file_id, RangeInfo::new(range, nav)))
589 .try_conv_with_to_vec(world)?;
590 if world.config.client_caps.location_link {
593 let locations: Vec<Location> = links
595 .map(|link| Location { uri: link.target_uri, range: link.target_selection_range })
602 pub fn to_call_hierarchy_item(
605 world: &WorldSnapshot,
606 line_index: &LineIndex,
607 nav: NavigationTarget,
608 ) -> Result<lsp_types::CallHierarchyItem> {
609 Ok(lsp_types::CallHierarchyItem {
610 name: nav.name().to_string(),
611 kind: nav.kind().conv(),
613 detail: nav.description().map(|it| it.to_string()),
614 uri: file_id.try_conv_with(&world)?,
615 range: nav.range().conv_with(&line_index),
616 selection_range: range.conv_with(&line_index),
623 world: &WorldSnapshot,
624 line_index: &LineIndex,
625 ) -> Result<Location> {
626 let url = file_id.try_conv_with(world)?;
627 let loc = Location::new(url, range.conv_with(line_index));
631 pub trait MapConvWith<CTX>: Sized {
634 fn map_conv_with(self, ctx: CTX) -> ConvWithIter<Self, CTX> {
635 ConvWithIter { iter: self, ctx }
639 impl<CTX, I> MapConvWith<CTX> for I
642 I::Item: ConvWith<CTX>,
644 type Output = <I::Item as ConvWith<CTX>>::Output;
647 pub struct ConvWithIter<I, CTX> {
652 impl<I, CTX> Iterator for ConvWithIter<I, CTX>
655 I::Item: ConvWith<CTX>,
658 type Item = <I::Item as ConvWith<CTX>>::Output;
660 fn next(&mut self) -> Option<Self::Item> {
661 self.iter.next().map(|item| item.conv_with(self.ctx))
665 pub trait TryConvWithToVec<CTX>: Sized {
668 fn try_conv_with_to_vec(self, ctx: CTX) -> Result<Vec<Self::Output>>;
671 impl<I, CTX> TryConvWithToVec<CTX> for I
674 I::Item: TryConvWith<CTX>,
677 type Output = <I::Item as TryConvWith<CTX>>::Output;
679 fn try_conv_with_to_vec(self, ctx: CTX) -> Result<Vec<Self::Output>> {
680 self.map(|it| it.try_conv_with(ctx)).collect()
687 use test_utils::extract_ranges;
690 fn conv_fold_line_folding_only_fixup() {
691 let text = r#"<fold>mod a;
698 }</fold> else <fold>{
703 let (ranges, text) = extract_ranges(text, "fold");
704 assert_eq!(ranges.len(), 4);
706 Fold { range: ranges[0], kind: FoldKind::Mods },
707 Fold { range: ranges[1], kind: FoldKind::Block },
708 Fold { range: ranges[2], kind: FoldKind::Block },
709 Fold { range: ranges[3], kind: FoldKind::Block },
712 let line_index = LineIndex::new(&text);
713 let ctx = FoldConvCtx { text: &text, line_index: &line_index, line_folding_only: true };
714 let converted: Vec<_> = folds.into_iter().map_conv_with(&ctx).collect();
716 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
717 assert_eq!(converted.len(), expected_lines.len());
718 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
719 assert_eq!(folding_range.start_line, *start_line);
720 assert_eq!(folding_range.start_character, None);
721 assert_eq!(folding_range.end_line, *end_line);
722 assert_eq!(folding_range.end_character, None);