elsmith 0.1.1

An Emacs Lisp language server with Lean-verified protocol and editing rules
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
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()
        );
    }
}