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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::{env, fs};

use serde_json::{Value, json};

fn binary() -> Command {
    Command::new(env!("CARGO_BIN_EXE_elsmith"))
}

fn send(input: &mut impl Write, bytes: &[u8]) {
    write!(input, "Content-Length: {}\r\n\r\n", bytes.len()).unwrap();
    input.write_all(bytes).unwrap();
}

fn responses(mut bytes: &[u8]) -> Vec<Value> {
    let mut messages = Vec::new();
    while !bytes.is_empty() {
        let separator = bytes.windows(4).position(|w| w == b"\r\n\r\n").unwrap();
        let header = str::from_utf8(&bytes[..separator]).unwrap();
        let length = header
            .strip_prefix("Content-Length: ")
            .unwrap()
            .parse()
            .unwrap();
        let (body, rest) = bytes[separator + 4..].split_at(length);
        messages.push(serde_json::from_slice(body).unwrap());
        bytes = rest;
    }
    messages
}

fn shell() -> PathBuf {
    let path = env::var_os("PATH").unwrap_or_default();
    std::iter::once(PathBuf::from("/bin/sh"))
        .chain(env::split_paths(&path).map(|dir| dir.join("sh")))
        .find(|path| path.is_absolute() && path.is_file())
        .expect("the test needs a POSIX shell for its fake Emacs")
}

fn gzip(text: &str) -> Vec<u8> {
    let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
    encoder.write_all(text.as_bytes()).unwrap();
    encoder.finish().unwrap()
}

const SEQ: &str = "(defun fake-filter (pred sequence)\n  \"Keep elements of SEQUENCE matching PRED.\"\n  (delq nil (mapcar pred sequence)))\n(defun fake-autoloaded (x) x)\n(provide 'fake-seq)\n";

struct Install {
    _temp: tempfile::TempDir,
    root: PathBuf,
    emacs: PathBuf,
    lisp: PathBuf,
    logs: PathBuf,
    cache: PathBuf,
    config: PathBuf,
    workspace: PathBuf,
}

