Skip to main content

elsmith/
document.rs

1use std::collections::HashMap;
2use std::sync::OnceLock;
3
4use serde::Deserialize;
5use serde_json::Value;
6
7use crate::analysis::{self, Analysis};
8use crate::elisp_header::{self, Header};
9use crate::position::{ContentChange, Edit, Encoding, apply_content_change};
10use crate::syntax::Tree;
11
12#[derive(Default)]
13pub(crate) struct Documents(HashMap<String, Document>);
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum Semantic {
17    Whole,
18    Range(usize, usize),
19}
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub struct Invalidation {
23    pub syntax: (usize, usize),
24    pub semantic: Semantic,
25    pub full: bool,
26}
27
28pub(crate) struct Document {
29    pub version: i32,
30    pub text: String,
31    pub tree: Tree,
32    header: Header,
33    analysis: OnceLock<Analysis>,
34    pub invalidations: Vec<Invalidation>,
35}
36
37const MACRO_DEFINERS: &[&str] = &[
38    "defmacro",
39    "cl-defmacro",
40    "define-inline",
41    "defalias",
42    "pcase-defmacro",
43];
44
45impl Document {
46    pub fn new(version: i32, text: String) -> Self {
47        Self {
48            version,
49            tree: Tree::parse_str(&text),
50            header: elisp_header::lexical_cookie(&text),
51            text,
52            analysis: OnceLock::new(),
53            invalidations: Vec::new(),
54        }
55    }
56
57    pub fn analysis(&self) -> &Analysis {
58        self.analysis
59            .get_or_init(|| analysis::analyze(&self.text, &self.tree))
60    }
61
62    fn apply(&mut self, text: String, edit: Edit) -> Invalidation {
63        let removed = &self.text[edit.start..edit.old_end];
64        let removed_macro = MACRO_DEFINERS.iter().any(|head| removed.contains(head));
65        let old_shorthands = analysis::shorthands(&self.text);
66        let reparse = self
67            .tree
68            .edit(text.as_bytes(), edit.start, edit.old_end, edit.new_end);
69        let header = elisp_header::lexical_cookie(&text);
70        let syntax = (reparse.restart, reparse.resumed.unwrap_or(text.len()));
71        let reparsed = &text[syntax.0..syntax.1];
72        let whole = header.cookie != self.header.cookie
73            || edit.start < self.header.extent
74            || removed_macro
75            || MACRO_DEFINERS.iter().any(|head| reparsed.contains(head))
76            || analysis::shorthands(&text) != old_shorthands;
77        self.text = text;
78        self.header = header;
79        Invalidation {
80            syntax,
81            semantic: if whole {
82                Semantic::Whole
83            } else {
84                Semantic::Range(syntax.0, syntax.1)
85            },
86            full: reparse.full,
87        }
88    }
89}
90
91#[derive(Deserialize)]
92struct Params<D> {
93    #[serde(rename = "textDocument")]
94    document: D,
95}
96
97#[derive(Deserialize)]
98struct Open {
99    uri: String,
100    #[serde(rename = "languageId")]
101    language_id: Option<String>,
102    version: i32,
103    text: String,
104}
105
106#[derive(Deserialize)]
107struct VersionedDocument {
108    uri: String,
109    version: i32,
110}
111
112#[derive(Deserialize)]
113struct Change {
114    #[serde(rename = "textDocument")]
115    document: VersionedDocument,
116    #[serde(rename = "contentChanges")]
117    changes: Vec<ContentChange>,
118}
119
120#[derive(Deserialize)]
121struct Identifier {
122    uri: String,
123}
124
125impl Documents {
126    pub(crate) fn open(&mut self, params: Value) -> Option<()> {
127        let params: Params<Open> = serde_json::from_value(params).ok()?;
128        let Open {
129            uri,
130            language_id,
131            version,
132            text,
133        } = params.document;
134        let parsed = url::Url::parse(&uri).ok()?;
135        let extension = std::path::Path::new(parsed.path())
136            .extension()
137            .and_then(|extension| extension.to_str());
138        if matches!(extension, Some("lisp" | "asd" | "cl"))
139            || language_id.as_deref().is_some_and(|id| match id {
140                "emacs-lisp" | "elisp" => false,
141                "lisp" => extension != Some("el"),
142                _ => true,
143            })
144        {
145            return None;
146        }
147        let std::collections::hash_map::Entry::Vacant(document) = self.0.entry(uri) else {
148            return None;
149        };
150        document.insert(Document::new(version, text));
151        Some(())
152    }
153
154    pub(crate) fn change(&mut self, params: Value, encoding: Encoding) -> Option<()> {
155        let Change {
156            document,
157            mut changes,
158        } = serde_json::from_value(params).ok()?;
159        let current = self.0.get_mut(&document.uri)?;
160        if document.version <= current.version {
161            return None;
162        }
163        if changes.len() == 1 {
164            let (text, edit) = apply_content_change(&current.text, encoding, changes.pop()?)?;
165            let invalidation = current.apply(text, edit);
166            current.version = document.version;
167            current.analysis.take();
168            current.invalidations.clear();
169            current.invalidations.push(invalidation);
170            return Some(());
171        }
172        let mut next = Document {
173            version: document.version,
174            text: current.text.clone(),
175            tree: current.tree.clone(),
176            header: current.header,
177            analysis: OnceLock::new(),
178            invalidations: Vec::new(),
179        };
180        for change in changes {
181            let (text, edit) = apply_content_change(&next.text, encoding, change)?;
182            let invalidation = next.apply(text, edit);
183            next.invalidations.push(invalidation);
184        }
185        *current = next;
186        Some(())
187    }
188
189    pub(crate) fn entry(&self, uri: &str) -> Option<(&String, &Document)> {
190        self.0.get_key_value(uri)
191    }
192
193    pub(crate) fn iter(&self) -> impl Iterator<Item = (&String, &Document)> {
194        self.0.iter()
195    }
196
197    pub(crate) fn get(&self, uri: &str) -> Option<&Document> {
198        self.0.get(uri)
199    }
200
201    pub(crate) fn save(&self, params: Value) -> Option<()> {
202        let params: Params<Identifier> = serde_json::from_value(params).ok()?;
203        self.0.get(&params.document.uri)?;
204        Some(())
205    }
206
207    pub(crate) fn close(&mut self, params: Value) -> Option<()> {
208        let params: Params<Identifier> = serde_json::from_value(params).ok()?;
209        self.0.remove(&params.document.uri)?;
210        Some(())
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use serde_json::json;
217
218    use super::*;
219
220    #[test]
221    fn rejects_a_partial_or_stale_change_and_accepts_reopening() {
222        let mut docs = Documents::default();
223        let id = "file:///sample.el";
224        let open = json!({"textDocument": {"uri": id, "text": "a😀\r\n", "version": 8}});
225        let identifier = json!({"textDocument": {"uri": id}});
226        docs.open(open.clone()).unwrap();
227        let bad = json!({"textDocument": {"uri": id, "version": 9}, "contentChanges": [
228            {"text": "b😀\r\n"},
229            {"text": "X", "range": {"start": {"line": 0, "character": 2}, "end": {"line": 0, "character": 3}}}
230        ]});
231        assert!(docs.change(bad, Encoding::Utf16).is_none());
232        assert_eq!(docs.0[id].text, "a😀\r\n");
233        assert_eq!(docs.0[id].version, 8);
234        let bad = json!({"textDocument": {"uri": id, "version": 9}, "contentChanges": [
235            {"text": "X", "range": {"start": {"line": 0, "character": 2}, "end": {"line": 0, "character": 3}}}
236        ]});
237        assert!(docs.change(bad, Encoding::Utf16).is_none());
238        assert_eq!(docs.0[id].text, "a😀\r\n");
239        assert_eq!(docs.0[id].version, 8);
240        let stale =
241            json!({"textDocument": {"uri": id, "version": 7}, "contentChanges": [{"text": "old"}]});
242        assert!(docs.change(stale, Encoding::Utf16).is_none());
243        docs.save(identifier.clone()).unwrap();
244        docs.close(identifier).unwrap();
245        docs.open(open).unwrap();
246        let change =
247            json!({"textDocument": {"uri": id, "version": 9}, "contentChanges": [{"text": "new"}]});
248        docs.change(change, Encoding::Utf16).unwrap();
249        assert_eq!(docs.0[id].text, "new");
250        assert_eq!(docs.0[id].tree, Tree::parse_str("new"));
251    }
252
253    #[test]
254    fn sequential_changes_reparse_incrementally_and_separate_invalidation() {
255        let mut docs = Documents::default();
256        let id = "file:///edit.el";
257        let text =
258            ";; -*- lexical-binding: t -*-\n(defun a () 1)\n(defun b () 2)\n(defun c () 3)\n";
259        docs.open(json!({"textDocument": {"uri": id, "text": text, "version": 1}}))
260            .unwrap();
261        let range = |line: u32, start: u32, end: u32| json!({"start": {"line": line, "character": start}, "end": {"line": line, "character": end}});
262        let change = json!({"textDocument": {"uri": id, "version": 2}, "contentChanges": [
263            {"range": range(2, 12, 13), "text": "20"},
264            {"range": range(3, 7, 8), "text": "\"open"},
265            {"range": range(3, 7, 8), "text": "c"},
266            {"range": range(0, 24, 25), "text": "nil"}
267        ]});
268        docs.change(change, Encoding::Utf16).unwrap();
269        let document = docs.get(id).unwrap();
270        assert_eq!(document.tree, Tree::parse_str(&document.text));
271        assert!(document.text.contains("(defun b () 20)"));
272        let kinds: Vec<_> = document
273            .invalidations
274            .iter()
275            .map(|invalidation| invalidation.semantic == Semantic::Whole)
276            .collect();
277        assert_eq!(kinds, vec![false, false, false, true]);
278        let first = document.invalidations[0];
279        assert_eq!(first.syntax, (45, 60));
280        assert!(!first.full);
281        assert!(!document.analysis().lexical);
282        let macro_change = json!({"textDocument": {"uri": id, "version": 3}, "contentChanges": [
283            {"range": range(1, 1, 6), "text": "defmacro"}
284        ]});
285        docs.change(macro_change, Encoding::Utf16).unwrap();
286        assert_eq!(
287            docs.get(id).unwrap().invalidations[0].semantic,
288            Semantic::Whole
289        );
290    }
291}