Skip to content
Draft
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/ide-host/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ ide-mcp.workspace = true
futures.workspace = true
tokio-tungstenite.workspace = true
ide-text.workspace = true
similar = { version = "2.7", default-features = false }
ide-vfs.workspace = true
regex-syntax.workspace = true
regex-lite = "0.1"
Expand Down
219 changes: 219 additions & 0 deletions crates/ide-host/src/ops/lsp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -438,8 +438,158 @@ pub async fn lsp_edit_argument(
host.project(window)?.lsp.edit_argument(doc, pos, name, value).await
}

/// Whether `doc` is a Git revision's blob (a `git-revision:` document).
fn is_revision_document(host: &Host, window: &str, doc: DocId) -> Option<String> {
let (path, _) = host.project(window).ok()?.documents.identity(doc).ok()?;
let uri = path.to_string_lossy();
uri.starts_with("git-revision:").then(|| uri.into_owned())
}

/// The working copy's text of `path`: the open document's (unsaved edits
/// included), else the file on disk.
fn working_text(project: &crate::Project, path: &Path) -> Option<String> {
project
.documents
.text_of(path)
.or_else(|| std::fs::read(path).ok().map(|bytes| String::from_utf8_lossy(&bytes).into_owned()))
}

/// The line of `new` that corresponds to 0-based `line` of `old`. A line that
/// only the old side has lands on the line that replaced it.
fn map_line(old: &str, new: &str, line: u32) -> u32 {
use similar::{Algorithm, DiffTag, capture_diff_slices};
let old_lines: Vec<&str> = old.split_inclusive('\n').collect();
let new_lines: Vec<&str> = new.split_inclusive('\n').collect();
let target = line as usize;
let (mut o, mut n) = (0usize, 0usize);
for op in capture_diff_slices(Algorithm::Myers, &old_lines, &new_lines) {
let (old_len, new_len) = (op.old_range().len(), op.new_range().len());
if target < o + old_len {
let offset = target - o;
let mapped =
if op.tag() == DiffTag::Equal { n + offset } else { n + offset.min(new_len.saturating_sub(1)) };
return mapped.min(new_lines.len().saturating_sub(1)) as u32;
}
o += old_len;
n += new_len;
}
new_lines.len().saturating_sub(1) as u32
}

/// Navigates inside a Git revision's blob through the project's own server:
/// the server analyses HEAD's text in a snapshot of its own, so the workspace
/// document and its servers stay untouched. Any language can answer the
/// generic revision request; a server without it returns "method not found"
/// and the request ends with no target, leaving the ordinary path to answer.
async fn revision_targets(
host: &Host,
window: &str,
doc: DocId,
uri: &str,
pos: Pos,
) -> IdeResult<Option<Vec<Location>>> {
let project = host.project(window)?;
let vd = crate::ops::vcs::revision_virtual_document(host, window, uri, None).await?;
let path = crate::ops::vcs::revision_blob_path(uri)?;
// The working copy is the document the server analyses (the diff's own right
// pane opens it). Without it there is nothing to swap: no jump.
let Some(working) = project.documents.by_path(&path) else {
return Ok(Some(Vec::new()));
};
let mut targets = project.lsp.revision_definition(working, &vd.text, pos).await?;
// A target in the same blob carries HEAD's line numbers, while the editor
// opens the working copy: translate them through the file's own diff.
if let Some(working) = working_text(&project, &path) {
for target in &mut targets {
if target.path.as_ref() != path.as_path() {
continue;
}
let line = map_line(&vd.text, &working, target.range.start.line);
let delta = i64::from(line) - i64::from(target.range.start.line);
target.range.start.line = line;
target.range.end.line = (i64::from(target.range.end.line) + delta).max(0) as u32;
}
}
Ok(Some(targets))
}

/// A revision's hits in the file itself carry the revision's line numbers,
/// while the editor opens the working copy: translate them through the file's
/// own diff, as [`revision_targets`] does for a jump.
fn map_revision_references(refs: &mut References, revision: &str, working: &str, path: &Path) {
fn one(location: &mut Location, revision: &str, working: &str, path: &Path) {
if location.path.as_ref() != path {
return;
}
let line = map_line(revision, working, location.range.start.line);
let delta = i64::from(line) - i64::from(location.range.start.line);
location.range.start.line = line;
location.range.end.line = (i64::from(location.range.end.line) + delta).max(0) as u32;
}
for location in &mut refs.locations {
one(location, revision, working, path);
}
for hit in &mut refs.classified {
one(&mut hit.location, revision, working, path);
}
}

