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, FileId, FilePosition,
13 FileRange, FileSystemEdit, Fold, FoldKind, Highlight, HighlightModifier, HighlightTag,
14 InlayHint, InlayKind, InsertTextFormat, LineCol, LineIndex, NavigationTarget, RangeInfo,
15 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)> for CompletionItem {
118 type Output = ::lsp_types::CompletionItem;
120 fn conv_with(self, ctx: (&LineIndex, LineEndings)) -> ::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 self.score().is_some() {
169 res.preselect = Some(true)
172 if self.deprecated() {
173 res.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
176 res.insert_text_format = Some(match self.insert_text_format() {
177 InsertTextFormat::Snippet => lsp_types::InsertTextFormat::Snippet,
178 InsertTextFormat::PlainText => lsp_types::InsertTextFormat::PlainText,
185 impl ConvWith<&LineIndex> for Position {
186 type Output = TextUnit;
188 fn conv_with(self, line_index: &LineIndex) -> TextUnit {
189 let line_col = LineCol { line: self.line as u32, col_utf16: self.character as u32 };
190 line_index.offset(line_col)
194 impl ConvWith<&LineIndex> for TextUnit {
195 type Output = Position;
197 fn conv_with(self, line_index: &LineIndex) -> Position {
198 let line_col = line_index.line_col(self);
199 Position::new(u64::from(line_col.line), u64::from(line_col.col_utf16))
203 impl ConvWith<&LineIndex> for TextRange {
206 fn conv_with(self, line_index: &LineIndex) -> Range {
207 Range::new(self.start().conv_with(line_index), self.end().conv_with(line_index))
211 impl ConvWith<&LineIndex> for Range {
212 type Output = TextRange;
214 fn conv_with(self, line_index: &LineIndex) -> TextRange {
215 TextRange::from_to(self.start.conv_with(line_index), self.end.conv_with(line_index))
219 impl Conv for ra_ide::Documentation {
220 type Output = lsp_types::Documentation;
221 fn conv(self) -> Documentation {
222 Documentation::MarkupContent(MarkupContent {
223 kind: MarkupKind::Markdown,
224 value: crate::markdown::format_docs(self.as_str()),
229 impl ConvWith<bool> for ra_ide::FunctionSignature {
230 type Output = lsp_types::SignatureInformation;
231 fn conv_with(self, concise: bool) -> Self::Output {
232 let (label, documentation, params) = if concise {
233 let mut params = self.parameters;
234 if self.has_self_param {
237 (params.join(", "), None, params)
239 (self.to_string(), self.doc.map(|it| it.conv()), self.parameters)
242 let parameters: Vec<ParameterInformation> = params
244 .map(|param| ParameterInformation {
245 label: ParameterLabel::Simple(param),
250 SignatureInformation { label, documentation, parameters: Some(parameters) }
254 impl ConvWith<(&LineIndex, LineEndings)> for TextEdit {
255 type Output = Vec<lsp_types::TextEdit>;
257 fn conv_with(self, ctx: (&LineIndex, LineEndings)) -> Vec<lsp_types::TextEdit> {
258 self.as_atoms().iter().map_conv_with(ctx).collect()
262 impl ConvWith<(&LineIndex, LineEndings)> for &AtomTextEdit {
263 type Output = lsp_types::TextEdit;
267 (line_index, line_endings): (&LineIndex, LineEndings),
268 ) -> lsp_types::TextEdit {
269 let mut new_text = self.insert.clone();
270 if line_endings == LineEndings::Dos {
271 new_text = new_text.replace('\n', "\r\n");
273 lsp_types::TextEdit { range: self.delete.conv_with(line_index), new_text }
277 pub(crate) struct FoldConvCtx<'a> {
278 pub(crate) text: &'a str,
279 pub(crate) line_index: &'a LineIndex,
280 pub(crate) line_folding_only: bool,
283 impl ConvWith<&FoldConvCtx<'_>> for Fold {
284 type Output = lsp_types::FoldingRange;
286 fn conv_with(self, ctx: &FoldConvCtx) -> lsp_types::FoldingRange {
287 let kind = match self.kind {
288 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
289 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
290 FoldKind::Mods => None,
291 FoldKind::Block => None,
294 let range = self.range.conv_with(&ctx.line_index);
296 if ctx.line_folding_only {
297 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
298 // even if it contains text not in the folding range. To prevent that we exclude
299 // range.end.line from the folding region if there is more text after range.end
301 let has_more_text_on_end_line = ctx.text
302 [TextRange::from_to(self.range.end(), TextUnit::of_str(ctx.text))]
304 .take_while(|it| *it != '\n')
305 .any(|it| !it.is_whitespace());
307 let end_line = if has_more_text_on_end_line {
308 range.end.line.saturating_sub(1)
313 lsp_types::FoldingRange {
314 start_line: range.start.line,
315 start_character: None,
321 lsp_types::FoldingRange {
322 start_line: range.start.line,
323 start_character: Some(range.start.character),
324 end_line: range.end.line,
325 end_character: Some(range.end.character),
332 impl ConvWith<&LineIndex> for InlayHint {
333 type Output = req::InlayHint;
334 fn conv_with(self, line_index: &LineIndex) -> Self::Output {
336 label: self.label.to_string(),
337 range: self.range.conv_with(line_index),
338 kind: match self.kind {
339 InlayKind::ParameterHint => req::InlayKind::ParameterHint,
340 InlayKind::TypeHint => req::InlayKind::TypeHint,
341 InlayKind::ChainingHint => req::InlayKind::ChainingHint,
347 impl Conv for Highlight {
348 type Output = (u32, u32);
350 fn conv(self) -> Self::Output {
351 let mut mods = ModifierSet::default();
352 let type_ = match self.tag {
353 HighlightTag::Struct => SemanticTokenType::STRUCT,
354 HighlightTag::Enum => SemanticTokenType::ENUM,
355 HighlightTag::Union => UNION,
356 HighlightTag::TypeAlias => TYPE_ALIAS,
357 HighlightTag::Trait => SemanticTokenType::INTERFACE,
358 HighlightTag::BuiltinType => BUILTIN_TYPE,
359 HighlightTag::SelfType => SemanticTokenType::TYPE,
360 HighlightTag::Field => SemanticTokenType::MEMBER,
361 HighlightTag::Function => SemanticTokenType::FUNCTION,
362 HighlightTag::Module => SemanticTokenType::NAMESPACE,
363 HighlightTag::Constant => {
365 mods |= SemanticTokenModifier::STATIC;
366 SemanticTokenType::VARIABLE
368 HighlightTag::Static => {
369 mods |= SemanticTokenModifier::STATIC;
370 SemanticTokenType::VARIABLE
372 HighlightTag::EnumVariant => ENUM_MEMBER,
373 HighlightTag::Macro => SemanticTokenType::MACRO,
374 HighlightTag::Local => SemanticTokenType::VARIABLE,
375 HighlightTag::TypeParam => SemanticTokenType::TYPE_PARAMETER,
376 HighlightTag::Lifetime => LIFETIME,
377 HighlightTag::ByteLiteral | HighlightTag::NumericLiteral => SemanticTokenType::NUMBER,
378 HighlightTag::CharLiteral | HighlightTag::StringLiteral => SemanticTokenType::STRING,
379 HighlightTag::Comment => SemanticTokenType::COMMENT,
380 HighlightTag::Attribute => ATTRIBUTE,
381 HighlightTag::Keyword => SemanticTokenType::KEYWORD,
382 HighlightTag::UnresolvedReference => UNRESOLVED_REFERENCE,
385 for modifier in self.modifiers.iter() {
386 let modifier = match modifier {
387 HighlightModifier::Definition => SemanticTokenModifier::DECLARATION,
388 HighlightModifier::ControlFlow => CONTROL_FLOW,
389 HighlightModifier::Mutable => MUTABLE,
390 HighlightModifier::Unsafe => UNSAFE,
395 (semantic_tokens::type_index(type_), mods.0)
399 impl<T: ConvWith<CTX>, CTX> ConvWith<CTX> for Option<T> {
400 type Output = Option<T::Output>;
402 fn conv_with(self, ctx: CTX) -> Self::Output {
403 self.map(|x| ConvWith::conv_with(x, ctx))
407 impl TryConvWith<&WorldSnapshot> for &Url {
408 type Output = FileId;
409 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
410 world.uri_to_file_id(self)
414 impl TryConvWith<&WorldSnapshot> for FileId {
416 fn try_conv_with(self, world: &WorldSnapshot) -> Result<Url> {
417 world.file_id_to_uri(self)
421 impl TryConvWith<&WorldSnapshot> for &TextDocumentItem {
422 type Output = FileId;
423 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
424 self.uri.try_conv_with(world)
428 impl TryConvWith<&WorldSnapshot> for &VersionedTextDocumentIdentifier {
429 type Output = FileId;
430 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
431 self.uri.try_conv_with(world)
435 impl TryConvWith<&WorldSnapshot> for &TextDocumentIdentifier {
436 type Output = FileId;
437 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
438 world.uri_to_file_id(&self.uri)
442 impl TryConvWith<&WorldSnapshot> for &TextDocumentPositionParams {
443 type Output = FilePosition;
444 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FilePosition> {
445 let file_id = self.text_document.try_conv_with(world)?;
446 let line_index = world.analysis().file_line_index(file_id)?;
447 let offset = self.position.conv_with(&line_index);
448 Ok(FilePosition { file_id, offset })
452 impl TryConvWith<&WorldSnapshot> for (&TextDocumentIdentifier, Range) {
453 type Output = FileRange;
454 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileRange> {
455 let file_id = self.0.try_conv_with(world)?;
456 let line_index = world.analysis().file_line_index(file_id)?;
457 let range = self.1.conv_with(&line_index);
458 Ok(FileRange { file_id, range })
462 impl<T: TryConvWith<CTX>, CTX: Copy> TryConvWith<CTX> for Vec<T> {
463 type Output = Vec<<T as TryConvWith<CTX>>::Output>;
464 fn try_conv_with(self, ctx: CTX) -> Result<Self::Output> {
465 let mut res = Vec::with_capacity(self.len());
467 res.push(item.try_conv_with(ctx)?);
473 impl TryConvWith<&WorldSnapshot> for SourceChange {
474 type Output = req::SourceChange;
475 fn try_conv_with(self, world: &WorldSnapshot) -> Result<req::SourceChange> {
476 let cursor_position = match self.cursor_position {
479 let line_index = world.analysis().file_line_index(pos.file_id)?;
483 .find(|it| it.file_id == pos.file_id)
485 let line_col = match edit {
486 Some(edit) => translate_offset_with_edit(&*line_index, pos.offset, edit),
487 None => line_index.line_col(pos.offset),
490 Position::new(u64::from(line_col.line), u64::from(line_col.col_utf16));
491 Some(TextDocumentPositionParams {
492 text_document: TextDocumentIdentifier::new(pos.file_id.try_conv_with(world)?),
497 let mut document_changes: Vec<DocumentChangeOperation> = Vec::new();
498 for resource_op in self.file_system_edits.try_conv_with(world)? {
499 document_changes.push(DocumentChangeOperation::Op(resource_op));
501 for text_document_edit in self.source_file_edits.try_conv_with(world)? {
502 document_changes.push(DocumentChangeOperation::Edit(text_document_edit));
504 let workspace_edit = WorkspaceEdit {
506 document_changes: Some(DocumentChanges::Operations(document_changes)),
508 Ok(req::SourceChange { label: self.label, workspace_edit, cursor_position })
512 impl TryConvWith<&WorldSnapshot> for SourceFileEdit {
513 type Output = TextDocumentEdit;
514 fn try_conv_with(self, world: &WorldSnapshot) -> Result<TextDocumentEdit> {
515 let text_document = VersionedTextDocumentIdentifier {
516 uri: self.file_id.try_conv_with(world)?,
519 let line_index = world.analysis().file_line_index(self.file_id)?;
520 let line_endings = world.file_line_endings(self.file_id);
522 self.edit.as_atoms().iter().map_conv_with((&line_index, line_endings)).collect();
523 Ok(TextDocumentEdit { text_document, edits })
527 impl TryConvWith<&WorldSnapshot> for FileSystemEdit {
528 type Output = ResourceOp;
529 fn try_conv_with(self, world: &WorldSnapshot) -> Result<ResourceOp> {
530 let res = match self {
531 FileSystemEdit::CreateFile { source_root, path } => {
532 let uri = world.path_to_uri(source_root, &path)?;
533 ResourceOp::Create(CreateFile { uri, options: None })
535 FileSystemEdit::MoveFile { src, dst_source_root, dst_path } => {
536 let old_uri = world.file_id_to_uri(src)?;
537 let new_uri = world.path_to_uri(dst_source_root, &dst_path)?;
538 ResourceOp::Rename(RenameFile { old_uri, new_uri, options: None })
545 impl TryConvWith<&WorldSnapshot> for &NavigationTarget {
546 type Output = Location;
547 fn try_conv_with(self, world: &WorldSnapshot) -> Result<Location> {
548 let line_index = world.analysis().file_line_index(self.file_id())?;
549 let range = self.range();
550 to_location(self.file_id(), range, &world, &line_index)
554 impl TryConvWith<&WorldSnapshot> for (FileId, RangeInfo<NavigationTarget>) {
555 type Output = LocationLink;
556 fn try_conv_with(self, world: &WorldSnapshot) -> Result<LocationLink> {
557 let (src_file_id, target) = self;
559 let target_uri = target.info.file_id().try_conv_with(world)?;
560 let src_line_index = world.analysis().file_line_index(src_file_id)?;
561 let tgt_line_index = world.analysis().file_line_index(target.info.file_id())?;
563 let target_range = target.info.full_range().conv_with(&tgt_line_index);
565 let target_selection_range = target
568 .map(|it| it.conv_with(&tgt_line_index))
569 .unwrap_or(target_range);
571 let res = LocationLink {
572 origin_selection_range: Some(target.range.conv_with(&src_line_index)),
575 target_selection_range,
581 impl TryConvWith<&WorldSnapshot> for (FileId, RangeInfo<Vec<NavigationTarget>>) {
582 type Output = req::GotoDefinitionResponse;
583 fn try_conv_with(self, world: &WorldSnapshot) -> Result<req::GotoTypeDefinitionResponse> {
584 let (file_id, RangeInfo { range, info: navs }) = self;
587 .map(|nav| (file_id, RangeInfo::new(range, nav)))
588 .try_conv_with_to_vec(world)?;
589 if world.config.client_caps.location_link {
592 let locations: Vec<Location> = links
594 .map(|link| Location { uri: link.target_uri, range: link.target_selection_range })
601 pub fn to_call_hierarchy_item(
604 world: &WorldSnapshot,
605 line_index: &LineIndex,
606 nav: NavigationTarget,
607 ) -> Result<lsp_types::CallHierarchyItem> {
608 Ok(lsp_types::CallHierarchyItem {
609 name: nav.name().to_string(),
610 kind: nav.kind().conv(),
612 detail: nav.description().map(|it| it.to_string()),
613 uri: file_id.try_conv_with(&world)?,
614 range: nav.range().conv_with(&line_index),
615 selection_range: range.conv_with(&line_index),
622 world: &WorldSnapshot,
623 line_index: &LineIndex,
624 ) -> Result<Location> {
625 let url = file_id.try_conv_with(world)?;
626 let loc = Location::new(url, range.conv_with(line_index));
630 pub trait MapConvWith<CTX>: Sized {
633 fn map_conv_with(self, ctx: CTX) -> ConvWithIter<Self, CTX> {
634 ConvWithIter { iter: self, ctx }
638 impl<CTX, I> MapConvWith<CTX> for I
641 I::Item: ConvWith<CTX>,
643 type Output = <I::Item as ConvWith<CTX>>::Output;
646 pub struct ConvWithIter<I, CTX> {
651 impl<I, CTX> Iterator for ConvWithIter<I, CTX>
654 I::Item: ConvWith<CTX>,
657 type Item = <I::Item as ConvWith<CTX>>::Output;
659 fn next(&mut self) -> Option<Self::Item> {
660 self.iter.next().map(|item| item.conv_with(self.ctx))
664 pub trait TryConvWithToVec<CTX>: Sized {
667 fn try_conv_with_to_vec(self, ctx: CTX) -> Result<Vec<Self::Output>>;
670 impl<I, CTX> TryConvWithToVec<CTX> for I
673 I::Item: TryConvWith<CTX>,
676 type Output = <I::Item as TryConvWith<CTX>>::Output;
678 fn try_conv_with_to_vec(self, ctx: CTX) -> Result<Vec<Self::Output>> {
679 self.map(|it| it.try_conv_with(ctx)).collect()
686 use test_utils::extract_ranges;
689 fn conv_fold_line_folding_only_fixup() {
690 let text = r#"<fold>mod a;
697 }</fold> else <fold>{
702 let (ranges, text) = extract_ranges(text, "fold");
703 assert_eq!(ranges.len(), 4);
705 Fold { range: ranges[0], kind: FoldKind::Mods },
706 Fold { range: ranges[1], kind: FoldKind::Block },
707 Fold { range: ranges[2], kind: FoldKind::Block },
708 Fold { range: ranges[3], kind: FoldKind::Block },
711 let line_index = LineIndex::new(&text);
712 let ctx = FoldConvCtx { text: &text, line_index: &line_index, line_folding_only: true };
713 let converted: Vec<_> = folds.into_iter().map_conv_with(&ctx).collect();
715 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
716 assert_eq!(converted.len(), expected_lines.len());
717 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
718 assert_eq!(folding_range.start_line, *start_line);
719 assert_eq!(folding_range.start_character, None);
720 assert_eq!(folding_range.end_line, *end_line);
721 assert_eq!(folding_range.end_character, None);