use super::{Doc, canonical_dir_of};
use lsp_types::Uri;
use std::cell::RefCell;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::str::FromStr;
pub(super) type Root = (PathBuf, PathBuf);
pub(super) fn roots_of(workspace: &[PathBuf]) -> Vec<Root> {
workspace.iter().map(|w| (normal(w), w.clone())).collect()
}
pub(super) fn normal(p: &Path) -> PathBuf {
std::fs::canonicalize(p).unwrap_or_else(|_| canonical_dir_of(p))
}
fn uri_of(path: &Path) -> Option<Uri> {
let url = url::Url::from_file_path(path).ok()?;
Uri::from_str(url.as_str()).ok()
}
pub(super) struct Spelling<'a> {
open: &'a HashMap<Uri, Doc>,
roots: &'a [Root],
here: Option<&'a Uri>,
made: RefCell<HashMap<PathBuf, Option<Uri>>>,
}
impl<'a> Spelling<'a> {
#[allow(clippy::mutable_key_type)]
pub(super) fn new(open: &'a HashMap<Uri, Doc>, roots: &'a [Root]) -> Self {
Self {
open,
roots,
here: None,
made: RefCell::new(HashMap::new()),
}
}
pub(super) fn asked_from(self, uri: &'a Uri) -> Self {
Self {
here: Some(uri),
..self
}
}
pub(super) fn client_uri(&self, p: &Path) -> Option<Uri> {
self.remembered(p, || {
normal(&std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf()))
})
}
pub(super) fn client_uri_canonical(&self, canonical: &Path) -> Option<Uri> {
self.remembered(canonical, || canonical.to_path_buf())
}
fn remembered(&self, p: &Path, real: impl FnOnce() -> PathBuf) -> Option<Uri> {
if let Some(known) = self.made.borrow().get(p) {
return known.clone();
}
let uri = self.spelled(&real());
self.made.borrow_mut().insert(p.to_path_buf(), uri.clone());
uri
}
fn spelled(&self, real: &Path) -> Option<Uri> {
if let Some(here) = self.here
&& self.open.get(here).is_some_and(|d| d.canonical == real)
{
return Some(here.clone());
}
if let Some(uri) = self
.open
.iter()
.filter(|(_, d)| d.canonical == real)
.map(|(u, _)| u)
.min()
{
return Some(uri.clone());
}
let mut best: Option<(usize, PathBuf)> = None;
for (root_real, root_spelled) in self.roots {
let Ok(rest) = real.strip_prefix(root_real) else {
continue;
};
let depth = root_real.components().count();
if best.as_ref().is_none_or(|(d, _)| depth > *d) {
let under = if rest.as_os_str().is_empty() {
root_spelled.clone()
} else {
root_spelled.join(rest)
};
best = Some((depth, under));
}
}
if let Some(uri) = best.and_then(|(_, under)| uri_of(&under)) {
return Some(uri);
}
uri_of(real)
}
}
#[cfg(test)]
#[allow(clippy::mutable_key_type)]
mod tests {
use super::super::path_of;
use super::*;
use std::collections::HashSet;
fn doc(path: &str, canonical: &str) -> Doc {
Doc {
path: PathBuf::from(path),
canonical: PathBuf::from(canonical),
project: None,
deps: HashSet::new(),
buffer: None,
unsynced: false,
checked: None,
}
}
fn uri(s: &str) -> Uri {
Uri::from_str(s).unwrap()
}
fn root(real: &str, spelled: &str) -> Root {
(PathBuf::from(real), PathBuf::from(spelled))
}
#[test]
fn a_path_and_its_uri_name_each_other() {
let path = Path::new("/work/my project/é.tl");
let uri = uri_of(path).unwrap();
assert_eq!(uri.as_str(), "file:///work/my%20project/%C3%A9.tl");
assert_eq!(path_of(&uri).as_deref(), Some(path));
assert_eq!(
path_of(&Uri::from_str("untitled:Untitled-1").unwrap()),
None
);
assert_eq!(uri_of(Path::new("a.tl")), None);
}
#[test]
fn an_open_file_is_named_by_the_uri_it_was_opened_with() {
let key = uri("file:///c%3A/work/a.tl");
let open = HashMap::from([(key.clone(), doc("/c:/work/a.tl", "/real/work/a.tl"))]);
let roots = [root("/real/work", "/link")];
let s = Spelling::new(&open, &roots);
assert_eq!(
s.client_uri(Path::new("/real/work/a.tl")),
Some(key.clone())
);
assert_eq!(
s.client_uri_canonical(Path::new("/real/work/a.tl")),
Some(key)
);
assert_eq!(
s.client_uri(Path::new("/real/work/b.tl")),
Some(uri("file:///link/b.tl"))
);
}
#[test]
fn a_file_open_under_two_uris_is_named_by_the_smaller() {
let (a, b) = (uri("file:///link/a.tl"), uri("file:///real/a.tl"));
let open = HashMap::from([
(b.clone(), doc("/real/a.tl", "/real/a.tl")),
(a.clone(), doc("/link/a.tl", "/real/a.tl")),
]);
let s = Spelling::new(&open, &[]);
assert_eq!(s.client_uri(Path::new("/real/a.tl")), Some(a.clone()));
let s = Spelling::new(&open, &[]).asked_from(&b);
assert_eq!(s.client_uri(Path::new("/real/a.tl")), Some(b));
let other = uri("file:///real/other.tl");
let s = Spelling::new(&open, &[]).asked_from(&other);
assert_eq!(s.client_uri(Path::new("/real/a.tl")), Some(a));
}
#[test]
fn the_longest_root_wins_and_the_first_of_equals() {
let open = HashMap::new();
let roots = [
root("/real", "/outer"),
root("/real/inner", "/inner"),
root("/real/inner", "/second"),
root("/real/in", "/wrong"),
];
let s = Spelling::new(&open, &roots);
assert_eq!(
s.client_uri(Path::new("/real/inner/x/y.tl")),
Some(uri("file:///inner/x/y.tl"))
);
assert_eq!(
s.client_uri(Path::new("/real/other.tl")),
Some(uri("file:///outer/other.tl"))
);
assert_eq!(
s.client_uri(Path::new("/real/inner")),
Some(uri("file:///inner"))
);
}
#[test]
fn a_file_under_no_root_is_named_by_its_real_path() {
let open = HashMap::new();
let roots = [root("/real/work", "/link")];
let s = Spelling::new(&open, &roots);
assert_eq!(
s.client_uri(Path::new("/elsewhere/a.tl")),
Some(uri("file:///elsewhere/a.tl"))
);
assert_eq!(
s.client_uri(Path::new("/real/workshop/a.tl")),
Some(uri("file:///real/workshop/a.tl"))
);
assert!(s.client_uri(Path::new("relative/a.tl")).is_some());
}
#[test]
fn no_other_file_of_the_server_makes_a_uri_from_a_path() {
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut files = vec![src.join("lsp.rs")];
for e in std::fs::read_dir(src.join("lsp")).unwrap() {
let path = e.unwrap().path();
if path.extension().is_some_and(|x| x == "rs")
&& path.file_name().is_some_and(|n| n != "spelling.rs")
{
files.push(path);
}
}
assert!(files.len() >= 4, "{files:?}");
for f in files {
let text = std::fs::read_to_string(&f).unwrap();
assert!(!text.contains("from_file_path"), "{}", f.display());
}
}
}