Skip to content

Commit 78f4aa0

Browse files
committed
fix(lsp): identify documents by the same resolved path as the index
The server canonicalized every workspace root at initialize but took document paths straight from the URI. On Windows canonicalization adds the \\?\ verbatim prefix that a URI never carries, so a document could never match its own workspace index entry and every cross-file feature (diagnostics, references, rename, path and anchor completion) was silently dead. On Unix the same skew appears whenever the editor reaches a file through a symlinked ancestor. Resolution is now a single boundary in src/lsp/mod.rs that every consumer goes through, so the LSP has one path space instead of two. Only a document's directory is resolved: the workspace scan does not follow symlinks, so it records a file under the name it was reached by, and a file deleted since it was indexed still resolves. Navigation asks for a document's content by the resolved spelling while the store is keyed by the spelling the editor opened, so did_open now records an alias between the two. Without it a hover under a symlinked root read the file from disk and previewed content the buffer no longer had. A buffer open under the requested spelling outranks any alias, since one file can be open under several spellings at once; a disk copy cached under it does not, having been read before the document was opened elsewhere. Each resolved path keeps every open spelling rather than the latest, so neither a second open nor the first close can strand a buffer that is still open.
1 parent 499b005 commit 78f4aa0

6 files changed

Lines changed: 587 additions & 94 deletions

File tree

