]> git.lizzy.rs Git - rust.git/blobdiff - crates/ra_lsp_server/src/conv.rs
Pass Documentation up to LSP and add "rust" to our codeblocks there
[rust.git] / crates / ra_lsp_server / src / conv.rs
index 8bf8576be9b48305689ea285dc7e17efc9d6e982..c033ecdeaa10a1c570b9b4e4bec72b7dee60dca4 100644 (file)
@@ -1,11 +1,16 @@
-use languageserver_types::{
-    Location, Position, Range, SymbolKind, TextDocumentEdit, TextDocumentIdentifier,
-    TextDocumentItem, TextDocumentPositionParams, TextEdit, Url, VersionedTextDocumentIdentifier,
+use lsp_types::{
+    self, CreateFile, Documentation, DocumentChangeOperation, DocumentChanges, Location, LocationLink,
+    MarkupContent, MarkupKind, Position, Range, RenameFile, ResourceOp, SymbolKind, TextDocumentEdit, TextDocumentIdentifier,
+    TextDocumentItem, TextDocumentPositionParams, Url, VersionedTextDocumentIdentifier,
+    WorkspaceEdit,
+};
+use ra_ide_api::{
+    CompletionItem, CompletionItemKind, FileId, FilePosition, FileRange, FileSystemEdit,
+    NavigationTarget, SourceChange, SourceFileEdit, RangeInfo,
+    LineCol, LineIndex, translate_offset_with_edit, InsertTextFormat
 };
-use ra_analysis::{FileId, FileSystemEdit, SourceChange, SourceFileNodeEdit, FilePosition};
-use ra_editor::{LineCol, LineIndex};
-use ra_text_edit::{AtomEdit, Edit};
 use ra_syntax::{SyntaxKind, TextRange, TextUnit};
+use ra_text_edit::{AtomTextEdit, TextEdit};
 
 use crate::{req, server_world::ServerWorld, Result};
 
@@ -39,12 +44,68 @@ fn conv(self) -> <Self as Conv>::Output {
             SyntaxKind::TYPE_DEF => SymbolKind::TypeParameter,
             SyntaxKind::STATIC_DEF => SymbolKind::Constant,
             SyntaxKind::CONST_DEF => SymbolKind::Constant,
-            SyntaxKind::IMPL_ITEM => SymbolKind::Object,
+            SyntaxKind::IMPL_BLOCK => SymbolKind::Object,
             _ => SymbolKind::Variable,
         }
     }
 }
 
+impl Conv for CompletionItemKind {
+    type Output = ::lsp_types::CompletionItemKind;
+
+    fn conv(self) -> <Self as Conv>::Output {
+        use lsp_types::CompletionItemKind::*;
+        match self {
+            CompletionItemKind::Keyword => Keyword,
+            CompletionItemKind::Snippet => Snippet,
+            CompletionItemKind::Module => Module,
+            CompletionItemKind::Function => Function,
+            CompletionItemKind::Struct => Struct,
+            CompletionItemKind::Enum => Enum,
+            CompletionItemKind::EnumVariant => EnumMember,
+            CompletionItemKind::Binding => Variable,
+            CompletionItemKind::Field => Field,
+            CompletionItemKind::Trait => Interface,
+            CompletionItemKind::TypeAlias => Struct,
+            CompletionItemKind::Const => Constant,
+            CompletionItemKind::Static => Value,
+            CompletionItemKind::Method => Method,
+        }
+    }
+}
+
+impl ConvWith for CompletionItem {
+    type Ctx = LineIndex;
+    type Output = ::lsp_types::CompletionItem;
+
+    fn conv_with(mut self, ctx: &LineIndex) -> ::lsp_types::CompletionItem {
+        let atom_text_edit = AtomTextEdit::replace(self.source_range(), self.insert_text());
+        let text_edit = (&atom_text_edit).conv_with(ctx);
+        let additional_text_edits = if let Some(edit) = self.take_text_edit() {
+            Some(edit.conv_with(ctx))
+        } else {
+            None
+        };
+
+        let mut res = lsp_types::CompletionItem {
+            label: self.label().to_string(),
+            detail: self.detail().map(|it| it.to_string()),
+            filter_text: Some(self.lookup().to_string()),
+            kind: self.kind().map(|it| it.conv()),
+            text_edit: Some(text_edit),
+            additional_text_edits,
+            documentation: self.documentation().map(|it| it.conv()),
+            ..Default::default()
+        };
+        res.insert_text_format = Some(match self.insert_text_format() {
+            InsertTextFormat::Snippet => lsp_types::InsertTextFormat::Snippet,
+            InsertTextFormat::PlainText => lsp_types::InsertTextFormat::PlainText,
+        });
+
+        res
+    }
+}
+
 impl ConvWith for Position {
     type Ctx = LineIndex;
     type Output = TextUnit;
@@ -92,26 +153,36 @@ fn conv_with(self, line_index: &LineIndex) -> TextRange {
     }
 }
 