impl Install {
    fn new() -> Self {
        let temp = tempfile::tempdir().unwrap();
        let root = fs::canonicalize(temp.path()).unwrap();
        let share = root.join("install/share/emacs/31.1");
        let lisp = share.join("lisp");
        fs::create_dir_all(lisp.join("emacs-lisp")).unwrap();
        fs::create_dir_all(share.join("src")).unwrap();
        fs::write(lisp.join("emacs-lisp/fake-seq.el.gz"), gzip(SEQ)).unwrap();
        fs::write(
            lisp.join("subr.el"),
            "(defmacro when (cond &rest body)\n  \"If COND yields non-nil, do BODY.\"\n  (list 'if cond (cons 'progn body)))\n",
        )
        .unwrap();
        fs::write(
            share.join("src/data.c"),
            "#include <config.h>\n\nDEFUN (\"car\", Fcar, Scar, 1, 1, 0,\n       doc: /* Return the car of LIST.  */)\n",
        )
        .unwrap();
        let logs = root.join("logs");
        fs::create_dir_all(&logs).unwrap();
        let lisp_text = lisp.display().to_string();
        let function = |name: &str,
                        kind: &str,
                        usage: &str,
                        doc: &str,
                        file: &str,
                        autoload: bool| {
            json!({"name": name, "kind": kind, "usage": usage, "doc": doc, "file": file, "autoload": autoload, "alias": null})
        };
        let catalog = json!({
            "schema": 2,
            "version": "31.1",
            "lispDirectory": lisp_text,
            "dataDirectory": share.join("etc"),
            "sourceDirectory": null,
            "loadPath": [lisp_text, lisp.join("emacs-lisp")],
            "features": ["subr"],
            "loadedDuringExtraction": [],
            "functions": [
                function("fake-filter", "function", "(fake-filter PRED SEQUENCE)", "Keep elements of SEQUENCE matching PRED.", &format!("{lisp_text}/emacs-lisp/fake-seq.elc"), false),
                function("fake-autoloaded", "function", "(fake-autoloaded X)", "Autoloaded.", "emacs-lisp/fake-seq", true),
                function("car", "subr", "(car LIST)", "Return the car of LIST.", "src/data.c", false),
                function("mapcar", "subr", "(mapcar FUNCTION SEQUENCE)", "Apply FUNCTION to each element of SEQUENCE.", "src/fns.c", false),
                function("when", "macro", "(when COND &rest BODY)", "If COND yields non-nil, do BODY.", &format!("{lisp_text}/subr.elc"), false),
                function("if", "special-form", "(if COND THEN ELSE...)", "If COND yields non-nil, do THEN.", "src/eval.c", false),
            ],
            "variables": [
                {"name": "load-path", "special": true, "constant": false, "doc": "List of directories.", "file": "src/lread.c"},
            ],
        });
        let text = serde_json::to_string(&catalog).unwrap();
        assert!(!text.contains('\''));
        let logs_text = logs.display();
        let emacs = root.join("install/bin/emacs");
        fs::create_dir_all(emacs.parent().unwrap()).unwrap();
        fs::write(
            &emacs,
            format!(
                "#!{}\nprintf '%s\\n' \"$@\" > '{logs_text}/args.txt'\nexport -p > '{logs_text}/env.txt'\nprintf '%s\\n' \"$PWD\" > '{logs_text}/cwd.txt'\nprintf '%s\\n' * > '{logs_text}/listing.txt'\nprintf x >> '{logs_text}/count.txt'\nprintf '%s' '{text}' > catalog.json\n",
                shell().display()
            ),
        )
        .unwrap();
        fs::set_permissions(&emacs, fs::Permissions::from_mode(0o755)).unwrap();
        let workspace = root.join("workspace");
        fs::create_dir_all(&workspace).unwrap();
        fs::write(
            workspace.join("sibling.el"),
            "(defun sibling-old (x) x)\n(provide 'sibling)\n",
        )
        .unwrap();
        fs::write(
            workspace.join("disk.el"),
            "(defun disk-only (x)\n  \"Only on disk.\"\n  x)\n(provide 'disk)\n",
        )
        .unwrap();
        Self {
            root: root.clone(),
            emacs,
            lisp,
            logs,
            cache: root.join("cache"),
            config: root.join("config"),
            workspace,
            _temp: temp,
        }
    }

    fn command(&self) -> Command {
        let mut command = binary();
        command
            .env("PATH", "")
            .env("XDG_CACHE_HOME", &self.cache)
            .env("ELSMITH_CONFIG_DIR", &self.config)
            .env("EMACSLOADPATH", "/should/not/leak")
            .current_dir(&self.root);
        command
    }

    fn session(&self, emacs: Option<&Path>, messages: &[Value]) -> (Output, Vec<Value>) {
        self.session_with_path(emacs, Path::new(""), messages)
    }

    fn session_with_path(
        &self,
        emacs: Option<&Path>,
        path: &Path,
        messages: &[Value],
    ) -> (Output, Vec<Value>) {
        let mut command = self.command();
        command
            .env("PATH", path)
            .args(["server", "run-server", "--debug"]);
        if let Some(emacs) = emacs {
            command.arg("--emacs").arg(emacs);
        }
        let mut child = command
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();
        {
            let mut input = child.stdin.take().unwrap();
            for message in messages {
                send(&mut input, &serde_json::to_vec(message).unwrap());
            }
        }
        let output = child.wait_with_output().unwrap();
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        let replies = responses(&output.stdout);
        (output, replies)
    }

