use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs;
use std::io::{self, Read};
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
pub const SCHEMA: u32 = 2;
const EXTRACTOR: &str = include_str!("catalog/extract.el");
const TIMEOUT: Duration = Duration::from_secs(60);
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Function {
pub name: String,
pub kind: String,
pub usage: Option<String>,
pub doc: Option<String>,
pub file: Option<String>,
pub autoload: bool,
pub alias: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Variable {
pub name: String,
pub special: bool,
pub constant: bool,
pub doc: Option<String>,
pub file: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Extracted {
pub schema: u32,
pub version: String,
pub lisp_directory: String,
pub data_directory: String,
pub source_directory: Option<String>,
pub load_path: Vec<String>,
pub features: Vec<String>,
pub loaded_during_extraction: Vec<String>,
pub functions: Vec<Function>,
pub variables: Vec<Variable>,
}
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct Stored {
schema: u32,
emacs: PathBuf,
mtime: i64,
mtime_nsec: i64,
size: u64,
stdlib: String,
catalog: Extracted,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
Function,
Subr,
Macro,
SpecialForm,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Source {
Lisp(PathBuf),
C { file: String, path: Option<PathBuf> },
Unknown,
}
pub struct Catalog {
pub emacs: PathBuf,
pub key: String,
pub cache_file: PathBuf,
pub data: Extracted,
functions: HashMap<String, usize>,
variables: HashMap<String, usize>,
libraries: HashMap<String, PathBuf>,
}
#[derive(Debug)]
pub struct Built {
pub catalog: Catalog,
pub cached: bool,
pub duration: Duration,
}
impl std::fmt::Debug for Catalog {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Catalog")
.field("emacs", &self.emacs)
.field("key", &self.key)
.finish_non_exhaustive()
}
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}
pub fn cache_dir() -> io::Result<PathBuf> {
let base = std::env::var_os("XDG_CACHE_HOME")
.map(PathBuf::from)
.filter(|path| path.is_absolute())
.or_else(|| {
std::env::var_os("HOME")
.map(PathBuf::from)
.filter(|path| path.is_absolute())
.map(|home| home.join(".cache"))
})
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "No cache directory"))?;
Ok(base.join("elsmith"))
}
fn executable(path: &Path) -> bool {
fs::metadata(path).is_ok_and(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0)
}
pub fn locate_emacs(
explicit: Option<&Path>,
configured: Option<&Path>,
excluded_roots: &[PathBuf],
) -> io::Result<PathBuf> {
let invalid = |message: String| io::Error::new(io::ErrorKind::InvalidInput, message);
for (origin, path) in [("--emacs", explicit), ("emacs_path", configured)] {
if let Some(path) = path {
if !path.is_absolute() {
return Err(invalid(format!(
"{origin} must be an absolute path: {}",
path.display()
)));
}
if !executable(path) {
return Err(invalid(format!(
"{origin} is not an executable file: {}",
path.display()
)));
}
return fs::canonicalize(path);
}
}
let search = std::env::var_os("PATH").unwrap_or_default();
for dir in std::env::split_paths(&search) {
if !dir.is_absolute() {
continue;
}
let candidate = dir.join("emacs");
if !executable(&candidate) {
continue;
}
let Ok(real) = fs::canonicalize(&candidate) else {
continue;
};
let inside = |root: &PathBuf| {
fs::canonicalize(root)
.is_ok_and(|root| real.starts_with(&root) || dir.starts_with(&root))
};
if excluded_roots.iter().any(inside) {
continue;
}
return Ok(real);
}
Err(io::Error::new(
io::ErrorKind::NotFound,
"Emacs was not found in the user configuration or the system PATH",
))
}
fn emacs_key(emacs: &Path) -> io::Result<(String, fs::Metadata)> {
let meta = fs::metadata(emacs)?;
let mut hasher = Sha256::new();
hasher.update(SCHEMA.to_le_bytes());
hasher.update(emacs.as_os_str().as_encoded_bytes());
hasher.update([0]);
hasher.update(meta.mtime().to_le_bytes());
hasher.update(meta.mtime_nsec().to_le_bytes());
hasher.update(meta.size().to_le_bytes());
Ok((hex(&hasher.finalize()[..8]), meta))
}
fn stdlib_fingerprint(load_path: &[String]) -> String {
let mut hasher = Sha256::new();
for dir in load_path {
hasher.update(dir.as_bytes());
hasher.update([0]);
if let Ok(meta) = fs::metadata(dir) {
hasher.update(meta.mtime().to_le_bytes());
hasher.update(meta.mtime_nsec().to_le_bytes());
hasher.update(meta.ino().to_le_bytes());
}
hasher.update([1]);
}
hex(&hasher.finalize()[..16])
}
pub fn extract(emacs: &Path) -> io::Result<Extracted> {
let work = tempfile::tempdir()?;
let scripts = tempfile::tempdir()?;
let script = scripts.path().join("extract.el");
fs::write(&script, EXTRACTOR)?;
let mut child = Command::new(emacs)
.arg("-Q")
.arg("--batch")
.arg("-l")
.arg(&script)
.current_dir(work.path())
.env_clear()
.env("HOME", work.path())
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()?;
let mut stderr = child.stderr.take().expect("stderr is piped");
let reader = std::thread::spawn(move || {
let mut text = String::new();
let _ = stderr.read_to_string(&mut text);
text
});
let started = Instant::now();
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if started.elapsed() > TIMEOUT {
let _ = child.kill();
let _ = child.wait();
return Err(io::Error::new(
io::ErrorKind::TimedOut,
"Emacs did not finish the catalog extraction",
));
}
std::thread::sleep(Duration::from_millis(5));
};
let errors = reader.join().unwrap_or_default();
if !status.success() {
let tail: String = errors.lines().rev().take(3).collect::<Vec<_>>().join(" | ");
return Err(io::Error::other(format!(
"Emacs exited with {status} during the catalog extraction: {tail}"
)));
}
let bytes = fs::read(work.path().join("catalog.json"))?;
let text = String::from_utf8_lossy(&bytes);
let data: Extracted = serde_json::from_str(&text)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
if data.schema != SCHEMA {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"The catalog extractor reported another schema",
));
}
Ok(data)
}
fn write_atomic(path: &Path, bytes: &[u8], mode: u32) -> io::Result<()> {
let dir = path.parent().expect("cache files have a parent");
fs::create_dir_all(dir)?;
let mut temp = tempfile::NamedTempFile::new_in(dir)?;
io::Write::write_all(&mut temp, bytes)?;
temp.as_file()
.set_permissions(fs::Permissions::from_mode(mode))?;
temp.persist(path).map_err(|err| err.error)?;
Ok(())
}
impl Catalog {
pub fn from_data(emacs: PathBuf, key: String, cache_file: PathBuf, data: Extracted) -> Self {
let functions = data
.functions
.iter()
.enumerate()
.map(|(index, function)| (function.name.clone(), index))
.collect();
let variables = data
.variables
.iter()
.enumerate()
.map(|(index, variable)| (variable.name.clone(), index))
.collect();
let mut libraries = HashMap::new();
for dir in &data.load_path {
let Ok(entries) = fs::read_dir(dir) else {
continue;
};
let mut names: Vec<PathBuf> = entries
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
.collect();
names.sort();
for path in names {
let Some(file) = path.file_name().and_then(OsStr::to_str) else {
continue;
};
let stem = file
.strip_suffix(".el.gz")
.or_else(|| file.strip_suffix(".el"));
if let Some(stem) = stem {
let plain = file.ends_with(".el");
match libraries.entry(stem.to_owned()) {
std::collections::hash_map::Entry::Vacant(slot) => {
slot.insert(path);
}
std::collections::hash_map::Entry::Occupied(mut slot) => {
if plain && slot.get().parent() == path.parent() {
slot.insert(path);
}
}
}
}
}
}
Self {
emacs,
key,
cache_file,
data,
functions,
variables,
libraries,
}
}
pub fn load_or_build(emacs: &Path, cache: &Path, force: bool) -> io::Result<Built> {
let started = Instant::now();
let (key, meta) = emacs_key(emacs)?;
let cache_file = cache.join("catalog").join(format!("{key}.json"));
if !force && let Some(catalog) = Self::load(emacs, &key, &cache_file, &meta) {
return Ok(Built {
catalog,
cached: true,
duration: started.elapsed(),
});
}
let data = extract(emacs)?;
let stored = Stored {
schema: SCHEMA,
emacs: emacs.to_owned(),
mtime: meta.mtime(),
mtime_nsec: meta.mtime_nsec(),
size: meta.size(),
stdlib: stdlib_fingerprint(&data.load_path),
catalog: data,
};
let bytes = serde_json::to_vec(&stored)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
write_atomic(&cache_file, &bytes, 0o644)?;
Ok(Built {
catalog: Self::from_data(emacs.to_owned(), key, cache_file, stored.catalog),
cached: false,
duration: started.elapsed(),
})
}
fn load(emacs: &Path, key: &str, cache_file: &Path, meta: &fs::Metadata) -> Option<Self> {
let bytes = fs::read(cache_file).ok()?;
let stored: Stored = serde_json::from_slice(&bytes).ok()?;
let valid = stored.schema == SCHEMA
&& stored.emacs == emacs
&& stored.mtime == meta.mtime()
&& stored.mtime_nsec == meta.mtime_nsec()
&& stored.size == meta.size()
&& stored.stdlib == stdlib_fingerprint(&stored.catalog.load_path);
valid.then(|| {
Self::from_data(
emacs.to_owned(),
key.to_owned(),
cache_file.to_owned(),
stored.catalog,
)
})
}
pub fn cached(emacs: &Path, cache: &Path) -> io::Result<Option<Self>> {
let (key, meta) = emacs_key(emacs)?;
let cache_file = cache.join("catalog").join(format!("{key}.json"));
Ok(Self::load(emacs, &key, &cache_file, &meta))
}
pub fn function(&self, name: &str) -> Option<&Function> {
self.functions
.get(name)
.map(|index| &self.data.functions[*index])
}
pub fn variable(&self, name: &str) -> Option<&Variable> {
self.variables
.get(name)
.map(|index| &self.data.variables[*index])
}
pub fn kind(&self, name: &str) -> Option<Kind> {
let function = self.function(name)?;
Some(match function.kind.as_str() {
"special-form" => Kind::SpecialForm,
"macro" => Kind::Macro,
"subr" => Kind::Subr,
_ => Kind::Function,
})
}
pub fn libraries(&self) -> impl Iterator<Item = &str> {
self.libraries.keys().map(String::as_str)
}
pub fn library(&self, name: &str) -> Option<&Path> {
self.libraries.get(name).map(PathBuf::as_path)
}
fn lisp_source(&self, file: &str) -> Option<PathBuf> {
let path = Path::new(file);
if path.is_absolute() {
let text = file.strip_suffix(".elc").unwrap_or(file);
let text = text.strip_suffix(".el").unwrap_or(text);
return ["el", "el.gz"]
.iter()
.map(|extension| PathBuf::from(format!("{text}.{extension}")))
.find(|candidate| candidate.is_file());
}
let name = file.strip_suffix(".elc").unwrap_or(file);
let name = name.strip_suffix(".el").unwrap_or(name);
let base = Path::new(&self.data.lisp_directory);
["el", "el.gz"]
.iter()
.map(|extension| base.join(format!("{name}.{extension}")))
.find(|candidate| candidate.is_file())
.or_else(|| {
let stem = Path::new(name).file_name()?.to_str()?;
self.libraries.get(stem).cloned()
})
}
pub fn c_source(&self, file: &str) -> Option<PathBuf> {
let lisp = Path::new(&self.data.lisp_directory);
let mut roots: Vec<PathBuf> = lisp.parent().map(Path::to_path_buf).into_iter().collect();
roots.extend(self.data.source_directory.as_deref().map(PathBuf::from));
roots
.into_iter()
.map(|root| root.join(file))
.find(|path| path.is_file())
}
pub fn function_source(&self, name: &str) -> Source {
let Some(function) = self.function(name) else {
return Source::Unknown;
};
if let Some(alias) = &function.alias
&& alias != name
&& function.file.is_none()
{
return self.function_source(alias);
}
match (&function.kind[..], &function.file) {
("subr" | "special-form", Some(file)) => Source::C {
file: file.clone(),
path: self.c_source(file),
},
(_, Some(file)) => self.lisp_source(file).map_or(Source::Unknown, Source::Lisp),
_ => Source::Unknown,
}
}
pub fn variable_source(&self, name: &str) -> Source {
let Some(file) = self
.variable(name)
.and_then(|variable| variable.file.as_ref())
else {
return Source::Unknown;
};
if file.ends_with(".c") {
return Source::C {
file: file.clone(),
path: self.c_source(file),
};
}
self.lisp_source(file).map_or(Source::Unknown, Source::Lisp)
}
pub fn stdlib_dir(&self, cache: &Path) -> PathBuf {
cache.join("stdlib").join(&self.key)
}
pub fn openable(&self, source: &Path, cache: &Path) -> io::Result<PathBuf> {
let Some(name) = source.to_str().and_then(|text| text.strip_suffix(".gz")) else {
return Ok(source.to_owned());
};
let relative = Path::new(name)
.strip_prefix(&self.data.lisp_directory)
.map(Path::to_path_buf)
.unwrap_or_else(|_| {
let mut hasher = Sha256::new();
hasher.update(
source
.parent()
.unwrap_or(source)
.as_os_str()
.as_encoded_bytes(),
);
let dir = hex(&hasher.finalize()[..8]);
Path::new("site")
.join(dir)
.join(Path::new(name).file_name().unwrap_or_default())
});
let target = self.stdlib_dir(cache).join(relative);
if target.is_file() {
return Ok(target);
}
let mut text = Vec::new();
flate2::read::GzDecoder::new(fs::File::open(source)?).read_to_end(&mut text)?;
write_atomic(&target, &text, 0o444)?;
Ok(target)
}
}
pub fn c_definition(text: &str, name: &str, variable: bool) -> Option<(usize, usize)> {
let needle = format!("(\"{name}\"");
let mut from = 0;
while let Some(found) = text[from..].find(&needle) {
let at = from + found;
let line_start = text[..at].rfind('\n').map_or(0, |index| index + 1);
let prefix = text[line_start..at].trim();
let matches = if variable {
prefix.starts_with("DEFVAR_")
} else {
prefix == "DEFUN"
};
if matches {
return Some((at + 1, at + 1 + name.len() + 2));
}
from = at + needle.len();
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_c_definitions() {
let text = "/* x */\nDEFUN (\"car\", Fcar, Scar, 1, 1, 0,\n doc: /* x */)\n DEFVAR_LISP (\"load-path\", Vload_path,\n";
let (start, end) = c_definition(text, "car", false).unwrap();
assert_eq!(&text[start..end], "\"car\"");
let (start, end) = c_definition(text, "load-path", true).unwrap();
assert_eq!(&text[start..end], "\"load-path\"");
assert!(c_definition(text, "cdr", false).is_none());
assert!(c_definition(text, "car", true).is_none());
}
#[test]
fn rejects_relative_and_workspace_emacs() {
let dir = tempfile::tempdir().unwrap();
let err = locate_emacs(Some(Path::new("emacs")), None, &[]).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
let fake = dir.path().join("emacs");
fs::write(&fake, "").unwrap();
fs::set_permissions(&fake, fs::Permissions::from_mode(0o755)).unwrap();
assert_eq!(
locate_emacs(Some(&fake), None, &[]).unwrap(),
fs::canonicalize(&fake).unwrap()
);
}
}