-impl ConvWith for Edit {
+impl Conv for ra_ide_api::Documentation {
+    type Output = lsp_types::Documentation;
+    fn conv(self) -> Documentation {
+        Documentation::MarkupContent(MarkupContent {
+            kind: MarkupKind::Markdown,
+            value: crate::markdown::sanitize_markdown(self).into(),
+        })
+    }
+}
+
+impl ConvWith for TextEdit {
     type Ctx = LineIndex;
-    type Output = Vec<TextEdit>;
+    type Output = Vec<lsp_types::TextEdit>;
 
-    fn conv_with(self, line_index: &LineIndex) -> Vec<TextEdit> {
-        self.into_atoms()
+    fn conv_with(self, line_index: &LineIndex) -> Vec<lsp_types::TextEdit> {
+        self.as_atoms()
             .into_iter()
             .map_conv_with(line_index)
             .collect()
     }
 }
 
-impl ConvWith for AtomEdit {
+impl<'a> ConvWith for &'a AtomTextEdit {
     type Ctx = LineIndex;
-    type Output = TextEdit;
+    type Output = lsp_types::TextEdit;
 
-    fn conv_with(self, line_index: &LineIndex) -> TextEdit {
-        TextEdit {
+    fn conv_with(self, line_index: &LineIndex) -> lsp_types::TextEdit {
+        lsp_types::TextEdit {
             range: self.delete.conv_with(line_index),
-            new_text: self.insert,
+            new_text: self.insert.clone(),
         }
     }
 }
@@ -175,6 +246,17 @@ fn try_conv_with(self, world: &ServerWorld) -> Result<FilePosition> {
     }
 }
 
+impl<'a> TryConvWith for (&'a TextDocumentIdentifier, Range) {
+    type Ctx = ServerWorld;
+    type Output = FileRange;
+    fn try_conv_with(self, world: &ServerWorld) -> Result<FileRange> {
+        let file_id = self.0.try_conv_with(world)?;
+        let line_index = world.analysis().file_line_index(file_id);
+        let range = self.1.conv_with(&line_index);
+        Ok(FileRange { file_id, range })
+    }
+}
+
 impl<T: TryConvWith> TryConvWith for Vec<T> {
     type Ctx = <T as TryConvWith>::Ctx;
     type Output = Vec<<T as TryConvWith>::Output>;
@@ -195,13 +277,15 @@ fn try_conv_with(self, world: &ServerWorld) -> Result<req::SourceChange> {
             None => None,
             Some(pos) => {
                 let line_index = world.analysis().file_line_index(pos.file_id);
-                let edits = self
+                let edit = self
                     .source_file_edits
                     .iter()
                     .find(|it| it.file_id == pos.file_id)
-                    .map(|it| it.edits.as_slice())
-                    .unwrap_or(&[]);
-                let line_col = translate_offset_with_edit(&*line_index, pos.offset, edits);
+                    .map(|it| &it.edit);
+                let line_col = match edit {
+                    Some(edit) => translate_offset_with_edit(&*line_index, pos.offset, edit),
+                    None => line_index.line_col(pos.offset),
+                };
                 let position =
                     Position::new(u64::from(line_col.line), u64::from(line_col.col_utf16));
                 Some(TextDocumentPositionParams {
@@ -210,53 +294,26 @@ fn try_conv_with(self, world: &ServerWorld) -> Result<req::SourceChange> {
                 })
             }
         };
-        let source_file_edits = self.source_file_edits.try_conv_with(world)?;
-        let file_system_edits = self.file_system_edits.try_conv_with(world)?;
+        let mut document_changes: Vec<DocumentChangeOperation> = Vec::new();
+        for resource_op in self.file_system_edits.try_conv_with(world)? {
+            document_changes.push(DocumentChangeOperation::Op(resource_op));
+        }
+        for text_document_edit in self.source_file_edits.try_conv_with(world)? {
+            document_changes.push(DocumentChangeOperation::Edit(text_document_edit));
+        }
+        let workspace_edit = WorkspaceEdit {
+            changes: None,
+            document_changes: Some(DocumentChanges::Operations(document_changes)),
+        };
         Ok(req::SourceChange {
             label: self.label,
-            source_file_edits,
-            file_system_edits,
+            workspace_edit,
             cursor_position,
         })
     }
 }
 
-// HACK: we should translate offset to line/column using linde_index *with edits applied*.
-// A naive version of this function would be to apply `edits` to the original text,
-// construct a new line index and use that, but it would be slow.
-//
-// Writing fast & correct version is issue #105, let's use a quick hack in the meantime
-fn translate_offset_with_edit(
-    pre_edit_index: &LineIndex,
-    offset: TextUnit,
-    edits: &[AtomEdit],
-) -> LineCol {
-    let fallback = pre_edit_index.line_col(offset);
-    let edit = match edits.first() {
-        None => return fallback,
-        Some(edit) => edit,
-    };
-    let end_offset = edit.delete.start() + TextUnit::of_str(&edit.insert);
-    if !(edit.delete.start() <= offset && offset <= end_offset) {
-        return fallback;
-    }
-    let rel_offset = offset - edit.delete.start();
-    let in_edit_line_col = LineIndex::new(&edit.insert).line_col(rel_offset);
-    let edit_line_col = pre_edit_index.line_col(edit.delete.start());
-    if in_edit_line_col.line == 0 {
-        LineCol {
-            line: edit_line_col.line,
-            col_utf16: edit_line_col.col_utf16 + in_edit_line_col.col_utf16,
-        }
-    } else {
-        LineCol {
-            line: edit_line_col.line + in_edit_line_col.line,
-            col_utf16: in_edit_line_col.col_utf16,
-        }
-    }
-}
-
-impl TryConvWith for SourceFileNodeEdit {
+impl TryConvWith for SourceFileEdit {
     type Ctx = ServerWorld;
     type Output = TextDocumentEdit;
     fn try_conv_with(self, world: &ServerWorld) -> Result<TextDocumentEdit> {
@@ -265,7 +322,12 @@ fn try_conv_with(self, world: &ServerWorld) -> Result<TextDocumentEdit> {
             version: None,
         };
         let line_index = world.analysis().file_line_index(self.file_id);
-        let edits = self.edits.into_iter().map_conv_with(&line_index).collect();
+        let edits = self
+            .edit
+            .as_atoms()
+            .iter()
+            .map_conv_with(&line_index)
+            .collect();
         Ok(TextDocumentEdit {
             text_document,
             edits,
@@ -275,26 +337,67 @@ fn try_conv_with(self, world: &ServerWorld) -> Result<TextDocumentEdit> {
 
 impl TryConvWith for FileSystemEdit {
     type Ctx = ServerWorld;
-    type Output = req::FileSystemEdit;
-    fn try_conv_with(self, world: &ServerWorld) -> Result<req::FileSystemEdit> {
+    type Output = ResourceOp;
+    fn try_conv_with(self, world: &ServerWorld) -> Result<ResourceOp> {
         let res = match self {
-            FileSystemEdit::CreateFile { anchor, path } => {
-                let uri = world.file_id_to_uri(anchor)?;
-                let path = &path.as_str()[3..]; // strip `../` b/c url is weird
-                let uri = uri.join(path)?;
-                req::FileSystemEdit::CreateFile { uri }
+            FileSystemEdit::CreateFile { source_root, path } => {
+                let uri = world.path_to_uri(source_root, &path)?;
+                ResourceOp::Create(CreateFile { uri, options: None })
             }
-            FileSystemEdit::MoveFile { file, path } => {
-                let src = world.file_id_to_uri(file)?;
-                let path = &path.as_str()[3..]; // strip `../` b/c url is weird
-                let dst = src.join(path)?;
-                req::FileSystemEdit::MoveFile { src, dst }
+            FileSystemEdit::MoveFile {
+                src,
+                dst_source_root,
+                dst_path,
+            } => {
+                let old_uri = world.file_id_to_uri(src)?;
+                let new_uri = world.path_to_uri(dst_source_root, &dst_path)?;
+                ResourceOp::Rename(RenameFile {
+                    old_uri,
+                    new_uri,
+                    options: None,
+                })
             }
         };
         Ok(res)
     }
 }
 
+impl TryConvWith for &NavigationTarget {
+    type Ctx = ServerWorld;
+    type Output = Location;
+    fn try_conv_with(self, world: &ServerWorld) -> Result<Location> {
+        let line_index = world.analysis().file_line_index(self.file_id());
+        let range = self.focus_range().unwrap_or(self.full_range());
+        to_location(self.file_id(), range, &world, &line_index)
+    }
+}
+
+pub fn to_location_link(
+    target: &RangeInfo<NavigationTarget>,
+    world: &ServerWorld,
+    // line index for original range file
+    line_index: &LineIndex,
+) -> Result<LocationLink> {
+    let target_uri = target.info.file_id().try_conv_with(world)?;
+    let tgt_line_index = world.analysis().file_line_index(target.info.file_id());
+
+    let target_range = target.info.full_range().conv_with(&tgt_line_index);
+
+    let target_selection_range = target
+        .info
+        .focus_range()
+        .map(|it| it.conv_with(&tgt_line_index))
+        .unwrap_or(target_range);
+
+    let res = LocationLink {
+        origin_selection_range: Some(target.range.conv_with(line_index)),
+        target_uri,
+        target_range,
+        target_selection_range: target_selection_range,
+    };
+    Ok(res)
+}
+
 pub fn to_location(
     file_id: FileId,
     range: TextRange,