    fn main_session(&self, emacs: Option<&Path>, requests: &[(u32, &str, Value)]) -> Vec<Value> {
        let main = self.uri("main.el");
        let mut messages = initialize(
            &self.workspace,
            json!({"textDocument": {"hover": {"contentFormat": ["markdown"]}}}),
        )
        .to_vec();
        messages.push(open(&main, MAIN));
        messages.push(open(&self.uri("sibling.el"), SIBLING));
        for (id, method, params) in requests {
            let mut params = params.clone();
            params["textDocument"] = json!({"uri": main});
            messages.push(request(*id, method, params));
        }
        messages.extend(finish());
        self.session(emacs, &messages).1
    }

    fn uri(&self, name: &str) -> String {
        url::Url::from_file_path(self.workspace.join(name))
            .unwrap()
            .to_string()
    }
}

const MAIN: &str = ";;; main.el --- Main -*- lexical-binding: t -*-\n(require 'fake-seq)\n(defun main-run (items)\n  (fake-filter #'identity items)\n  (car items)\n  (mapcar #'1+ items)\n  (when items (fake-autoloaded items))\n  (sibling-new items)\n  (disk-only items))\n";
const SIBLING: &str = "(defun sibling-new (x)\n  \"New.\"\n  x)\n(provide 'sibling)\n";

fn at(text: &str, needle: &str) -> Value {
    let offset = text.find(needle).unwrap();
    let line = text[..offset].matches('\n').count();
    let column = offset - text[..offset].rfind('\n').map_or(0, |index| index + 1);
    json!({"line": line, "character": column})
}

fn request(id: u32, method: &str, params: Value) -> Value {
    json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})
}

fn open(uri: &str, text: &str) -> Value {
    json!({"jsonrpc": "2.0", "method": "textDocument/didOpen", "params": {"textDocument": {"uri": uri, "languageId": "emacs-lisp", "version": 1, "text": text}}})
}

fn initialize(root: &Path, capabilities: Value) -> [Value; 2] {
    let uri = url::Url::from_directory_path(root).unwrap();
    [
        request(
            1,
            "initialize",
            json!({"processId": null, "rootUri": uri.as_str(), "capabilities": capabilities}),
        ),
        json!({"jsonrpc": "2.0", "method": "initialized", "params": {}}),
    ]
}

fn finish() -> [Value; 2] {
    [
        request(999, "shutdown", Value::Null),
        json!({"jsonrpc": "2.0", "method": "exit"}),
    ]
}

fn by_id(replies: &[Value], id: u32) -> &Value {
    let reply = replies.iter().find(|reply| reply["id"] == id).unwrap();
    assert!(reply.get("error").is_none(), "{reply}");
    &reply["result"]
}

fn range_text(uri: &str, range: &Value) -> String {
    let path = url::Url::parse(uri).unwrap().to_file_path().unwrap();
    let text = fs::read_to_string(path).unwrap();
    let line = |key: &str| range[key]["line"].as_u64().unwrap() as usize;
    let character = |key: &str| range[key]["character"].as_u64().unwrap() as usize;
    let lines: Vec<&str> = text.split('\n').collect();
    assert_eq!(line("start"), line("end"));
    lines[line("start")][character("start")..character("end")].to_owned()
}

fn definition_at(needle: &str) -> Value {
    json!({"position": at(MAIN, needle)})
}

