use std::collections::{BTreeMap, HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use serde_json::{Value, json};
use crate::analysis::{Analysis, Definition, Form, Role, Space, analyze, form_at_range, forms};
use crate::catalog::{self, Catalog, Kind, Source};
use crate::document::Documents;
use crate::navigation::{self, Lines};
use crate::position::{Encoding, Position};
use crate::semantic;
use crate::signature::{self, Signature};
use crate::syntax::{Kind as Syntax, Node, Tree};
use crate::workspace::{self, Workspace};
const COMPLETION_LIMIT: usize = 500;
const FEATURE_HEADS: &[&str] = &[
"require",
"featurep",
"provide",
"with-eval-after-load",
"eval-after-load",
"unload-feature",
];
pub struct Parsed {
pub uri: String,
pub text: String,
pub tree: Tree,
pub analysis: Analysis,
}
pub type ParsedCache = Mutex<HashMap<PathBuf, Arc<Parsed>>>;
pub(crate) struct World<'a> {
pub documents: &'a Documents,
pub workspace: Option<&'a Workspace>,
pub catalog: Option<&'a Catalog>,
pub cache: Option<&'a Path>,
pub parsed: &'a ParsedCache,
pub encoding: Encoding,
pub client: &'a Value,
}
#[derive(Clone, Copy)]
pub struct View<'a> {
pub uri: &'a str,
pub text: &'a str,
pub tree: &'a Tree,
pub analysis: &'a Analysis,
}
#[derive(Clone, Debug, Default)]
pub struct Info {
pub usage: Option<String>,
pub role: String,
pub origin: Option<String>,
pub doc: Option<String>,
pub feature: Option<String>,
pub source: &'static str,
pub kind: Option<Kind>,
}
struct Target {
start: usize,
end: usize,
name: String,
space: Space,
role: Role,
binder: Option<usize>,
}
fn symbol_char(c: char) -> bool {
!(c.is_whitespace()
|| matches!(
c,
'(' | ')' | '[' | ']' | '"' | ';' | '\'' | '`' | ',' | '#'
))
}
pub fn string_value(literal: &str) -> String {
let body = literal
.strip_prefix('"')
.map(|rest| rest.strip_suffix('"').unwrap_or(rest))
.unwrap_or(literal);
let mut out = String::new();
let mut chars = body.chars();
while let Some(c) = chars.next() {
if c != '\\' {
out.push(c);
continue;
}
match chars.next() {
Some('n') => out.push('\n'),
Some('t') => out.push('\t'),
Some('\n') | Some(' ') | None => {}
Some(other) => out.push(other),
}
}
out
}
pub fn doc_text(doc: &str, markdown: bool) -> String {
let mut out = String::new();
let chars: Vec<char> = doc.chars().collect();
let mut index = 0;
while index < chars.len() {
let c = chars[index];
if c == '\\' && chars.get(index + 1) == Some(&'\\') {
let next = chars.get(index + 2).copied();
match next {
Some('=') => {
index += 3;
if let Some(&escaped) = chars.get(index) {
out.push(escaped);
index += 1;
}
continue;
}
Some(open @ ('[' | '<' | '{')) => {
let close = match open {
'[' => ']',
'<' => '>',
_ => '}',
};
if let Some(length) = chars[index + 3..].iter().position(|c| *c == close) {
let name: String = chars[index + 3..index + 3 + length].iter().collect();
if open == '[' {
if markdown {
out.push_str(&format!("`M-x {name}`"));
} else {
out.push_str(&format!("M-x {name}"));
}
}
index += 4 + length;
continue;
}
}
_ => {}
}
}
if c == '`' || c == '‘' {
let close = if c == '`' { '\'' } else { '’' };
if let Some(length) = chars[index + 1..]
.iter()
.take(80)
.position(|candidate| *candidate == close || *candidate == '\n')
&& chars[index + 1 + length] == close
&& length > 0
{
let inner: String = chars[index + 1..index + 1 + length].iter().collect();
if markdown {
out.push('`');
out.push_str(&inner);
out.push('`');
} else {
out.push_str(&inner);
}
index += length + 2;
continue;
}
}
if markdown && matches!(c, '*' | '_' | '<' | '>' | '[' | ']' | '\\' | '#' | '|') {
out.push('\\');
}
out.push(c);
index += 1;
}
out
}
fn in_text(node: &Node, offset: usize, target: usize, text: &str) -> bool {
let mut at = offset;
for child in &node.children {
let end = at + child.len;
if at < target && target <= end {
match child.kind {
Syntax::Comment => return true,
Syntax::String => {
let closed = child.len > 1 && text[..end].ends_with('"');
return target < end || !closed;
}
_ if !child.children.is_empty() => return in_text(child, at, target, text),
_ => {}
}
}
at = end;
}
false
}
fn atom_text<'t>(form: &Form, text: &'t str) -> &'t str {
let (start, end) = form.range();
&text[start..end]
}
fn is_string(form: &Form) -> bool {
matches!(
form,
Form::Atom {
kind: Syntax::String,
..
}
)
}
fn usage_from_arglist(name: &str, arglist: &Form, text: &str) -> Option<String> {
let Form::List { items, .. } = arglist else {
return None;
};
let mut parts = vec![name.to_owned()];
for item in items {
match item {
Form::Atom {
kind: Syntax::Symbol,
..
} => {
let symbol = atom_text(item, text);
if symbol.starts_with('&') {
parts.push(symbol.to_owned());
} else {
parts.push(symbol.to_uppercase());
}
}
Form::List { items: inner, .. } => {
let raw = atom_text(item, text);
match inner.first() {
Some(
first @ Form::Atom {
kind: Syntax::Symbol,
..
},
) => {
let (start, end) = first.range();
let (list_start, _) = item.range();
let symbol = &text[start..end];
parts.push(format!(
"{}{}{}",
&raw[..start - list_start],
symbol.to_uppercase(),
&raw[end - list_start..]
));
}
_ => parts.push(raw.to_owned()),
}
}
_ => parts.push(atom_text(item, text).to_owned()),
}
}
Some(format!("({})", parts.join(" ")))
}
fn definition_details(view: View, definition: &Definition) -> (Option<String>, Option<String>) {
let Some(Form::List { items, .. }) = form_at_range(view.tree, definition.range) else {
return (None, None);
};
let text = view.text;
let string_at = |index: usize| {
items
.get(index)
.filter(|form| is_string(form))
.map(|form| string_value(atom_text(form, text)))
};
let kind = definition.kind.as_str();
match (definition.space, kind) {
(
Space::Function,
"defun" | "defmacro" | "defsubst" | "define-inline" | "cl-defun" | "cl-defmacro"
| "cl-defsubst" | "cl-iter-defun" | "iter-defun" | "cl-defgeneric",
) => {
let usage = items
.get(2)
.and_then(|arglist| usage_from_arglist(&definition.name, arglist, text));
let doc = (items.len() > 4).then(|| string_at(3)).flatten();
(usage, doc)
}
(Space::Function, "cl-defmethod") => {
let at = items
.iter()
.skip(2)
.position(|item| matches!(item, Form::List { .. }))
.map(|index| index + 2);
let usage = at.and_then(|at| usage_from_arglist(&definition.name, &items[at], text));
let doc = at.and_then(|at| (items.len() > at + 2).then(|| string_at(at + 1)).flatten());
(usage, doc)
}
(Space::Function, "defalias" | "fset") => (None, string_at(3)),
(Space::Function | Space::Value, "define-minor-mode" | "define-globalized-minor-mode") => {
(None, string_at(2))
}
(_, "define-derived-mode") => (None, string_at(4)),
(
Space::Value | Space::Face | Space::Group,
"defvar" | "defconst" | "defcustom" | "defvar-local" | "defface" | "defgroup",
) => (None, string_at(3)),
_ => (None, None),
}
}
fn role_text(kind: &str, space: Space) -> String {
match (kind, space) {
("defmacro" | "cl-defmacro", _) => "Macro".into(),
("defsubst" | "define-inline" | "cl-defsubst", _) => "Inline function".into(),
("cl-defgeneric" | "cl-defmethod", _) => "Generic function".into(),
("defcustom", _) => "User option".into(),
("defconst", _) => "Constant".into(),
("defface", _) => "Face".into(),
("defgroup", _) => "Customization group".into(),
("provide" | "provide-theme", _) => "Feature".into(),
("declare-function", _) => "Declared function".into(),
("autoload", _) => "Autoloaded function".into(),
("define-minor-mode" | "define-globalized-minor-mode", Space::Value) => {
"Minor mode variable".into()
}
("define-minor-mode" | "define-globalized-minor-mode", _) => "Minor mode".into(),
("define-derived-mode", _) => "Major mode".into(),
(_, Space::Value) => "Variable".into(),
(_, Space::Function) => "Function".into(),
(_, Space::Feature) => "Feature".into(),
(other, _) => other.to_owned(),
}
}
fn file_label(uri: &str) -> String {
url::Url::parse(uri)
.ok()
.and_then(|url| url.to_file_path().ok())
.and_then(|path| {
path.file_name()
.map(|name| name.to_string_lossy().into_owned())
})
.unwrap_or_else(|| uri.to_owned())
}
fn line_of(text: &str, offset: usize) -> usize {
text[..offset].matches('\n').count() + 1
}
fn kind_from_definition(definition: &Definition) -> Kind {
if definition.kind.contains("macro") && definition.kind != "define-compiler-macro" {
Kind::Macro
} else {
Kind::Function
}
}
fn markup(markdown: bool, value: String) -> Value {
json!({"kind": if markdown { "markdown" } else { "plaintext" }, "value": value})
}
impl<'a> World<'a> {
fn supports(&self, pointer: &str, value: &str) -> bool {
self.client
.pointer(pointer)
.and_then(Value::as_array)
.is_some_and(|list| list.iter().any(|item| item.as_str() == Some(value)))
}
fn flag(&self, pointer: &str) -> bool {
self.client
.pointer(pointer)
.and_then(Value::as_bool)
.unwrap_or(false)
}
pub fn view(&self, uri: &str) -> Option<View<'a>> {
if let Some((key, document)) = self.documents.entry(uri) {
return Some(View {
uri: key,
text: &document.text,
tree: &document.tree,
analysis: document.analysis(),
});
}
self.workspace?.by_uri(uri).map(|file| View {
uri: &file.uri,
text: &file.text,
tree: &file.tree,
analysis: &file.analysis,
})
}
pub fn views(&self) -> Vec<View<'a>> {
let mut out: Vec<View<'a>> = Vec::new();
let mut open = HashSet::new();
let mut documents: Vec<_> = self.documents.iter().collect();
documents.sort_by(|a, b| a.0.cmp(b.0));
for (uri, document) in documents {
if let Some(path) = url::Url::parse(uri)
.ok()
.and_then(|url| url.to_file_path().ok())
{
open.insert(fs::canonicalize(&path).unwrap_or(path));
}
out.push(View {
uri,
text: &document.text,
tree: &document.tree,
analysis: document.analysis(),
});
}
if let Some(workspace) = self.workspace {
for file in workspace.files() {
if !open.contains(&file.path) {
out.push(View {
uri: &file.uri,
text: &file.text,
tree: &file.tree,
analysis: &file.analysis,
});
}
}
}
out
}
fn lines<'t>(&self, text: &'t str) -> Lines<'t> {
Lines::new(text, self.encoding)
}
fn target(view: View, offset: usize) -> Option<Target> {
if let Some(occurrence) = view.analysis.occurrence_at(offset) {
return Some(Target {
start: occurrence.start,
end: occurrence.end,
name: occurrence.name.clone(),
space: occurrence.space,
role: occurrence.role,
binder: occurrence.binder,
});
}
view.analysis
.heads
.iter()
.find(|(start, end)| *start <= offset && offset <= *end)
.map(|&(start, end)| Target {
start,
end,
name: view.text[start..end].to_owned(),
space: Space::Function,
role: Role::Reference,
binder: None,
})
}
fn definition_info(&self, view: View, definition: &Definition, here: bool) -> Info {
let (usage, doc) = definition_details(view, definition);
let line = line_of(view.text, definition.selection.0);
let origin = if here {
format!("defined in this file (line {line})")
} else {
format!("defined in `{}` (line {line})", file_label(view.uri))
};
let feature = (!here)
.then(|| {
view.analysis
.definitions
.iter()
.find(|definition| definition.space == Space::Feature)
.map(|definition| definition.name.clone())
})
.flatten();
Info {
usage,
role: role_text(&definition.kind, definition.space),
origin: Some(origin),
doc,
feature,
source: if here { "document" } else { "workspace" },
kind: (definition.space == Space::Function).then(|| kind_from_definition(definition)),
}
}
fn emacs_origin(&self, catalog: &Catalog, source: Source) -> Option<String> {
match source {
Source::Lisp(path) => {
let lisp = Path::new(&catalog.data.lisp_directory);
let shown = path
.strip_prefix(lisp)
.unwrap_or(&path)
.to_string_lossy()
.trim_end_matches(".gz")
.to_owned();
Some(format!(
"defined in `{shown}` (Emacs {})",
catalog.data.version
))
}
Source::C { file, path } => Some(if path.is_some() {
format!(
"defined in C source `{file}` (Emacs {})",
catalog.data.version
)
} else {
format!(
"defined in C source `{file}` (Emacs {}, source not installed)",
catalog.data.version
)
}),
Source::Unknown => Some(format!("Emacs {}", catalog.data.version)),
}
}
fn catalog_info(&self, name: &str, space: Space) -> Option<Info> {
let catalog = self.catalog?;
match space {
Space::Function => {
let function = catalog.function(name)?;
let kind = catalog.kind(name);
let role = match function.kind.as_str() {
"special-form" => "Special form",
"macro" => "Macro",
"subr" => "Built-in function",
_ => "Function",
};
let role = if function.autoload {
format!("Autoloaded {}", role.to_lowercase())
} else {
role.to_owned()
};
let mut doc = function.doc.clone();
if let Some(alias) = &function.alias {
let note = format!("Alias for `{alias}'.");
doc = Some(match doc {
Some(text) if !text.is_empty() => format!("{note}\n\n{text}"),
_ => note,
});
}
Some(Info {
usage: function.usage.clone(),
role,
origin: self.emacs_origin(catalog, catalog.function_source(name)),
doc,
feature: None,
source: "emacs",
kind,
})
}
Space::Value => {
let variable = catalog.variable(name)?;
let role = if variable.constant {
"Constant"
} else if variable.special {
"Special variable"
} else {
"Variable"
};
Some(Info {
usage: None,
role: role.to_owned(),
origin: self.emacs_origin(catalog, catalog.variable_source(name)),
doc: variable.doc.clone(),
feature: None,
source: "emacs",
kind: None,
})
}
Space::Feature => {
let path = catalog.library(name)?;
Some(Info {
usage: None,
role: "Feature".into(),
origin: self.emacs_origin(catalog, Source::Lisp(path.to_owned())),
doc: None,
feature: None,
source: "emacs",
kind: None,
})
}
_ => None,
}
}
pub fn info(&self, here: Option<View>, name: &str, space: Space) -> Option<Info> {
let matches = |definition: &&Definition| {
definition.name == name && definition.space == space && !definition.declaration
};
if let Some(view) = here
&& let Some(definition) = view.analysis.definitions.iter().find(matches)
{
return Some(self.definition_info(view, definition, true));
}
for view in self.views() {
if here.is_some_and(|here| here.uri == view.uri) {
continue;
}
if let Some(definition) = view.analysis.definitions.iter().find(matches) {
return Some(self.definition_info(view, definition, false));
}
}
self.catalog_info(name, space)
}
fn render(&self, info: &Info, name: &str, markdown: bool) -> String {
let mut out = String::new();
let title = info.usage.clone().unwrap_or_else(|| name.to_owned());
let summary = match &info.origin {
Some(origin) => format!("{}, {origin}", info.role),
None => info.role.clone(),
};
if markdown {
out.push_str(&format!("```elisp\n{title}\n```\n\n"));
let summary = summary.replace('*', "\\*");
out.push_str(&format!("*{summary}*"));
} else {
out.push_str(&format!("{title}\n{summary}"));
}
if let Some(doc) = info.doc.as_deref().filter(|doc| !doc.trim().is_empty()) {
out.push_str("\n\n");
let body = doc_text(doc.trim_end(), markdown);
if markdown {
out.push_str(&body.replace('\n', " \n"));
} else {
out.push_str(&body);
}
}
out
}
pub fn hover(&self, uri: &str, position: Position) -> Value {
let Some(view) = self.view(uri) else {
return Value::Null;
};
let lines = self.lines(view.text);
let Some(offset) = lines.offset(position) else {
return Value::Null;
};
let Some(target) = Self::target(view, offset) else {
return Value::Null;
};
let markdown = self.supports("/textDocument/hover/contentFormat", "markdown");
let info = if let Some(binder) = target.binder {
let binder = &view.analysis.binders[binder];
Some(Info {
role: if binder.space == Space::Function {
"Local function".into()
} else if binder.dynamic {
"Dynamically bound variable".into()
} else {
"Local variable".into()
},
origin: Some(format!(
"bound at line {}",
line_of(view.text, binder.start)
)),
..Info::default()
})
} else if target.role == Role::Quoted {
self.info(Some(view), &target.name, Space::Function)
.or_else(|| self.info(Some(view), &target.name, Space::Value))
} else {
self.info(Some(view), &target.name, target.space)
};
let Some(info) = info else {
return Value::Null;
};
json!({
"contents": markup(markdown, self.render(&info, &target.name, markdown)),
"range": lines.range(target.start, target.end),
})
}
fn parsed(&self, path: &Path) -> Option<Arc<Parsed>> {
if let Some(found) = self.parsed.lock().ok()?.get(path) {
return Some(Arc::clone(found));
}
let text = String::from_utf8(fs::read(path).ok()?).ok()?;
let tree = Tree::parse_str(&text);
let analysis = analyze(&text, &tree);
let parsed = Arc::new(Parsed {
uri: url::Url::from_file_path(path).ok()?.to_string(),
text,
tree,
analysis,
});
self.parsed
.lock()
.ok()?
.insert(path.to_owned(), Arc::clone(&parsed));
Some(parsed)
}
fn emacs_location(&self, name: &str, space: Space) -> Option<Value> {
let catalog = self.catalog?;
let source = match space {
Space::Function => catalog.function_source(name),
Space::Value => catalog.variable_source(name),
Space::Feature => catalog
.library(name)
.map_or(Source::Unknown, |path| Source::Lisp(path.to_owned())),
_ => Source::Unknown,
};
match source {
Source::Lisp(path) => {
let cache = self.cache?;
let openable = catalog.openable(&path, cache).ok()?;
let parsed = self.parsed(&openable)?;
let lines = self.lines(&parsed.text);
let found: Vec<&Definition> = parsed
.analysis
.definitions
.iter()
.filter(|definition| definition.name == name && definition.space == space)
.collect();
let best: Vec<&&Definition> = found
.iter()
.filter(|definition| !definition.declaration)
.collect();
let chosen: Vec<&Definition> = if best.is_empty() {
found.clone()
} else {
best.into_iter().copied().collect()
};
let ranges: Vec<(usize, usize)> = if chosen.is_empty() {
vec![(0, 0)]
} else {
chosen
.iter()
.map(|definition| definition.selection)
.collect()
};
Some(Value::Array(
ranges
.into_iter()
.map(|(start, end)| json!({"uri": parsed.uri, "range": lines.range(start, end)}))
.collect(),
))
}
Source::C {
path: Some(path), ..
} => {
let text = String::from_utf8_lossy(&fs::read(&path).ok()?).into_owned();
let (start, end) = catalog::c_definition(&text, name, space == Space::Value)?;
let lines = self.lines(&text);
let uri = url::Url::from_file_path(&path).ok()?.to_string();
Some(json!([{"uri": uri, "range": lines.range(start, end)}]))
}
Source::C { path: None, .. } => Some(json!([])),
Source::Unknown => None,
}
}
pub fn definition(&self, uri: &str, position: Position, declaration: bool) -> Value {
let Some(view) = self.view(uri) else {
return Value::Null;
};
let lines = self.lines(view.text);
let Some(offset) = lines.offset(position) else {
return Value::Null;
};
let Some(target) = Self::target(view, offset) else {
return Value::Null;
};
if target.binder.is_some() || target.role == Role::Quoted {
return navigation::definition(uri, &lines, view.analysis, position, declaration);
}
let views = self.views();
let collect = |wanted: bool, here: bool| -> Vec<Value> {
let mut out = Vec::new();
for other in &views {
if (other.uri == view.uri) != here {
continue;
}
let other_lines = self.lines(other.text);
for definition in &other.analysis.definitions {
if definition.name == target.name
&& definition.space == target.space
&& definition.declaration == wanted
{
out.push(json!({
"uri": other.uri,
"range": other_lines.range(definition.selection.0, definition.selection.1),
}));
}
}
}
out
};
let mut fallback = Value::Null;
for wanted in [declaration, !declaration] {
for here in [true, false] {
let found = collect(wanted, here);
if !found.is_empty() {
return Value::Array(found);
}
}
if !wanted && let Some(found) = self.emacs_location(&target.name, target.space) {
if found.as_array().is_some_and(|list| !list.is_empty()) {
return found;
}
fallback = found;
}
}
fallback
}
pub fn references(&self, uri: &str, position: Position, include: bool) -> Value {
let Some(view) = self.view(uri) else {
return json!([]);
};
let lines = self.lines(view.text);
let Some(offset) = lines.offset(position) else {
return json!([]);
};
let Some(target) = Self::target(view, offset) else {
return json!([]);
};
if target.binder.is_some() {
return navigation::references(uri, &lines, view.analysis, position, include);
}
if target.role == Role::Quoted {
return json!([]);
}
let mut views = self.views();
views.sort_by_key(|other| (other.uri != view.uri, other.uri.to_owned()));
let mut out = Vec::new();
for other in views {
let other_lines = self.lines(other.text);
for occurrence in &other.analysis.occurrences {
if occurrence.name == target.name
&& occurrence.space == target.space
&& occurrence.binder.is_none()
&& occurrence.role != Role::Quoted
&& (include
|| !matches!(
occurrence.role,
Role::Definition | Role::Declaration | Role::Binding
))
{
out.push(json!({
"uri": other.uri,
"range": other_lines.range(occurrence.start, occurrence.end),
}));
}
}
}
Value::Array(out)
}
pub fn workspace_symbols(&self, query: &str) -> Value {
let query: Vec<char> = query.to_lowercase().chars().collect();
let matches = |name: &str| {
let mut wanted = query.iter().peekable();
for c in name.to_lowercase().chars() {
if wanted.peek() == Some(&&c) {
wanted.next();
}
}
wanted.peek().is_none()
};
let mut out = Vec::new();
for view in self.views() {
let lines = self.lines(view.text);
let container = file_label(view.uri);
for definition in &view.analysis.definitions {
if definition.declaration
|| definition.name.is_empty()
|| !matches(&definition.name)
{
continue;
}
out.push(json!({
"name": definition.name,
"kind": navigation::symbol_kind(definition),
"location": {
"uri": view.uri,
"range": lines.range(definition.selection.0, definition.selection.1),
},
"containerName": container,
}));
if out.len() >= COMPLETION_LIMIT {
return Value::Array(out);
}
}
}
Value::Array(out)
}
fn enclosing_list<'f>(
items: &'f [Form],
offset: usize,
text: &str,
best: &mut Option<&'f [Form]>,
) {
for form in items {
let (start, end) = form.range();
let unclosed = !text[..end].ends_with(')');
let inside = start < offset && (offset < end || (offset == end && unclosed));
if !inside {
continue;
}
match form {
Form::List { items, .. } => {
*best = Some(items);
Self::enclosing_list(items, offset, text, best);
}
Form::Vector { items, .. } => Self::enclosing_list(items, offset, text, best),
Form::Prefixed {
prefix: Syntax::Quote,
..
} => {}
Form::Prefixed {
inner: Some(inner), ..
} => Self::enclosing_list(std::slice::from_ref(inner), offset, text, best),
_ => {}
}
}
}
fn head_name(view: View, head: &Form) -> Option<String> {
if !matches!(
head,
Form::Atom {
kind: Syntax::Symbol,
..
}
) {
return None;
}
let (start, end) = head.range();
Some(
view.analysis
.occurrences
.iter()
.find(|occurrence| occurrence.start == start)
.map_or_else(
|| view.text[start..end].to_owned(),
|occurrence| occurrence.name.clone(),
),
)
}
fn keyword(view: View, form: &Form) -> Option<String> {
match form {
Form::Atom {
kind: Syntax::Symbol,
start,
end,
} if view.text[*start..*end].starts_with(':') => {
Some(view.text[*start..*end].to_owned())
}
_ => None,
}
}
fn signature_of(&self, view: View, name: &str) -> Option<(Signature, Info)> {
let info = self.info(Some(view), name, Space::Function)?;
let signature = signature::parse_usage(info.usage.as_deref()?)?;
Some((signature, info))
}
fn units(&self, text: &str, byte: usize) -> usize {
match self.encoding {
Encoding::Utf8 => byte,
Encoding::Utf16 => text[..byte].encode_utf16().count(),
Encoding::Utf32 => text[..byte].chars().count(),
}
}
pub fn signature_help(&self, uri: &str, position: Position) -> Value {
let Some(view) = self.view(uri) else {
return Value::Null;
};
let lines = self.lines(view.text);
let Some(offset) = lines.offset(position) else {
return Value::Null;
};
let all = forms(view.tree);
let mut best = None;
Self::enclosing_list(&all, offset, view.text, &mut best);
let Some(items) = best else {
return Value::Null;
};
let Some(head) = items.first() else {
return Value::Null;
};
if head.range().1 >= offset {
return Value::Null;
}
let Some(name) = Self::head_name(view, head) else {
return Value::Null;
};
if view
.analysis
.occurrences
.iter()
.any(|occurrence| occurrence.start == head.range().0 && occurrence.binder.is_some())
{
return Value::Null;
}
let Some((signature, info)) = self.signature_of(view, &name) else {
return Value::Null;
};
let mut args = Vec::new();
let mut current = None;
for item in &items[1..] {
let (start, end) = item.range();
if end < offset || (end == offset && !matches!(item, Form::Atom { .. })) {
args.push(Self::keyword(view, item));
} else if start < offset {
current = Self::keyword(view, item);
break;
} else {
break;
}
}
let active = signature::active_parameter(&signature, &args, current);
let markdown = self.supports(
"/textDocument/signatureHelp/signatureInformation/documentationFormat",
"markdown",
);
let offsets = self.flag(
"/textDocument/signatureHelp/signatureInformation/parameterInformation/labelOffsetSupport",
);
let parameters: Vec<Value> = signature
.parameters
.iter()
.map(|parameter| {
if offsets {
json!({"label": [
self.units(&signature.label, parameter.start),
self.units(&signature.label, parameter.end),
]})
} else {
json!({"label": parameter.label})
}
})
.collect();
let mut information = json!({
"label": signature.label,
"parameters": parameters,
});
if let Some(doc) = info.doc.as_deref().filter(|doc| !doc.trim().is_empty()) {
information["documentation"] = markup(markdown, doc_text(doc.trim_end(), markdown));
}
let none_supported =
self.flag("/textDocument/signatureHelp/signatureInformation/noActiveParameterSupport");
let active_value = match active {
Some(index) => json!(index),
None if none_supported => Value::Null,
None => json!(signature.parameters.len()),
};
information["activeParameter"] = active_value.clone();
json!({
"signatures": [information],
"activeSignature": 0,
"activeParameter": active_value,
})
}
pub(crate) fn calls<'f>(items: &'f [Form], out: &mut Vec<&'f [Form]>) {
for form in items {
match form {
Form::List { items, .. } => {
if !items.is_empty() {
out.push(items);
}
Self::calls(items, out);
}
Form::Vector { .. }
| Form::Prefixed {
prefix: Syntax::Quote,
..
} => {}
Form::Prefixed {
inner: Some(inner), ..
} => Self::calls(std::slice::from_ref(inner), out),
_ => {}
}
}
}
pub fn inlay_hints(&self, uri: &str, range: (usize, usize)) -> Value {
let Some(view) = self.view(uri) else {
return json!([]);
};
let lines = self.lines(view.text);
let all = forms(view.tree);
let mut calls = Vec::new();
Self::calls(&all, &mut calls);
let mut signatures: HashMap<String, Option<Signature>> = HashMap::new();
let mut out = Vec::new();
for items in calls {
let head = &items[0];
let (head_start, _) = head.range();
let Some((call_start, _)) = items.last().map(Form::range) else {
continue;
};
if call_start < range.0 || head_start > range.1 {
continue;
}
let is_call = view.analysis.occurrences.iter().any(|occurrence| {
occurrence.start == head_start
&& occurrence.space == Space::Function
&& occurrence.role == Role::Reference
&& occurrence.binder.is_none()
});
if !is_call {
continue;
}
let Some(name) = Self::head_name(view, head) else {
continue;
};
let signature = signatures
.entry(name.clone())
.or_insert_with(|| {
self.signature_of(view, &name)
.filter(|(_, info)| matches!(info.kind, Some(Kind::Function | Kind::Subr)))
.map(|(signature, _)| signature)
})
.clone();
let Some(signature) = signature else {
continue;
};
let mut args = Vec::new();
let mut rest_labelled = false;
for item in &items[1..] {
let keyword = Self::keyword(view, item);
let index = signature::active_parameter(&signature, &args, None);
args.push(keyword.clone());
let Some(index) = index else { break };
if keyword.is_some() {
continue;
}
let parameter = &signature.parameters[index];
if matches!(parameter.param, signature::Param::Rest) {
if rest_labelled {
continue;
}
rest_labelled = true;
}
let label = parameter
.label
.trim_start_matches(['(', '['])
.split([' ', ')', ']'])
.next()
.unwrap_or_default()
.trim_end_matches("...")
.to_lowercase();
if label.is_empty() {
continue;
}
let (start, end) = item.range();
if start < range.0 || start > range.1 {
continue;
}
if view.text[start..end].eq_ignore_ascii_case(&label) {
continue;
}
out.push((
start,
json!({
"position": lines.position(start),
"label": format!("{label}:"),
"kind": 2,
"paddingRight": true,
"data": {"uri": view.uri, "function": name, "parameter": index},
}),
));
}
}
out.sort_by_key(|(start, _)| *start);
Value::Array(out.into_iter().map(|(_, hint)| hint).collect())
}
pub fn resolve_inlay_hint(&self, mut hint: Value) -> Value {
let tooltip = self.supports(
"/textDocument/inlayHint/resolveSupport/properties",
"tooltip",
);
if !tooltip {
return hint;
}
let uri = hint
.pointer("/data/uri")
.and_then(Value::as_str)
.map(str::to_owned);
let function = hint
.pointer("/data/function")
.and_then(Value::as_str)
.map(str::to_owned);
let (Some(uri), Some(function)) = (uri, function) else {
return hint;
};
let Some(view) = self.view(&uri) else {
return hint;
};
if let Some((signature, info)) = self.signature_of(view, &function) {
let first = info
.doc
.as_deref()
.and_then(|doc| doc.lines().next())
.map(|line| doc_text(line, false))
.unwrap_or_default();
let text = if first.is_empty() {
signature.label
} else {
format!("{}\n{first}", signature.label)
};
hint["tooltip"] = json!(text);
}
hint
}
fn workspace_kinds(&self) -> HashMap<String, Kind> {
let mut out = HashMap::new();
for view in self.views() {
for definition in &view.analysis.definitions {
if definition.space == Space::Function && !definition.declaration {
out.entry(definition.name.clone())
.or_insert_with(|| kind_from_definition(definition));
}
}
}
out
}
pub fn semantic_tokens(&self, uri: &str, range: Option<(usize, usize)>) -> Option<Vec<u32>> {
let view = self.view(uri)?;
let lines = self.lines(view.text);
let env = SemanticEnv {
catalog: self.catalog,
workspace: self.workspace_kinds(),
};
let tokens = semantic::roles(view.text, view.analysis, &env);
let mut data = Vec::new();
let (mut previous_line, mut previous_start) = (0u64, 0u64);
for token in tokens {
if let Some((start, end)) = range
&& (token.end <= start || token.start >= end)
{
continue;
}
let (line, character) = lines.point(token.start);
let (end_line, end_character) = lines.point(token.end);
if line != end_line || end_character <= character {
continue;
}
let line = line as u64;
let delta_line = line - previous_line;
let delta_start = if delta_line == 0 {
character - previous_start
} else {
character
};
let (kind, modifiers) = semantic::lsp_type(&token, &env);
data.extend([
delta_line as u32,
delta_start as u32,
(end_character - character) as u32,
kind,
modifiers,
]);
previous_line = line;
previous_start = character;
}
Some(data)
}
fn visible_binders(view: View, offset: usize) -> Vec<(String, Space)> {
let all = forms(view.tree);
let Some(top) = all
.iter()
.find(|form| form.range().0 <= offset && offset <= form.range().1)
else {
return Vec::new();
};
let (start, _) = top.range();
let mut seen = HashSet::new();
view.analysis
.binders
.iter()
.filter(|binder| binder.start >= start && binder.end <= offset)
.rev()
.filter(|binder| seen.insert((binder.name.clone(), binder.space)))
.map(|binder| (binder.name.clone(), binder.space))
.collect()
}
pub fn completion(&self, uri: &str, position: Position) -> Value {
let Some(view) = self.view(uri) else {
return json!({"isIncomplete": false, "items": []});
};
let lines = self.lines(view.text);
let Some(offset) = lines.offset(position) else {
return json!({"isIncomplete": false, "items": []});
};
if in_text(&view.tree.root, 0, offset, view.text) {
return json!({"isIncomplete": false, "items": []});
}
let before = &view.text[..offset];
let prefix_start = before
.char_indices()
.rev()
.take_while(|(_, c)| symbol_char(*c))
.last()
.map_or(offset, |(index, _)| index);
let prefix = &view.text[prefix_start..offset];
let preceding = view.text[..prefix_start].chars().next_back();
let quoted_function = view.text[..prefix_start].ends_with("#'");
let context = if quoted_function {
"function"
} else if preceding == Some('\'') {
let all = forms(view.tree);
let mut best = None;
Self::enclosing_list(&all, prefix_start, view.text, &mut best);
let feature = best
.and_then(|items| items.first())
.and_then(|head| Self::head_name(view, head))
.is_some_and(|head| FEATURE_HEADS.contains(&head.as_str()));
if feature { "feature" } else { "quoted" }
} else if prefix.starts_with(':') {
"keyword"
} else if preceding == Some('(') {
"function"
} else {
"variable"
};
let mut items: BTreeMap<String, (u32, u32, &'static str, &'static str)> = BTreeMap::new();
let mut add =
|label: &str, kind: u32, rank: u32, space: &'static str, source: &'static str| {
if label.starts_with(prefix) && !label.is_empty() {
items
.entry(label.to_owned())
.or_insert((kind, rank, space, source));
}
};
let wants_functions = matches!(context, "function" | "quoted");
let wants_variables = matches!(context, "variable" | "quoted");
for (name, space) in Self::visible_binders(view, prefix_start) {
match space {
Space::Function if wants_functions => add(&name, 3, 0, "function", "local"),
Space::Value if wants_variables => add(&name, 6, 0, "variable", "local"),
_ => {}
}
}
let views = self.views();
for other in &views {
let source_rank = if other.uri == view.uri { 1 } else { 2 };
let source = if other.uri == view.uri {
"document"
} else {
"workspace"
};
for definition in &other.analysis.definitions {
match definition.space {
Space::Function if wants_functions => {
add(&definition.name, 3, source_rank, "function", source)
}
Space::Value if wants_variables => {
let kind = if definition.kind == "defconst" { 21 } else { 6 };
add(&definition.name, kind, source_rank, "variable", source)
}
Space::Feature if context == "feature" => {
add(&definition.name, 9, source_rank, "feature", source)
}
_ => {}
}
}
if context == "keyword" && other.uri == view.uri {
for &(start, end) in &other.analysis.constants {
add(&other.text[start..end], 14, 1, "keyword", "document");
}
}
}
if let Some(catalog) = self.catalog {
if wants_functions {
for function in &catalog.data.functions {
let kind = if function.kind == "special-form" {
14
} else {
3
};
add(&function.name, kind, 3, "function", "emacs");
}
}
for variable in &catalog.data.variables {
let keyword = variable.name.starts_with(':');
if context == "keyword" && keyword {
add(&variable.name, 14, 3, "keyword", "emacs");
} else if wants_variables && !keyword {
let kind = if variable.constant { 21 } else { 6 };
add(&variable.name, kind, 3, "variable", "emacs");
}
}
if context == "feature" {
for library in catalog.libraries() {
add(library, 9, 3, "feature", "emacs");
}
for feature in &catalog.data.features {
add(feature, 9, 3, "feature", "emacs");
}
}
}
let total = items.len();
let edit_range = lines.range(prefix_start, offset);
let defaults = self.supports(
"/textDocument/completion/completionList/itemDefaults",
"editRange",
);
let mut ordered: Vec<_> = items.into_iter().collect();
ordered.sort_by(|a, b| {
a.1.1
.cmp(&b.1.1)
.then(a.0.len().cmp(&b.0.len()))
.then(a.0.cmp(&b.0))
});
let list: Vec<Value> = ordered
.into_iter()
.take(COMPLETION_LIMIT)
.map(|(label, (kind, rank, space, source))| {
let mut item = json!({
"label": label,
"kind": kind,
"sortText": format!("{rank}{label}"),
"data": {"uri": view.uri, "name": label, "space": space, "source": source},
});
if !defaults {
item["textEdit"] = json!({"range": edit_range, "newText": label});
}
item
})
.collect();
let mut result = json!({
"isIncomplete": total > COMPLETION_LIMIT || prefix.is_empty(),
"items": list,
});
if defaults {
result["itemDefaults"] = json!({"editRange": edit_range});
}
result
}
pub(crate) fn unique_feature(
&self,
target: View<'_>,
name: &str,
space: Space,
feature: &str,
) -> bool {
if feature.is_empty()
|| !feature
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '+'))
{
return false;
}
let views = self.views();
let mut definitions = views.iter().filter(|view| {
view.analysis.definitions.iter().any(|definition| {
definition.name == name && definition.space == space && !definition.declaration
})
});
let Some(provider) = definitions.next() else {
return false;
};
let mut features = provider
.analysis
.definitions
.iter()
.filter(|definition| definition.space == Space::Feature && !definition.declaration);
if definitions.next().is_some()
|| features.next().is_none_or(|found| found.name != feature)
|| features.next().is_some()
|| self
.catalog
.is_some_and(|catalog| catalog.library(feature).is_some())
{
return false;
}
let to_path = |uri: &str| {
url::Url::parse(uri)
.ok()?
.to_file_path()
.ok()?
.canonicalize()
.ok()
};
let Some(provider_path) = to_path(provider.uri) else {
return false;
};
let Some(target_path) = to_path(target.uri).or_else(|| {
let path = url::Url::parse(target.uri).ok()?.to_file_path().ok()?;
Some(path.parent()?.canonicalize().ok()?.join(path.file_name()?))
}) else {
return false;
};
self.workspace.is_some_and(|workspace| {
workspace
.environments
.iter()
.filter(|env| target_path.starts_with(&env.root))
.max_by_key(|env| env.root.components().count())
.and_then(|env| {
env.load_paths.iter().find_map(|entry| {
[".elc", ".el", ".el.gz"].iter().find_map(|suffix| {
entry
.path
.join(format!("{feature}{suffix}"))
.canonicalize()
.ok()
})
})
})
.as_ref()
== Some(&provider_path)
})
}
pub(crate) fn require_edit(&self, view: View, feature: &str) -> Option<Value> {
let lines = self.lines(view.text);
let top = forms(view.tree);
let is_require = |form: &Form| {
form.items()
.and_then(|items| items.first())
.is_some_and(|head| atom_text(head, view.text) == "require")
};
let (offset, text) = if let Some(last) = top.iter().rev().find(|form| is_require(form)) {
(last.range().1, format!("\n(require '{feature})"))
} else if let Some(first) = top.first() {
(first.range().0, format!("(require '{feature})\n\n"))
} else {
(view.text.len(), format!("\n(require '{feature})\n"))
};
Some(json!({"range": lines.range(offset, offset), "newText": text}))
}
pub fn resolve_completion(&self, mut item: Value, additional_edits: bool) -> Value {
let Some(data) = item.get("data").cloned() else {
return item;
};
let text = |key: &str| data.get(key).and_then(Value::as_str).map(str::to_owned);
let (Some(uri), Some(name), Some(space)) = (text("uri"), text("name"), text("space"))
else {
return item;
};
let source = text("source").unwrap_or_default();
let Some(view) = self.view(&uri) else {
return item;
};
let space = match space.as_str() {
"function" => Space::Function,
"feature" => Space::Feature,
_ => Space::Value,
};
let markdown = self.supports(
"/textDocument/completion/completionItem/documentationFormat",
"markdown",
);
if source == "local" {
item["detail"] = json!(if space == Space::Function {
"Local function"
} else {
"Local variable"
});
return item;
}
let Some(info) = self.info(Some(view), &name, space) else {
return item;
};
item["detail"] = json!(info.usage.clone().unwrap_or_else(|| info.role.clone()));
item["documentation"] = markup(markdown, self.render(&info, &name, markdown));
if additional_edits
&& info.source == "workspace"
&& let Some(feature) = &info.feature
&& !workspace::requires(view.analysis).any(|required| required == feature)
&& !view
.analysis
.definitions
.iter()
.any(|definition| definition.space == Space::Feature && &definition.name == feature)
&& let Some(edit) = self.require_edit(view, feature)
{
item["additionalTextEdits"] = json!([edit]);
}
item
}
}
struct SemanticEnv<'a> {
catalog: Option<&'a Catalog>,
workspace: HashMap<String, Kind>,
}
impl semantic::Environment for SemanticEnv<'_> {
fn kind(&self, name: &str) -> Option<Kind> {
self.workspace
.get(name)
.copied()
.or_else(|| self.catalog?.kind(name))
}
fn special(&self, name: &str) -> bool {
self.catalog
.and_then(|catalog| catalog.variable(name))
.is_some_and(|variable| variable.special)
}
fn knows_everything(&self) -> bool {
self.catalog.is_some()
}
fn builtin(&self, name: &str, space: Space) -> bool {
let Some(catalog) = self.catalog else {
return false;
};
match space {
Space::Function => {
!self.workspace.contains_key(name) && catalog.function(name).is_some()
}
Space::Value => catalog.variable(name).is_some(),
_ => false,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn docstrings_become_markdown() {
let doc = "Return `car' of LIST.\nSee \\\\[describe-function] and *x*.";
assert_eq!(
doc_text(doc, true),
"Return `car` of LIST.\nSee `M-x describe-function` and \\*x\\*."
);
assert_eq!(
doc_text(doc, false),
"Return car of LIST.\nSee M-x describe-function and *x*."
);
}
#[test]
fn detects_comments_and_strings() {
let text = "(foo \"ab\" bar) ; note\n(baz \"open";
let tree = Tree::parse_str(text);
let inside = |needle: &str, delta: usize| {
in_text(&tree.root, 0, text.find(needle).unwrap() + delta, text)
};
assert!(inside("ab", 1));
assert!(!inside(" bar", 0));
assert!(!inside("bar", 2));
assert!(inside("note", 4));
assert!(inside("open", 4));
assert!(!inside("baz", 2));
}
#[test]
fn usage_is_rendered_from_arglists() {
let text = "(cl-defun demo (a &optional b &key (test #'eq)) \"Doc.\" a)";
let tree = Tree::parse_str(text);
let all = forms(&tree);
let Form::List { items, .. } = &all[0] else {
panic!()
};
assert_eq!(
usage_from_arglist("demo", &items[2], text).unwrap(),
"(demo A &optional B &key (TEST #'eq))"
);
}
}