/// Find Usages inside a Git revision's blob: the blob's text is swapped onto
/// the working document (see [`revision_targets`]), so the servers answer as if
/// the file already read that way. The working document not being open leaves
/// nothing to swap and no results; the ordinary path would only ask the servers
/// with a URI they reject.
async fn revision_references(
host: &Host,
window: &str,
uri: &str,
pos: Pos,
include_declaration: bool,
project_wide: bool,
libraries: bool,
cancel: CancellationToken,
on_partial: &super::Channel<References>,
) -> IdeResult<References> {
let project = host.project(window)?;
let vd = crate::ops::vcs::revision_virtual_document(host, window, uri, None).await?;
let path = crate::ops::vcs::revision_blob_path(uri)?;
let Some(target) = project.documents.by_path(&path) else {
return Ok(References::default());
};
let revision = vd.text;
let working = working_text(&project, &path);
let partial = |mut refs: References| {
if let Some(working) = &working {
map_revision_references(&mut refs, &revision, working, &path);
}
let _ = on_partial.send(refs);
};
let mut result = project
.lsp
.revision_references(
target,
&revision,
pos,
include_declaration,
project_wide,
libraries,
cancel,
Some(&partial),
)
.await?;
if let Some(working) = &working {
map_revision_references(&mut result, &revision, working, &path);
}
Ok(result)
}