#[test]
fn stdlib_el_gz_definitions_open_a_read_only_cache_copy() {
    let install = Install::new();
    let replies = install.main_session(
        Some(&install.emacs),
        &[
            (
                10,
                "textDocument/definition",
                definition_at("fake-filter #'"),
            ),
            (
                11,
                "textDocument/definition",
                definition_at("fake-autoloaded items"),
            ),
            (12, "textDocument/definition", definition_at("fake-seq)")),
        ],
    );
    let stdlib = by_id(&replies, 10);
    let target = stdlib[0]["uri"].as_str().unwrap();
    let cached = url::Url::parse(target).unwrap().to_file_path().unwrap();
    assert!(
        cached.starts_with(install.cache.join("elsmith/stdlib")),
        "{target}"
    );
    assert!(cached.ends_with("emacs-lisp/fake-seq.el"));
    assert!(cached.starts_with(&install.cache));
    assert_eq!(fs::read_to_string(&cached).unwrap(), SEQ);
    assert_eq!(
        fs::metadata(&cached).unwrap().permissions().mode() & 0o222,
        0
    );
    assert_eq!(range_text(target, &stdlib[0]["range"]), "fake-filter");
    let autoloaded = by_id(&replies, 11);
    assert_eq!(autoloaded[0]["uri"].as_str().unwrap(), target);
    assert_eq!(
        range_text(target, &autoloaded[0]["range"]),
        "fake-autoloaded"
    );
    let feature = by_id(&replies, 12);
    assert_eq!(feature[0]["uri"].as_str().unwrap(), target);
    assert_eq!(range_text(target, &feature[0]["range"]), "fake-seq");
    assert!(install.lisp.join("emacs-lisp/fake-seq.el.gz").is_file());
}

#[test]
fn c_source_present_opens_the_defun() {
    let install = Install::new();
    let replies = install.main_session(
        Some(&install.emacs),
        &[
            (10, "textDocument/definition", definition_at("car items")),
            (11, "textDocument/hover", definition_at("car items")),
        ],
    );
    let c_source = by_id(&replies, 10);
    let data_c = c_source[0]["uri"].as_str().unwrap();
    assert!(
        data_c.ends_with("/install/share/emacs/31.1/src/data.c"),
        "{data_c}"
    );
    assert_eq!(range_text(data_c, &c_source[0]["range"]), "\"car\"");
    let hover = by_id(&replies, 11)["contents"]["value"].as_str().unwrap();
    assert!(
        hover.contains("`src/data.c`") && !hover.contains("not installed"),
        "{hover}"
    );
}

#[test]
fn c_source_absent_gives_an_empty_definition_and_a_rich_hover() {
    let install = Install::new();
    let replies = install.main_session(
        Some(&install.emacs),
        &[
            (10, "textDocument/definition", definition_at("mapcar #'")),
            (11, "textDocument/hover", definition_at("mapcar #'")),
        ],
    );
    assert_eq!(by_id(&replies, 10), &json!([]));
    let hover = by_id(&replies, 11)["contents"]["value"].as_str().unwrap();
    assert!(hover.contains("(mapcar FUNCTION SEQUENCE)"), "{hover}");
    assert!(hover.contains("Built-in function"), "{hover}");
    assert!(hover.contains("source not installed"), "{hover}");
    assert!(
        hover.contains("Apply FUNCTION to each element of SEQUENCE."),
        "{hover}"
    );
}

#[test]
fn no_emacs_with_an_empty_path_still_serves_the_workspace() {
    let install = Install::new();
    let main = install.uri("main.el");
    let doc = json!({"uri": main});
    let mut messages = initialize(&install.workspace, json!({})).to_vec();
    messages.push(open(&main, MAIN));
    messages.push(request(
        10,
        "textDocument/hover",
        json!({"textDocument": doc, "position": at(MAIN, "car items")}),
    ));
    messages.push(request(
        11,
        "textDocument/definition",
        json!({"textDocument": doc, "position": at(MAIN, "car items")}),
    ));
    messages.push(request(
        12,
        "textDocument/definition",
        json!({"textDocument": doc, "position": at(MAIN, "disk-only items")}),
    ));
    messages.push(request(
        13,
        "textDocument/completion",
        json!({"textDocument": doc, "position": {"line": 8, "character": 6}}),
    ));
    messages.push(request(
        14,
        "textDocument/signatureHelp",
        json!({"textDocument": doc, "position": {"line": 8, "character": 13}}),
    ));
    messages.push(request(
        15,
        "textDocument/semanticTokens/full",
        json!({"textDocument": doc}),
    ));
    messages.extend(finish());
    let (output, replies) = install.session(None, &messages);
    let log = String::from_utf8_lossy(&output.stderr);
    assert!(
        log.contains("No Emacs catalog: Emacs was not found"),
        "{log}"
    );
    assert!(by_id(&replies, 10).is_null());
    assert!(by_id(&replies, 11).is_null());
    assert_eq!(by_id(&replies, 12)[0]["uri"], install.uri("disk.el"));
    let items = by_id(&replies, 13)["items"].as_array().unwrap();
    assert!(items.iter().any(|item| item["label"] == "disk-only"));
    let signature = by_id(&replies, 14);
    assert_eq!(signature["signatures"][0]["label"], "(disk-only X)");
    assert_eq!(signature["activeParameter"], 0);
    assert!(!by_id(&replies, 15)["data"].as_array().unwrap().is_empty());
    assert!(!install.cache.exists());
    assert!(!install.logs.join("count.txt").exists());
}

