use std::collections::HashMap;
use std::sync::OnceLock;
use serde::Deserialize;
use serde_json::Value;
use crate::analysis::{self, Analysis};
use crate::elisp_header::{self, Header};
use crate::position::{ContentChange, Edit, Encoding, apply_content_change};
use crate::syntax::Tree;
#[derive(Default)]
pub(crate) struct Documents(HashMap<String, Document>);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Semantic {
Whole,
Range(usize, usize),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Invalidation {
pub syntax: (usize, usize),
pub semantic: Semantic,
pub full: bool,
}
pub(crate) struct Document {
pub version: i32,
pub text: String,
pub tree: Tree,
header: Header,
analysis: OnceLock<Analysis>,
pub invalidations: Vec<Invalidation>,
}
const MACRO_DEFINERS: &[&str] = &[
"defmacro",
"cl-defmacro",
"define-inline",
"defalias",
"pcase-defmacro",
];
impl Document {
pub fn new(version: i32, text: String) -> Self {
Self {
version,
tree: Tree::parse_str(&text),
header: elisp_header::lexical_cookie(&text),
text,
analysis: OnceLock::new(),
invalidations: Vec::new(),
}
}
pub fn analysis(&self) -> &Analysis {
self.analysis
.get_or_init(|| analysis::analyze(&self.text, &self.tree))
}
fn apply(&mut self, text: String, edit: Edit) -> Invalidation {
let removed = &self.text[edit.start..edit.old_end];
let removed_macro = MACRO_DEFINERS.iter().any(|head| removed.contains(head));
let old_shorthands = analysis::shorthands(&self.text);
let reparse = self
.tree
.edit(text.as_bytes(), edit.start, edit.old_end, edit.new_end);
let header = elisp_header::lexical_cookie(&text);
let syntax = (reparse.restart, reparse.resumed.unwrap_or(text.len()));
let reparsed = &text[syntax.0..syntax.1];
let whole = header.cookie != self.header.cookie
|| edit.start < self.header.extent
|| removed_macro
|| MACRO_DEFINERS.iter().any(|head| reparsed.contains(head))
|| analysis::shorthands(&text) != old_shorthands;
self.text = text;
self.header = header;
Invalidation {
syntax,
semantic: if whole {
Semantic::Whole
} else {
Semantic::Range(syntax.0, syntax.1)
},
full: reparse.full,
}
}
}
#[derive(Deserialize)]
struct Params<D> {
#[serde(rename = "textDocument")]
document: D,
}
#[derive(Deserialize)]
struct Open {
uri: String,
#[serde(rename = "languageId")]
language_id: Option<String>,
version: i32,
text: String,
}
#[derive(Deserialize)]
struct VersionedDocument {
uri: String,
version: i32,
}
#[derive(Deserialize)]
struct Change {
#[serde(rename = "textDocument")]
document: VersionedDocument,
#[serde(rename = "contentChanges")]
changes: Vec<ContentChange>,
}
#[derive(Deserialize)]
struct Identifier {
uri: String,
}
impl Documents {
pub(crate) fn open(&mut self, params: Value) -> Option<()> {
let params: Params<Open> = serde_json::from_value(params).ok()?;
let Open {
uri,
language_id,
version,
text,
} = params.document;
let parsed = url::Url::parse(&uri).ok()?;
let extension = std::path::Path::new(parsed.path())
.extension()
.and_then(|extension| extension.to_str());
if matches!(extension, Some("lisp" | "asd" | "cl"))
|| language_id.as_deref().is_some_and(|id| match id {
"emacs-lisp" | "elisp" => false,
"lisp" => extension != Some("el"),
_ => true,
})
{
return None;
}
let std::collections::hash_map::Entry::Vacant(document) = self.0.entry(uri) else {
return None;
};
document.insert(Document::new(version, text));
Some(())
}
pub(crate) fn change(&mut self, params: Value, encoding: Encoding) -> Option<()> {
let Change {
document,
mut changes,
} = serde_json::from_value(params).ok()?;
let current = self.0.get_mut(&document.uri)?;
if document.version <= current.version {
return None;
}
if changes.len() == 1 {
let (text, edit) = apply_content_change(¤t.text, encoding, changes.pop()?)?;
let invalidation = current.apply(text, edit);
current.version = document.version;
current.analysis.take();
current.invalidations.clear();
current.invalidations.push(invalidation);
return Some(());
}
let mut next = Document {
version: document.version,
text: current.text.clone(),
tree: current.tree.clone(),
header: current.header,
analysis: OnceLock::new(),
invalidations: Vec::new(),
};
for change in changes {
let (text, edit) = apply_content_change(&next.text, encoding, change)?;
let invalidation = next.apply(text, edit);
next.invalidations.push(invalidation);
}
*current = next;
Some(())
}
pub(crate) fn entry(&self, uri: &str) -> Option<(&String, &Document)> {
self.0.get_key_value(uri)
}
pub(crate) fn iter(&self) -> impl Iterator<Item = (&String, &Document)> {
self.0.iter()
}
pub(crate) fn get(&self, uri: &str) -> Option<&Document> {
self.0.get(uri)
}
pub(crate) fn save(&self, params: Value) -> Option<()> {
let params: Params<Identifier> = serde_json::from_value(params).ok()?;
self.0.get(¶ms.document.uri)?;
Some(())
}
pub(crate) fn close(&mut self, params: Value) -> Option<()> {
let params: Params<Identifier> = serde_json::from_value(params).ok()?;
self.0.remove(¶ms.document.uri)?;
Some(())
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn rejects_a_partial_or_stale_change_and_accepts_reopening() {
let mut docs = Documents::default();
let id = "file:///sample.el";
let open = json!({"textDocument": {"uri": id, "text": "a😀\r\n", "version": 8}});
let identifier = json!({"textDocument": {"uri": id}});
docs.open(open.clone()).unwrap();
let bad = json!({"textDocument": {"uri": id, "version": 9}, "contentChanges": [
{"text": "b😀\r\n"},
{"text": "X", "range": {"start": {"line": 0, "character": 2}, "end": {"line": 0, "character": 3}}}
]});
assert!(docs.change(bad, Encoding::Utf16).is_none());
assert_eq!(docs.0[id].text, "a😀\r\n");
assert_eq!(docs.0[id].version, 8);
let bad = json!({"textDocument": {"uri": id, "version": 9}, "contentChanges": [
{"text": "X", "range": {"start": {"line": 0, "character": 2}, "end": {"line": 0, "character": 3}}}
]});
assert!(docs.change(bad, Encoding::Utf16).is_none());
assert_eq!(docs.0[id].text, "a😀\r\n");
assert_eq!(docs.0[id].version, 8);
let stale =
json!({"textDocument": {"uri": id, "version": 7}, "contentChanges": [{"text": "old"}]});
assert!(docs.change(stale, Encoding::Utf16).is_none());
docs.save(identifier.clone()).unwrap();
docs.close(identifier).unwrap();
docs.open(open).unwrap();
let change =
json!({"textDocument": {"uri": id, "version": 9}, "contentChanges": [{"text": "new"}]});
docs.change(change, Encoding::Utf16).unwrap();
assert_eq!(docs.0[id].text, "new");
assert_eq!(docs.0[id].tree, Tree::parse_str("new"));
}
#[test]
fn sequential_changes_reparse_incrementally_and_separate_invalidation() {
let mut docs = Documents::default();
let id = "file:///edit.el";
let text =
";; -*- lexical-binding: t -*-\n(defun a () 1)\n(defun b () 2)\n(defun c () 3)\n";
docs.open(json!({"textDocument": {"uri": id, "text": text, "version": 1}}))
.unwrap();
let range = |line: u32, start: u32, end: u32| json!({"start": {"line": line, "character": start}, "end": {"line": line, "character": end}});
let change = json!({"textDocument": {"uri": id, "version": 2}, "contentChanges": [
{"range": range(2, 12, 13), "text": "20"},
{"range": range(3, 7, 8), "text": "\"open"},
{"range": range(3, 7, 8), "text": "c"},
{"range": range(0, 24, 25), "text": "nil"}
]});
docs.change(change, Encoding::Utf16).unwrap();
let document = docs.get(id).unwrap();
assert_eq!(document.tree, Tree::parse_str(&document.text));
assert!(document.text.contains("(defun b () 20)"));
let kinds: Vec<_> = document
.invalidations
.iter()
.map(|invalidation| invalidation.semantic == Semantic::Whole)
.collect();
assert_eq!(kinds, vec![false, false, false, true]);
let first = document.invalidations[0];
assert_eq!(first.syntax, (45, 60));
assert!(!first.full);
assert!(!document.analysis().lexical);
let macro_change = json!({"textDocument": {"uri": id, "version": 3}, "contentChanges": [
{"range": range(1, 1, 6), "text": "defmacro"}
]});
docs.change(macro_change, Encoding::Utf16).unwrap();
assert_eq!(
docs.get(id).unwrap().invalidations[0].semantic,
Semantic::Whole
);
}
}