elsmith 0.1.0

An Emacs Lisp language server with Lean-verified protocol and editing rules
Documentation
use std::collections::{BTreeMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use notify::{RecommendedWatcher, RecursiveMode, Watcher};

use crate::analysis::{Analysis, Role, Space, analyze};
use crate::project::Environment;
use crate::syntax::Tree;

const MAX_FILE_BYTES: u64 = 4 << 20;
const MAX_WATCHED_DIRS: usize = 4096;

pub struct FileIndex {
    pub uri: String,
    pub path: PathBuf,
    pub text: String,
    pub tree: Tree,
    pub analysis: Analysis,
    pub dependency: bool,
}

impl FileIndex {
    fn read(path: &Path, dependency: bool) -> Option<Self> {
        let meta = fs::metadata(path).ok()?;
        if !meta.is_file() || meta.len() > MAX_FILE_BYTES {
            return None;
        }
        let text = String::from_utf8(fs::read(path).ok()?).ok()?;
        let uri = url::Url::from_file_path(path).ok()?.to_string();
        let tree = Tree::parse_str(&text);
        let analysis = analyze(&text, &tree);
        Some(Self {
            uri,
            path: path.to_owned(),
            text,
            tree,
            analysis,
            dependency,
        })
    }

    pub fn provides(&self) -> impl Iterator<Item = &str> {
        self.analysis
            .definitions
            .iter()
            .filter(|definition| definition.space == Space::Feature)
            .map(|definition| definition.name.as_str())
    }
}

pub fn requires(analysis: &Analysis) -> impl Iterator<Item = &str> {
    analysis
        .occurrences
        .iter()
        .filter(|occurrence| {
            occurrence.space == Space::Feature && occurrence.role == Role::Reference
        })
        .map(|occurrence| occurrence.name.as_str())
}

pub struct Workspace {
    pub environments: Vec<Environment>,
    files: BTreeMap<PathBuf, FileIndex>,
    unindexed: HashSet<PathBuf>,
    roots: Vec<PathBuf>,
    dependency_dirs: Vec<PathBuf>,
    watched: HashSet<PathBuf>,
    watcher: Option<RecommendedWatcher>,
    changes: Arc<Mutex<HashSet<PathBuf>>>,
}

fn is_elisp(path: &Path) -> bool {
    path.extension().is_some_and(|extension| extension == "el")
        && !path
            .file_name()
            .and_then(|name| name.to_str())
            .is_some_and(|name| name.starts_with(".#") || name == ".dir-locals.el")
}

impl Workspace {
    pub fn build(environments: Vec<Environment>, watch: bool) -> Self {
        let changes = Arc::new(Mutex::new(HashSet::new()));
        let watcher = if watch {
            let sink = Arc::clone(&changes);
            notify::recommended_watcher(move |event: notify::Result<notify::Event>| {
                if let Ok(event) = event
                    && !matches!(event.kind, notify::EventKind::Access(_))
                    && let Ok(mut set) = sink.lock()
                {
                    set.extend(event.paths);
                }
            })
            .ok()
        } else {
            None
        };
        let roots = environments.iter().map(|env| env.root.clone()).collect();
        let mut workspace = Self {
            environments,
            files: BTreeMap::new(),
            unindexed: HashSet::new(),
            roots,
            dependency_dirs: Vec::new(),
            watched: HashSet::new(),
            watcher,
            changes,
        };
        for index in 0..workspace.environments.len() {
            let root = workspace.environments[index].root.clone();
            workspace.walk(&root, index);
            let dirs: Vec<PathBuf> = workspace.environments[index]
                .load_paths
                .iter()
                .map(|entry| entry.path.clone())
                .collect();
            for dir in dirs {
                workspace.dependency(&dir);
            }
        }
        workspace
    }

    fn watch(&mut self, dir: &Path) {
        if self.watched.len() >= MAX_WATCHED_DIRS || self.watched.contains(dir) {
            return;
        }
        if let Some(watcher) = &mut self.watcher
            && watcher.watch(dir, RecursiveMode::NonRecursive).is_ok()
        {
            self.watched.insert(dir.to_owned());
        }
    }

    fn walk(&mut self, root: &Path, env: usize) {
        let ignored = self.environments[env].ignored.clone();
        let walker = ignore::WalkBuilder::new(root)
            .require_git(false)
            .filter_entry(move |entry| !ignored.iter().any(|path| entry.path().starts_with(path)))
            .build();
        for entry in walker.flatten() {
            let path = entry.path();
            match entry.file_type() {
                Some(kind) if kind.is_dir() => self.watch(path),
                Some(kind) if kind.is_file() && is_elisp(path) => {
                    if let Some(file) = FileIndex::read(path, false) {
                        self.unindexed.remove(path);
                        self.files.insert(path.to_owned(), file);
                    } else {
                        self.unindexed.insert(path.to_owned());
                    }
                }
                _ => {}
            }
        }
    }

    fn inside_roots(&self, path: &Path) -> bool {
        self.roots.iter().any(|root| path.starts_with(root))
    }

    fn dependency(&mut self, dir: &Path) {
        let Ok(entries) = fs::read_dir(dir) else {
            return;
        };
        let external = !self.inside_roots(dir)
            || dir.components().any(|part| {
                part.as_os_str()
                    .to_str()
                    .is_some_and(|name| matches!(name, ".keg" | ".eask" | ".cask"))
            });
        if !external {
            return;
        }
        self.dependency_dirs.push(dir.to_owned());
        self.watch(dir);
        for entry in entries.flatten() {
            let path = entry.path();
            if is_elisp(&path)
                && !self.files.contains_key(&path)
                && let Some(file) = FileIndex::read(&path, true)
            {
                self.files.insert(path, file);
            }
        }
    }

    pub fn mark_changed(&self, path: PathBuf) {
        let path = fs::canonicalize(&path).unwrap_or_else(|_| {
            match (
                path.parent()
                    .and_then(|parent| fs::canonicalize(parent).ok()),
                path.file_name(),
            ) {
                (Some(parent), Some(name)) => parent.join(name),
                _ => path.clone(),
            }
        });
        if let Ok(mut set) = self.changes.lock() {
            set.insert(path);
        }
    }

    pub fn refresh(&mut self) -> usize {
        let changed: Vec<PathBuf> = match self.changes.lock() {
            Ok(mut set) => set.drain().collect(),
            Err(_) => return 0,
        };
        let mut updated = 0;
        for path in changed {
            let dependency = path
                .parent()
                .is_some_and(|parent| self.dependency_dirs.iter().any(|dir| dir == parent));
            let ignored = self.environments.iter().any(|env| env.is_ignored(&path));
            if ignored || !(dependency || self.inside_roots(&path)) {
                continue;
            }
            if path.is_dir() {
                if !dependency
                    && !self.watched.contains(&path)
                    && let Some(env) = self
                        .environments
                        .iter()
                        .position(|env| path.starts_with(&env.root))
                {
                    self.walk(&path, env);
                    updated += 1;
                }
                continue;
            }
            if !is_elisp(&path) {
                continue;
            }
            match FileIndex::read(&path, dependency) {
                Some(file)
                    if self.files.get(&path).is_some_and(|old| {
                        old.text == file.text && old.dependency == file.dependency
                    }) => {}
                Some(file) => {
                    self.unindexed.remove(&path);
                    self.files.insert(path, file);
                    updated += 1;
                }
                None => {
                    if !dependency && path.is_file() {
                        self.unindexed.insert(path.clone());
                    } else {
                        self.unindexed.remove(&path);
                    }
                    updated += usize::from(self.files.remove(&path).is_some());
                }
            }
        }
        updated
    }

    pub(crate) fn has_unindexed_sources(&self) -> bool {
        self.unindexed.iter().any(|path| path.exists())
    }

    pub fn files(&self) -> impl Iterator<Item = &FileIndex> {
        self.files.values()
    }

    pub fn len(&self) -> usize {
        self.files.len()
    }

    pub fn is_empty(&self) -> bool {
        self.files.is_empty()
    }

    pub fn watched(&self) -> usize {
        self.watched.len()
    }

    pub fn by_uri(&self, uri: &str) -> Option<&FileIndex> {
        let path = url::Url::parse(uri).ok()?.to_file_path().ok()?;
        self.files
            .get(&path)
            .or_else(|| self.files.get(&fs::canonicalize(&path).ok()?))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::project::LoadPath;

    #[test]
    fn indexes_roots_and_dependencies_and_respects_ignores() {
        let dir = tempfile::tempdir().unwrap();
        let root = fs::canonicalize(dir.path()).unwrap();
        fs::create_dir_all(root.join("lisp")).unwrap();
        fs::create_dir_all(root.join("build")).unwrap();
        fs::create_dir_all(root.join(".keg/31.1/elpa/dep-1.0")).unwrap();
        fs::write(root.join(".gitignore"), "build/\n.keg/\n").unwrap();
        fs::write(root.join("lisp/a.el"), "(defun a-one () 1)\n(provide 'a)\n").unwrap();
        fs::write(root.join("build/b.el"), "(defun b-one () 1)\n").unwrap();
        fs::write(
            root.join(".keg/31.1/elpa/dep-1.0/dep.el"),
            "(defun dep-one () 1)\n(provide 'dep)\n",
        )
        .unwrap();
        let env = Environment {
            root: root.clone(),
            load_paths: vec![LoadPath {
                path: root.join(".keg/31.1/elpa/dep-1.0"),
                source: "Keg",
            }],
            ignored: Vec::new(),
            notes: Vec::new(),
        };
        let mut workspace = Workspace::build(vec![env], false);
        let mut names: Vec<(String, bool)> = workspace
            .files()
            .map(|file| {
                (
                    file.path.strip_prefix(&root).unwrap().display().to_string(),
                    file.dependency,
                )
            })
            .collect();
        names.sort();
        assert_eq!(
            names,
            vec![
                (".keg/31.1/elpa/dep-1.0/dep.el".to_owned(), true),
                ("lisp/a.el".to_owned(), false),
            ]
        );
        fs::write(root.join("lisp/a.el"), "(defun a-two () 2)\n").unwrap();
        fs::write(root.join("lisp/c.el"), "(defun c-one () 1)\n").unwrap();
        workspace.mark_changed(root.join("lisp/a.el"));
        workspace.mark_changed(root.join("lisp/c.el"));
        assert_eq!(workspace.refresh(), 2);
        let a = workspace
            .by_uri(
                url::Url::from_file_path(root.join("lisp/a.el"))
                    .unwrap()
                    .as_str(),
            )
            .unwrap();
        assert_eq!(a.analysis.definitions[0].name, "a-two");
        assert_eq!(workspace.len(), 3);
        fs::remove_file(root.join("lisp/c.el")).unwrap();
        workspace.mark_changed(root.join("lisp/c.el"));
        workspace.refresh();
        assert_eq!(workspace.len(), 2);
    }

    #[test]
    fn notify_watches_directories_without_recursion() {
        let dir = tempfile::tempdir().unwrap();
        let root = fs::canonicalize(dir.path()).unwrap();
        fs::create_dir_all(root.join("lisp")).unwrap();
        let env = Environment {
            root: root.clone(),
            ..Environment::default()
        };
        let mut workspace = Workspace::build(vec![env], true);
        assert_eq!(workspace.watched(), 2);
        fs::write(root.join("lisp/new.el"), "(defun new-one () 1)\n").unwrap();
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        while workspace.is_empty() && std::time::Instant::now() < deadline {
            std::thread::sleep(std::time::Duration::from_millis(20));
            workspace.refresh();
        }
        assert_eq!(workspace.len(), 1);
    }
}