#[test]
fn a_workspace_emacs_on_path_is_never_spawned() {
    let install = Install::new();
    let marker = install.root.join("spawned");
    let workspace_emacs = install.workspace.join("emacs");
    fs::write(
        &workspace_emacs,
        format!(
            "#!{}\nprintf x > '{}'\n",
            shell().display(),
            marker.display()
        ),
    )
    .unwrap();
    fs::set_permissions(&workspace_emacs, fs::Permissions::from_mode(0o755)).unwrap();
    let main = install.uri("main.el");
    let mut messages = initialize(&install.workspace, json!({})).to_vec();
    messages.push(open(&main, MAIN));
    messages.push(request(
        10,
        "textDocument/hover",
        json!({"textDocument": {"uri": main}, "position": at(MAIN, "car items")}),
    ));
    messages.extend(finish());
    let (output, replies) = install.session_with_path(None, &install.workspace, &messages);
    assert!(by_id(&replies, 10).is_null());
    assert!(!marker.exists());
    let log = String::from_utf8_lossy(&output.stderr);
    assert!(log.contains("No Emacs catalog"), "{log}");
}

#[test]
fn the_extractor_runs_isolated_and_only_once() {
    let install = Install::new();
    install.main_session(
        Some(&install.emacs),
        &[(10, "textDocument/hover", definition_at("car items"))],
    );
    install.main_session(
        Some(&install.emacs),
        &[(10, "textDocument/hover", definition_at("car items"))],
    );
    let args = fs::read_to_string(install.logs.join("args.txt")).unwrap();
    assert!(args.starts_with("-Q\n--batch\n-l\n"), "{args}");
    let environment = fs::read_to_string(install.logs.join("env.txt")).unwrap();
    for leaked in [
        "EMACSLOADPATH",
        "XDG_CACHE_HOME",
        "ELSMITH_CONFIG_DIR",
        "PATH=",
    ] {
        assert!(
            !environment.contains(leaked),
            "{leaked} leaked: {environment}"
        );
    }
    assert_eq!(
        fs::read_to_string(install.logs.join("listing.txt")).unwrap(),
        "*\n"
    );
    let cwd = fs::read_to_string(install.logs.join("cwd.txt")).unwrap();
    assert!(
        !cwd.trim().starts_with(install.root.to_str().unwrap()),
        "{cwd}"
    );
    assert_eq!(
        fs::read_to_string(install.logs.join("count.txt")).unwrap(),
        "x"
    );
}