‎src/lsp/completion.rs‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ impl RumdlLanguageServer {
199199
position: Position,
200200
) -> Vec<CompletionItem> {
201201
// Resolve config for this file to get MD040 settings
202-
let file_path = uri.to_file_path().ok();
202+
let file_path = super::resolve_uri(uri);
203203
let config = if let Some(ref path) = file_path {
204204
self.resolve_config_for_file(path).await
205205
} else {
@@ -398,7 +398,7 @@ impl RumdlLanguageServer {
398398
.await;
399399
}
400400

401-
let Ok(current_file) = uri.to_file_path() else {
401+
let Some(current_file) = super::resolve_uri(uri) else {
402402
return CompletionList::default();
403403
};
404404
let Some(current_dir) = current_file.parent().map(std::path::Path::to_path_buf) else {
@@ -596,7 +596,10 @@ impl RumdlLanguageServer {
596596
for entry in &configured {
597597
let path = PathBuf::from(entry);
598598
if path.is_absolute() {
599-
out.push(path);
599+
// A configured absolute root is written independently of the
600+
// workspace, so it is resolved to the space index keys live in.
601+
// A relative one is joined onto an already resolved root.
602+
out.push(super::resolve_workspace_root(&path));
600603
} else {
601604
for root in roots.iter() {
602605
out.push(normalize_path(&root.join(&path)));
@@ -656,7 +659,7 @@ impl RumdlLanguageServer {
656659
start_col: u32,
657660
position: Position,
658661
) -> Vec<CompletionItem> {
659-
let Ok(current_file) = uri.to_file_path() else {
662+
let Some(current_file) = super::resolve_uri(uri) else {
660663
return Vec::new();
661664
};
662665

‎src/lsp/linting.rs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ impl RumdlLanguageServer {
2020
/// Check if a file URI should be excluded based on exclude patterns
2121
pub(super) async fn should_exclude_uri(&self, uri: &Url) -> bool {
2222
// Try to convert URI to file path
23-
let Ok(file_path) = uri.to_file_path() else {
23+
let Some(file_path) = super::resolve_uri(uri) else {
2424
return false; // If we can't get a path, don't exclude
2525
};
2626

@@ -86,7 +86,7 @@ impl RumdlLanguageServer {
8686
}
8787

8888
// Resolve configuration for this specific file
89-
let file_path = uri.to_file_path().ok();
89+
let file_path = super::resolve_uri(uri);
9090
let file_config = if let Some(ref path) = file_path {
9191
self.resolve_config_for_file(path).await
9292
} else {
@@ -266,7 +266,7 @@ impl RumdlLanguageServer {
266266
drop(config_guard);
267267

268268
// Resolve configuration for this specific file
269-
let file_path = uri.to_file_path().ok();
269+
let file_path = super::resolve_uri(uri);
270270
let file_config = if let Some(ref path) = file_path {
271271
self.resolve_config_for_file(path).await
272272
} else {
@@ -379,7 +379,7 @@ impl RumdlLanguageServer {
379379
drop(config_guard);
380380

381381
// Resolve configuration for this specific file
382-
let file_path = uri.to_file_path().ok();
382+
let file_path = super::resolve_uri(uri);
383383
let file_config = if let Some(ref path) = file_path {
384384
self.resolve_config_for_file(path).await
385385
} else {

‎src/lsp/mod.rs‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,61 @@ pub use server::RumdlLanguageServer;
2020
pub use types::{RumdlLspConfig, warning_to_code_actions, warning_to_diagnostic};
2121

2222
use anyhow::Result;
23+
use std::path::{Path, PathBuf};
2324
use tokio::net::TcpListener;
2425
use tower_lsp::{LspService, Server};
2526

27+
/// Resolve a workspace root to the path space the server identifies files in.
28+
///
29+
/// Every index key descends from a resolved root, so a document must be
30+
/// resolved the same way for a lookup to find its entry. Sharing one space also
31+
/// makes a root-relative comparison (`starts_with`, exclude relativization)
32+
/// answer for the paths documents actually arrive as.
33+
pub(crate) fn resolve_workspace_root(path: &Path) -> PathBuf {
34+
crate::discovery::canonicalize_for_matching(path).unwrap_or_else(|| path.to_path_buf())
35+
}
36+
37+
/// Resolve a document path to the same space as [`resolve_workspace_root`].
38+
///
39+
/// A URI arrives in whatever form the editor sent. It can reach the file
40+
/// through a symlinked ancestor, and on Windows it never carries the `\\?\`
41+
/// prefix that canonicalization produces, so the raw path routinely names the
42+
/// same file as a key without being equal to it.
43+
///
44+
/// Only the directory is resolved. The workspace scan does not follow symlinks,
45+
/// so it records a symlinked file under the name it was reached by rather than
46+
/// under its target, and resolving the file itself would look up a path the
47+
/// scan never produced. Resolving the directory also keeps working for a file
48+
/// that is not on disk, such as one deleted since it was indexed.
49+
pub(crate) fn resolve_document_path(path: &Path) -> PathBuf {
50+
let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else {
51+
return resolve_workspace_root(path);
52+
};
53+
match crate::discovery::canonicalize_for_matching(parent) {
54+
Some(dir) => dir.join(name),
55+
None => path.to_path_buf(),
56+
}
57+
}
58+
59+
/// Resolve a document URI to the path the server identifies it by.
60+
///
61+
/// `None` for a URI that names no file, such as an editor's untitled buffer.
62+
pub(crate) fn resolve_uri(uri: &tower_lsp::lsp_types::Url) -> Option<PathBuf> {
63+
uri.to_file_path().ok().map(|path| resolve_document_path(&path))
64+
}
65+
66+
/// Spell a URI the way the server identifies the document it names.
67+
///
68+
/// Navigation resolves a link target to a path and turns it back into a URI to
69+
/// ask for that document's content, so a document whose own URI spells its path
70+
/// differently is reachable under two URIs. This is the one the server treats as
71+
/// the document's identity; a URI naming no file is its own.
72+
pub(crate) fn resolve_uri_spelling(uri: &tower_lsp::lsp_types::Url) -> tower_lsp::lsp_types::Url {
73+
resolve_uri(uri)
74+
.and_then(|path| tower_lsp::lsp_types::Url::from_file_path(path).ok())
75+
.unwrap_or_else(|| uri.clone())
76+
}
77+
2678
/// Start the Language Server Protocol server
2779
/// This is the main entry point for `rumdl server`
2880
pub async fn start_server(config_path: Option<&str>) -> Result<()> {

‎src/lsp/navigation.rs‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -500,7 +500,8 @@ impl RumdlLanguageServer {
500500

501501
/// Base path for resolving a link target's relative file path.
502502
///
503-
/// For `file://` URIs this is the document's own path. For non-file URIs
503+
/// For `file://` URIs this is the document's own resolved path, so a target
504+
/// resolved against it is comparable with the workspace index. For non-file URIs
504505
/// (unsaved buffers like `buffer:647`, `untitled:` documents) there is no
505506
/// on-disk path, so relative links are anchored to the first workspace root.
506507
/// Returns `None` when neither is available, so navigation degrades to a no-op.
@@ -509,7 +510,7 @@ impl RumdlLanguageServer {
509510
/// so a synthetic file name is hung off the workspace root to make the root the
510511
/// parent directory.
511512
async fn link_resolution_base(&self, uri: &Url) -> Option<PathBuf> {
512-
if let Ok(path) = uri.to_file_path() {
513+
if let Some(path) = super::resolve_uri(uri) {
513514
return Some(path);
514515
}
515516
let root = self.workspace_roots.read().await.first().cloned()?;
@@ -700,7 +701,7 @@ impl RumdlLanguageServer {
700701
/// that point to the same target.
701702
pub(super) async fn handle_references(&self, uri: &Url, position: Position) -> Option<Vec<Location>> {
702703
let text = self.get_document_content(uri).await?;
703-
let current_file = uri.to_file_path().ok()?;
704+
let current_file = super::resolve_uri(uri)?;
704705

705706
// Check if cursor is on a heading by consulting the workspace index.
706707
// This avoids false positives from `#` lines inside code blocks.
@@ -969,7 +970,7 @@ impl RumdlLanguageServer {
969970
/// text range (excluding `#` markers, leading whitespace, and custom anchors).
970971
pub(super) async fn handle_prepare_rename(&self, uri: &Url, position: Position) -> Option<PrepareRenameResponse> {
971972
let text = self.get_document_content(uri).await?;
972-
let current_file = uri.to_file_path().ok()?;
973+
let current_file = super::resolve_uri(uri)?;
973974

974975
let heading_line_1indexed = (position.line as usize) + 1;
975976

@@ -1023,7 +1024,7 @@ impl RumdlLanguageServer {
10231024
}
10241025

10251026
let text = self.get_document_content(uri).await?;
1026-
let current_file = uri.to_file_path().ok()?;
1027+
let current_file = super::resolve_uri(uri)?;
10271028

10281029
let heading_line_1indexed = (position.line as usize) + 1;
10291030

‎src/lsp/server.rs‎

Lines changed: 84 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,19 @@ pub struct RumdlLanguageServer {
9797
pub(crate) rumdl_sourced: Arc<RwLock<Option<Arc<SourcedConfig<ConfigValidated>>>>>,
9898
/// Document store for open files and cached disk files
9999
pub(crate) documents: Arc<RwLock<HashMap<Url, DocumentEntry>>>,
100+
/// Maps a document's resolved URI to every open spelling that names it.
101+
///
102+
/// The store is keyed by the editor's spelling, because that is the spelling
103+
/// diagnostics must be published against. Navigation asks for a document by
104+
/// its resolved spelling, which differs only when the editor reached the file
105+
/// through a symlinked ancestor, so this stays empty for most workspaces.
106+
/// Without it such a request would read the file on disk and miss the buffer.
107+
///
108+
/// One resolved path can have several spellings open at once (two symlinks
109+
/// to the same directory, each opened), so this holds all of them rather
110+
/// than the latest. A single slot would let the second open displace the
111+
/// first and the first close strand the second.
112+
pub(crate) document_aliases: Arc<RwLock<HashMap<Url, Vec<Url>>>>,
100113
/// Workspace root folders from the client
101114
pub(crate) workspace_roots: Arc<RwLock<Vec<PathBuf>>>,
102115
/// Configuration cache: maps directory path to resolved config
@@ -158,6 +171,7 @@ impl RumdlLanguageServer {
158171
rumdl_config,
159172
rumdl_sourced: Arc::new(RwLock::new(None)),
160173
documents: Arc::new(RwLock::new(HashMap::new())),
174+
document_aliases: Arc::new(RwLock::new(HashMap::new())),
161175
workspace_roots,
162176
config_cache: Arc::new(RwLock::new(HashMap::new())),
163177
workspace_index,
@@ -175,6 +189,8 @@ impl RumdlLanguageServer {
175189
/// If not found, it attempts to read the file from disk and caches it for
176190
/// future requests.
177191
pub(super) async fn get_document_content(&self, uri: &Url) -> Option<String> {
192+
let uri = &self.store_uri(uri).await;
193+
178194
// First check the cache
179195
{
180196
let docs = self.documents.read().await;
@@ -212,17 +228,47 @@ impl RumdlLanguageServer {
212228
/// scoped to open documents. This avoids lingering diagnostics after a file
213229
/// is closed when clients use pull diagnostics.
214230
async fn get_open_document_content(&self, uri: &Url) -> Option<String> {
231+
let uri = self.store_uri(uri).await;
215232
let docs = self.documents.read().await;
216-
docs.get(uri)
233+
docs.get(&uri)
217234
.and_then(|entry| (!entry.from_disk).then(|| entry.content.clone()))
218235
}
219236

237+
/// The URI a document is stored under, given any spelling that names it.
238+
///
239+
/// Answers with the request's own URI, except when the file is open only
240+
/// under a different spelling of the same path: an alias then finds the
241+
/// editor's buffer instead of falling through to the file on disk.
242+
///
243+
/// An open buffer under the requested spelling wins over any alias, because
244+
/// one file can be open under several spellings at once and the editor holds
245+
/// a separate buffer for each. A disk copy cached under the requested
246+
/// spelling does not win: it was read before the document was opened
247+
/// elsewhere, and the buffer an alias names has since become the truth.
248+
async fn store_uri(&self, uri: &Url) -> Url {
249+
let Some(spellings) = self.document_aliases.read().await.get(uri).cloned() else {
250+
return uri.clone();
251+
};
252+
let docs = self.documents.read().await;
253+
let is_open = |u: &Url| matches!(docs.get(u), Some(entry) if !entry.from_disk);
254+
if is_open(uri) {
255+
return uri.clone();
256+
}
257+
// The most recently opened spelling, so a reopen supersedes an older one.
258+
spellings
259+
.iter()
260+
.rev()
261+
.find(|u| is_open(u))
262+
.cloned()
263+
.unwrap_or_else(|| uri.clone())
264+
}
265+
220266
/// Resolve the Markdown flavor for a document, mirroring the per-file flavor
221267
/// resolution used by diagnostics and formatting so symbol parsing matches.
222268
pub(super) async fn resolve_flavor_for_uri(&self, uri: &Url) -> crate::config::MarkdownFlavor {
223-
match uri.to_file_path() {
224-
Ok(path) => self.resolve_config_for_file(&path).await.get_flavor_for_file(&path),
225-
Err(_) => self.rumdl_config.read().await.markdown_flavor(),
269+
match super::resolve_uri(uri) {
270+
Some(path) => self.resolve_config_for_file(&path).await.get_flavor_for_file(&path),
271+
None => self.rumdl_config.read().await.markdown_flavor(),
226272
}
227273
}
228274
}
@@ -271,15 +317,15 @@ impl LanguageServer for RumdlLanguageServer {
271317
if let Some(workspace_folders) = params.workspace_folders {
272318
for folder in workspace_folders {
273319
if let Ok(path) = folder.uri.to_file_path() {
274-
let path = path.canonicalize().unwrap_or(path);
320+
let path = super::resolve_workspace_root(&path);
275321
log::info!("Workspace root: {}", path.display());
276322
roots.push(path);
277323
}
278324
}
279325
} else if let Some(root_uri) = params.root_uri
280326
&& let Ok(path) = root_uri.to_file_path()
281327
{
282-
let path = path.canonicalize().unwrap_or(path);
328+
let path = super::resolve_workspace_root(&path);
283329
log::info!("Workspace root: {}", path.display());
284330
roots.push(path);
285331
}
@@ -537,9 +583,12 @@ impl LanguageServer for RumdlLanguageServer {
537583
// Update workspace roots
538584
let mut roots = self.workspace_roots.write().await;
539585

586+
// Resolved the same way `initialize` resolves a root, so a folder added
587+
// or removed later is comparable with the ones already recorded.
540588
// Remove deleted workspace folders
541589
for removed in &params.event.removed {
542590
if let Ok(path) = removed.uri.to_file_path() {
591+
let path = super::resolve_workspace_root(&path);
543592
roots.retain(|r| r != &path);
544593
log::info!("Removed workspace root: {}", path.display());
545594
}
@@ -548,6 +597,7 @@ impl LanguageServer for RumdlLanguageServer {
548597
// Add new workspace folders
549598
for added in &params.event.added {
550599
if let Ok(path) = added.uri.to_file_path()
600+
&& let path = super::resolve_workspace_root(&path)
551601
&& !roots.contains(&path)
552602
{
553603
log::info!("Added workspace root: {}", path.display());
@@ -869,8 +919,18 @@ impl LanguageServer for RumdlLanguageServer {
869919
};
870920
self.documents.write().await.insert(uri.clone(), entry);
871921

922+
// Make the document reachable by the spelling navigation resolves it to.
923+
let resolved = super::resolve_uri_spelling(&uri);
924+
if resolved != uri {
925+
let mut aliases = self.document_aliases.write().await;
926+
let spellings = aliases.entry(resolved).or_default();
927+
if !spellings.contains(&uri) {
928+
spellings.push(uri.clone());
929+
}
930+
}
931+
872932
// Send update to index worker for cross-file analysis
873-
if let Ok(path) = uri.to_file_path() {
933+
if let Some(path) = super::resolve_uri(&uri) {
874934
let _ = self
875935
.update_tx
876936
.send(IndexUpdate::FileChanged {
@@ -898,7 +958,7 @@ impl LanguageServer for RumdlLanguageServer {
898958
self.documents.write().await.insert(uri.clone(), entry);
899959

900960
// Send update to index worker for cross-file analysis
901-
if let Ok(path) = uri.to_file_path() {
961+
if let Some(path) = super::resolve_uri(&uri) {
902962
let _ = self
903963
.update_tx
904964
.send(IndexUpdate::FileChanged {
@@ -964,6 +1024,18 @@ impl LanguageServer for RumdlLanguageServer {
9641024
async fn did_close(&self, params: DidCloseTextDocumentParams) {
9651025
// Remove document from storage
9661026
self.documents.write().await.remove(&params.text_document.uri);
1027+
// Drop only this spelling. Another one naming the same file can still be
1028+
// open, and it stays reachable under the resolved URI.
1029+
let resolved = super::resolve_uri_spelling(&params.text_document.uri);
1030+
if resolved != params.text_document.uri {
1031+
let mut aliases = self.document_aliases.write().await;
1032+
if let Some(spellings) = aliases.get_mut(&resolved) {
1033+
spellings.retain(|u| u != &params.text_document.uri);
1034+
if spellings.is_empty() {
1035+
aliases.remove(&resolved);
1036+
}
1037+
}
1038+
}
9671039

9681040
// Always clear diagnostics on close to ensure cleanup
9691041
// (Ruff does this unconditionally as a defensive measure)
@@ -990,7 +1062,10 @@ impl LanguageServer for RumdlLanguageServer {
9901062
let reads_editorconfig = self.reads_editorconfig().await;
9911063

9921064
for change in &params.changes {
993-
if let Ok(path) = change.uri.to_file_path() {
1065+
// Resolved like every other path the server records, so a watch event
1066+
// is comparable with the workspace roots and with the index keys the
1067+
// scan produced. A deleted file still resolves: only its directory is.
1068+
if let Some(path) = super::resolve_uri(&change.uri) {
9941069
let file_name = path.file_name().and_then(|f| f.to_str());
9951070

9961071
// Handle config file changes

0 commit comments

Comments
 (0)