#[command(trust = trusted)]
pub async fn lsp_goto(host: &Host, window: &str, doc: DocId, pos: Pos, kind: GotoKind) -> IdeResult<Vec<Location>> {
if kind == GotoKind::Definition
&& let Some(uri) = is_revision_document(host, window, doc)
{
return Ok(revision_targets(host, window, doc, &uri, pos).await?.unwrap_or_default());
}
let target = position_document(host, window, doc, pos).await?;
// ⌘B on a declaration shows its usages, also when a plugin's index links the name elsewhere
// (a MyBatis mapper method to its XML statement): the server's answer comes along for the
Expand Down Expand Up @@ -870,6 +1020,26 @@ pub async fn lsp_references(
libraries: bool,
on_partial: super::Channel<References>,
) -> IdeResult<References> {
// The revision pane's document: its `git-revision:` URI never reaches the
// servers (they reject it), so the search runs through the working copy
// swapped to the blob's text instead — the same isolation as a jump.
if let Some(uri) = is_revision_document(host, window, doc) {
let cancel = host.begin_request(request);
let result = revision_references(
host,
window,
&uri,
pos,
include_declaration,
project_wide,
libraries,
cancel,
&on_partial,
)
.await;
host.end_request(request);
return result;
}
// Java: without `libraries`, the dependencies and the JDK are not searched.
let project = host.project(window)?;
let lsp = project.lsp.clone();
Expand Down Expand Up @@ -1943,6 +2113,11 @@ pub async fn lsp_inlay_hints(host: &Host, window: &str, doc: DocId, range: Range

#[command(trust = trusted)]
pub async fn lsp_semantic_tokens(host: &Host, window: &str, doc: DocId) -> IdeResult<Option<SemanticTokens>> {
// A revision pane's colours would need the server's revision token request;
// until it exists, no tokens is the honest answer (not an error).
if is_revision_document(host, window, doc).is_some() {
return Ok(None);
}
let lsp = host.project(window)?.lsp.clone();
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::SemanticTokens) else {
return lsp.semantic_tokens(doc).await;
Expand Down Expand Up @@ -3252,6 +3427,50 @@ mod tests {
}
}

#[cfg(test)]
mod revision_tests {
#[test]
fn revision_lines_map_to_the_working_copy() {
let head = "a\nb\nc\nd\ne\n";
let working = "a\nb\nX\nY\nc\nD1\nD2\ne\n";
assert_eq!(super::map_line(head, working, 0), 0);
assert_eq!(super::map_line(head, working, 1), 1);
assert_eq!(super::map_line(head, working, 2), 4);
assert_eq!(super::map_line(head, working, 3), 5);
assert_eq!(super::map_line(head, working, 4), 7);
}

#[test]
fn unchanged_files_keep_their_lines() {
let text = "a\nb\nc\n";
assert_eq!(super::map_line(text, text, 2), 2);
}

#[test]
fn revision_hits_map_onto_the_working_copy() {
use super::*;
let revision = "a\nb\nc\n";
let working = "a\nX\nb\nc\n";
let path = std::path::PathBuf::from("C:/repo/src/Main.java");
let mut refs = References::default();
refs.locations.push(Location {
path: path.clone().into(),
range: Range { start: Pos::new(1, 0), end: Pos::new(1, 3) },
uri: None,
});
refs.locations.push(Location {
path: std::path::PathBuf::from("C:/repo/src/Other.java").into(),
range: Range { start: Pos::new(1, 0), end: Pos::new(1, 3) },
uri: None,
});
map_revision_references(&mut refs, revision, working, &path);
// Line 1 ("b") moved down by the inserted line; the other file's hit stands.
assert_eq!(refs.locations[0].range.start.line, 2);
assert_eq!(refs.locations[0].range.end.line, 4);
assert_eq!(refs.locations[1].range.start.line, 1);
}
}

ide_command::domain!(
lsp:
apply_workspace_edit,
Expand Down
45 changes: 29 additions & 16 deletions crates/ide-host/src/ops/vcs/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,21 +30,15 @@ fn external_log_of(host: &Host, window: &str, path: &Path) -> Option<std::sync::
})
}

/// Immutable Git objects exposed through the editor's ordinary read-only VFS.
/// `encoding` re-decodes the blob with it ("Reload with Encoding") instead of
/// the project's detection.
pub async fn revision_virtual_document(
host: &Host,
window: &str,
uri: &str,
encoding: Option<&str>,
) -> IdeResult<ide_lsp::types::VirtualDocument> {
#[derive(Deserialize)]
struct Target {
repo: PathBuf,
revision: String,
path: PathBuf,
}
#[derive(Deserialize)]
struct RevisionTarget {
repo: PathBuf,
revision: String,
path: PathBuf,
}

/// Decodes the `{repo, revision, path}` a `git-revision:` URI carries.
fn revision_target(uri: &str) -> IdeResult<RevisionTarget> {
let encoded = uri
.strip_prefix("git-revision:")
.and_then(|s| s.split('/').next())
Expand All @@ -59,7 +53,26 @@ pub async fn revision_virtual_document(
.map_err(|_| ide_core::IdeError::invalid("invalid Git revision URI"))
})
.collect::<IdeResult<Vec<_>>>()?;
let target: Target = serde_json::from_slice(&bytes).map_err(|e| ide_core::IdeError::invalid(e.to_string()))?;
serde_json::from_slice(&bytes).map_err(|e| ide_core::IdeError::invalid(e.to_string()))
}

/// The file's own path for a `git-revision:` URI: the path the revision blob
/// stands in for, which is also the path the language server knows.
pub fn revision_blob_path(uri: &str) -> IdeResult<PathBuf> {
let target = revision_target(uri)?;
Ok(target.repo.join(&target.path))
}

/// Immutable Git objects exposed through the editor's ordinary read-only VFS.
/// `encoding` re-decodes the blob with it ("Reload with Encoding") instead of
/// the project's detection.
pub async fn revision_virtual_document(
host: &Host,
window: &str,
uri: &str,
encoding: Option<&str>,
) -> IdeResult<ide_lsp::types::VirtualDocument> {
let target = revision_target(uri)?;
let path = target.repo.join(&target.path);
let (text, charset, has_bom) = revision_text(host, window, &path, &target.revision, encoding)
.await?
Expand Down
4 changes: 4 additions & 0 deletions crates/ide-host/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2176,6 +2176,10 @@ impl DocumentObserver for LspObserver {
return;
}
match &info.uri {
// A revision blob is served by swapping the working document's text
// (see `revision_targets`), never opened as a document: its
// `git-revision:` URI names no file the server could analyse.
Some(uri) if uri.starts_with("git-revision:") => {}
Some(uri) => self.0.did_open_virtual(info.id, uri, &info.language, info.version, &info.text),
None => self.0.did_open(info.id, &info.path, &info.language, info.version, &info.text),
}
Expand Down
Loading