#[test]
fn unsaved_buffers_override_disk_across_files() {
    let install = Install::new();
    let main = install.uri("main.el");
    let sibling = install.uri("sibling.el");
    let replies = install.main_session(
        Some(&install.emacs),
        &[
            (10, "textDocument/definition", definition_at("sibling-new items")),
            (11, "textDocument/definition", definition_at("disk-only items")),
            (12, "textDocument/references", json!({"position": at(MAIN, "sibling-new items"), "context": {"includeDeclaration": true}})),
            (13, "workspace/symbol", json!({"query": "sibling"})),
            (14, "textDocument/completion", json!({"position": {"line": 8, "character": 6}})),
        ],
    );
    assert_eq!(
        by_id(&replies, 10),
        &json!([{"uri": sibling, "range": {"start": {"line": 0, "character": 7}, "end": {"line": 0, "character": 18}}}])
    );
    assert_eq!(by_id(&replies, 11)[0]["uri"], install.uri("disk.el"));
    let references: Vec<&str> = by_id(&replies, 12)
        .as_array()
        .unwrap()
        .iter()
        .map(|location| location["uri"].as_str().unwrap())
        .collect();
    assert_eq!(references, vec![main.as_str(), sibling.as_str()]);
    let names: Vec<&str> = by_id(&replies, 13)
        .as_array()
        .unwrap()
        .iter()
        .map(|symbol| symbol["name"].as_str().unwrap())
        .collect();
    assert_eq!(names, vec!["sibling-new", "sibling"]);
    let items = by_id(&replies, 14)["items"].as_array().unwrap();
    assert!(items.iter().any(|item| item["label"] == "disk-only"));
}

#[test]
fn buffers_opened_through_a_symlink_or_an_escaped_uri_replace_the_index() {
    let install = Install::new();
    let link = install.root.join("link");
    std::os::unix::fs::symlink(&install.workspace, &link).unwrap();
    fs::write(
        install.workspace.join("plus+file.el"),
        "(defun plus-old () 1)\n",
    )
    .unwrap();
    let sibling = url::Url::from_file_path(link.join("sibling.el"))
        .unwrap()
        .to_string();
    let plus = url::Url::from_file_path(link.join("plus+file.el"))
        .unwrap()
        .to_string()
        .replace('+', "%2B");
    let mut messages = initialize(&link, json!({})).to_vec();
    messages.push(open(&sibling, SIBLING));
    messages.push(open(&plus, "(defun plus-new () 2)\n"));
    messages.push(request(
        10,
        "workspace/symbol",
        json!({"query": "sibling-"}),
    ));
    messages.push(request(11, "workspace/symbol", json!({"query": "plus-"})));
    messages.extend(finish());
    let (_, replies) = install.session(None, &messages);
    let names = |id| -> Vec<(String, String)> {
        by_id(&replies, id)
            .as_array()
            .unwrap()
            .iter()
            .map(|symbol| {
                (
                    symbol["name"].as_str().unwrap().to_owned(),
                    symbol["location"]["uri"].as_str().unwrap().to_owned(),
                )
            })
            .collect()
    };
    assert_eq!(names(10), vec![("sibling-new".to_owned(), sibling.clone())]);
    assert_eq!(names(11), vec![("plus-new".to_owned(), plus.clone())]);
}

#[test]
fn local_declarations_do_not_hide_definitions_elsewhere() {
    let install = Install::new();
    let main = install.uri("main.el");
    let text = format!(
        "{MAIN}(declare-function sibling-new \"sibling\")\n(declare-function car \"data\")\n(defvar load-path)\n(defun main-more () (sibling-new 1) (car nil) load-path)\n"
    );
    let doc = json!({"uri": main});
    let mut messages = initialize(&install.workspace, json!({})).to_vec();
    messages.push(open(&main, &text));
    messages.push(open(&install.uri("sibling.el"), SIBLING));
    let call = |needle: &str| json!({"textDocument": doc, "position": at(&text, needle)});
    messages.push(request(
        10,
        "textDocument/definition",
        call("sibling-new 1"),
    ));
    messages.push(request(11, "textDocument/definition", call("car nil")));
    messages.push(request(
        12,
        "textDocument/declaration",
        call("sibling-new 1"),
    ));
    messages.push(request(13, "textDocument/definition", call("load-path)\n")));
    messages.extend(finish());
    let (_, replies) = install.session(Some(&install.emacs), &messages);
    assert_eq!(by_id(&replies, 10)[0]["uri"], install.uri("sibling.el"));
    assert!(
        by_id(&replies, 11)[0]["uri"]
            .as_str()
            .unwrap()
            .ends_with("src/data.c")
    );
    let declaration = by_id(&replies, 12);
    assert_eq!(declaration[0]["uri"], main);
    assert_eq!(declaration[0]["range"]["start"]["line"], 9);
    let variable = by_id(&replies, 13);
    assert_eq!(variable[0]["uri"], main);
    assert_eq!(variable[0]["range"]["start"]["line"], 11);
}

#[test]
fn require_edits_follow_the_client_capability_and_the_cache_is_reused() {
    let install = Install::new();
    let main = install.uri("main.el");
    let doc = json!({"uri": main});
    let item = |edits: bool| {
        let capabilities = if edits {
            json!({"textDocument": {"completion": {"completionItem": {"resolveSupport": {"properties": ["additionalTextEdits"]}}}}})
        } else {
            json!({})
        };
        let mut messages = initialize(&install.workspace, capabilities).to_vec();
        messages.push(open(&main, MAIN));
        messages.push(request(
            10,
            "textDocument/completion",
            json!({"textDocument": doc, "position": {"line": 8, "character": 6}}),
        ));
        messages.extend(finish());
        let (_, replies) = install.session(Some(&install.emacs), &messages);
        let completion = by_id(&replies, 10);
        let disk = completion["items"]
            .as_array()
            .unwrap()
            .iter()
            .find(|item| item["label"] == "disk-only")
            .unwrap()
            .clone();
        let mut messages = initialize(&install.workspace, if edits {
            json!({"textDocument": {"completion": {"completionItem": {"resolveSupport": {"properties": ["additionalTextEdits"]}}}}})
        } else {
            json!({})
        })
        .to_vec();
        messages.push(open(&main, MAIN));
        messages.push(request(11, "completionItem/resolve", disk));
        messages.extend(finish());
        let (_, replies) = install.session(Some(&install.emacs), &messages);
        by_id(&replies, 11).clone()
    };
    let with_edits = item(true);
    assert_eq!(
        with_edits["additionalTextEdits"],
        json!([{"range": {"start": {"line": 1, "character": 19}, "end": {"line": 1, "character": 19}}, "newText": "\n(require 'disk)"}])
    );
    assert!(
        with_edits["documentation"]["value"]
            .as_str()
            .unwrap()
            .contains("Only on disk.")
    );
    let without = item(false);
    assert!(without.get("additionalTextEdits").is_none(), "{without}");
    assert_eq!(
        fs::read_to_string(install.logs.join("count.txt")).unwrap(),
        "x"
    );
}

#[test]
fn catalog_commands_build_show_and_report_missing_emacs() {
    let install = Install::new();
    let run = |args: &[&str]| install.command().args(args).output().unwrap();
    let missing = run(&["catalog", "show-catalog"]);
    assert_eq!(missing.status.code(), Some(254));
    let emacs = install.emacs.to_str().unwrap();
    let absent = run(&["catalog", "show-catalog", "--emacs", emacs]);
    assert_eq!(absent.status.code(), Some(254));
    let built = run(&["catalog", "build-catalog", "--emacs", emacs]);
    assert!(
        built.status.success(),
        "{}",
        String::from_utf8_lossy(&built.stderr)
    );
    let built: Value = serde_json::from_slice(&built.stdout).unwrap();
    assert_eq!(built["Cached"], false);
    assert_eq!(built["Functions"], 6);
    assert_eq!(built["Subrs"], 2);
    let again: Value =
        serde_json::from_slice(&run(&["catalog", "build-catalog", "--emacs", emacs]).stdout)
            .unwrap();
    assert_eq!(again["Cached"], true);
    let shown = run(&["catalog", "show-catalog", "--emacs", emacs]);
    assert!(shown.status.success());
    let shown: Value = serde_json::from_slice(&shown.stdout).unwrap();
    assert_eq!(shown["CacheFile"], built["CacheFile"]);
    assert_eq!(
        fs::read_to_string(install.logs.join("count.txt")).unwrap(),
        "x"
    );
    let forced = run(&["catalog", "build-catalog", "--emacs", emacs, "--force"]);
    assert!(forced.status.success());
    assert_eq!(
        fs::read_to_string(install.logs.join("count.txt")).unwrap(),
        "xx"
    );
    let relative = run(&["catalog", "build-catalog", "--emacs", "emacs"]);
    assert_eq!(relative.status.code(), Some(254));
}

fn system_emacs() -> Option<PathBuf> {
    let path = env::var_os("PATH")?;
    env::split_paths(&path)
        .filter(|dir| dir.is_absolute())
        .map(|dir| dir.join("emacs"))
        .find(|candidate| candidate.is_file())
}

#[test]
fn real_emacs_catalog_jumps_into_the_stdlib_cache() {
    let Some(emacs) = system_emacs() else {
        eprintln!("skipped: no emacs on PATH");
        return;
    };
    let temp = tempfile::tempdir().unwrap();
    let root = fs::canonicalize(temp.path()).unwrap();
    let workspace = root.join("workspace");
    fs::create_dir_all(&workspace).unwrap();
    let text = ";;; real.el --- Real -*- lexical-binding: t -*-\n(defun real-run (items)\n  (seq-filter #'identity items)\n  (car items))\n";
    let uri = url::Url::from_file_path(workspace.join("real.el"))
        .unwrap()
        .to_string();
    let doc = json!({"uri": uri});
    let mut messages = initialize(&workspace, json!({})).to_vec();
    messages.push(open(&uri, text));
    messages.push(request(
        10,
        "textDocument/definition",
        json!({"textDocument": doc, "position": at(text, "seq-filter")}),
    ));
    messages.push(request(
        11,
        "textDocument/definition",
        json!({"textDocument": doc, "position": at(text, "car items")}),
    ));
    messages.push(request(
        12,
        "textDocument/hover",
        json!({"textDocument": doc, "position": at(text, "seq-filter")}),
    ));
    messages.extend(finish());
    let mut child = binary()
        .args(["server", "run-server", "--emacs"])
        .arg(&emacs)
        .env("XDG_CACHE_HOME", root.join("cache"))
        .env("ELSMITH_CONFIG_DIR", root.join("config"))
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    {
        let mut input = child.stdin.take().unwrap();
        for message in &messages {
            send(&mut input, &serde_json::to_vec(message).unwrap());
        }
    }
    let output = child.wait_with_output().unwrap();
    assert!(output.status.success());
    let replies = responses(&output.stdout);
    let seq = by_id(&replies, 10);
    let target = seq[0]["uri"].as_str().unwrap();
    let path = url::Url::parse(target).unwrap().to_file_path().unwrap();
    assert!(
        path.starts_with(root.join("cache/elsmith/stdlib")),
        "{target}"
    );
    assert!(path.ends_with("emacs-lisp/seq.el"));
    assert_eq!(range_text(target, &seq[0]["range"]), "seq-filter");
    let car = by_id(&replies, 11);
    let lisp = fs::canonicalize(&emacs)
        .unwrap()
        .parent()
        .unwrap()
        .join("../share/emacs");
    let has_c_source = fs::read_dir(&lisp)
        .ok()
        .into_iter()
        .flatten()
        .flatten()
        .any(|entry| entry.path().join("src/data.c").is_file());
    if has_c_source {
        let data_c = car[0]["uri"].as_str().unwrap();
        assert!(data_c.ends_with("/src/data.c"), "{data_c}");
        assert_eq!(range_text(data_c, &car[0]["range"]), "\"car\"");
    } else {
        assert_eq!(car, &json!([]));
    }
    let hover = by_id(&replies, 12)["contents"]["value"].as_str().unwrap();
    assert!(hover.contains("(seq-filter PRED SEQUENCE)"), "{hover}");
}