use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use super::{Id, Server, error};
use crate::analysis::{Role, Space, forms};
use crate::catalog::Kind;
use crate::diagnostic_generation::{Generation, accept_diagnostics};
use crate::diagnostics::{self, Action, Diagnostic};
use crate::oracle::{Input, Job, Report};
use serde_json::{Value, json};
type Response = Result<Value, (i32, &'static str)>;
const CHANGED: (i32, &str) = (-32801, "The diagnostic snapshot has changed");
const SAVE_DEBOUNCE: Duration = Duration::from_millis(100);
struct DocumentReport {
open_epoch: u64,
generation: Option<Generation>,
static_items: Vec<Diagnostic>,
header_action: Option<Action>,
eval_items: Vec<Value>,
result_id: u64,
action_id: u64,
published: bool,
}
impl DocumentReport {
fn new(open_epoch: u64) -> Self {
Self {
open_epoch,
generation: None,
static_items: Vec::new(),
header_action: None,
eval_items: Vec::new(),
result_id: 0,
action_id: 0,
published: false,
}
}
fn items(&self) -> Vec<&Value> {
self.static_items
.iter()
.map(|item| &item.value)
.chain(self.eval_items.iter())
.collect()
}
fn actions(&self) -> impl Iterator<Item = (usize, Option<&Value>, &Action)> {
self.static_items
.iter()
.enumerate()
.filter_map(|(i, diagnostic)| {
Some((i, Some(&diagnostic.value), diagnostic.action.as_ref()?))
})
.chain(
self.header_action
.iter()
.map(|action| (self.static_items.len(), None, action)),
)
}
}
struct Expansion {
form: String,
id: Id,
raw_id: Value,
}
struct Running {
job: Job,
uri: String,
generation: Generation,
progress_id: String,
progress_started: bool,
expansion: Option<Expansion>,
}
#[derive(Default)]
pub(super) struct Diagnostics {
docs: HashMap<String, DocumentReport>,
dependency: u64,
config: u64,
saved: BTreeMap<String, Instant>,
attempted: HashMap<String, Generation>,
running: Option<Running>,
expansion_cache: HashMap<(String, String), Value>,
refresh_pending: Option<String>,
refresh_dirty: bool,
}
fn file_path(uri: &str) -> Option<PathBuf> {
url::Url::parse(uri).ok()?.to_file_path().ok()
}
fn target_uri(params: &Value) -> Option<&str> {
params.pointer("/textDocument/uri")?.as_str()
}
fn point(position: &Value) -> Option<(u64, u64)> {
Some((
position.get("line")?.as_u64()?,
position.get("character")?.as_u64()?,
))
}
fn range(value: &Value) -> Option<((u64, u64), (u64, u64))> {
let start = point(value.get("start")?)?;
let end = point(value.get("end")?)?;
(start <= end).then_some((start, end))
}
impl Server<'_> {
pub(super) fn next_result(&mut self) -> u64 {
self.result_ids = self.result_ids.checked_add(1).expect("result ID overflow");
self.result_ids
}
pub(super) fn has_capability(&self, pointer: &str) -> bool {
self.client.pointer(pointer).and_then(Value::as_bool) == Some(true)
}
pub(super) fn pull_diagnostics(&self) -> bool {
self.client
.pointer("/textDocument/diagnostic")
.is_some_and(Value::is_object)
}
pub(super) fn diagnostic_open(&mut self, uri: &str) {
let epoch = self.next_result();
self.diagnostics
.docs
.insert(uri.to_owned(), DocumentReport::new(epoch));
self.dependencies_changed();
}
pub(super) fn diagnostic_change(&mut self, uri: &str) {
self.diagnostics.saved.remove(uri);
self.dependencies_changed();
}
pub(super) fn diagnostic_save(&mut self, uri: &str) {
self.diagnostics
.saved
.insert(uri.to_owned(), Instant::now());
self.dependencies_changed();
}
pub(super) fn diagnostic_close(&mut self, uri: &str) {
let previous = self.diagnostics.docs.remove(uri);
self.diagnostics.saved.remove(uri);
self.diagnostics.attempted.remove(uri);
self.dependencies_changed();
if !self.pull_diagnostics() && previous.is_some_and(|report| report.published) {
self.outbox.push(json!({
"jsonrpc": "2.0", "method": "textDocument/publishDiagnostics",
"params": {"uri": uri, "diagnostics": []}
}));
}
}
pub(super) fn check_trust(&mut self, log: bool) {
let old = self.trust.epoch();
if log {
self.refresh_trust();
} else {
let _ = self.trust.refresh(self.config_dir.as_deref());
}
if self.trust.epoch() != old {
self.reload_environment = true;
self.invalidate_diagnostics();
}
}
pub(super) fn dependencies_changed(&mut self) {
self.diagnostics.dependency += 1;
self.invalidate_diagnostics();
}
pub(super) fn diagnostic_config_changed(&mut self) {
self.diagnostics.config += 1;
self.reload_environment = true;
self.check_trust(true);
self.invalidate_diagnostics();
}
fn invalidate_diagnostics(&mut self) {
self.diagnostics.expansion_cache.clear();
self.stop_oracle(CHANGED);
self.update_static_diagnostics();
}
fn generation(&self, uri: &str) -> Option<Generation> {
let version = self.documents.get(uri)?.version;
let report = self.diagnostics.docs.get(uri)?;
Some(Generation {
open_epoch: report.open_epoch.into(),
doc_version: u64::from(version as u32).into(),
dep_gen: self.diagnostics.dependency.into(),
config_gen: self.diagnostics.config.into(),
trust_epoch: self.trust.epoch().into(),
})
}
pub(super) fn update_static_diagnostics(&mut self) {
let mut uris: Vec<_> = self.diagnostics.docs.keys().cloned().collect();
uris.sort();
for uri in uris {
let Some(generation) = self.generation(&uri) else {
continue;
};
let Some(world) = self.world() else {
continue;
};
let Some(view) = world.view(&uri) else {
continue;
};
let (items, header) = diagnostics::collect(&world, view);
let id = self.next_result();
let report = self.diagnostics.docs.get_mut(&uri).expect("open document");
let stale = report.generation.as_ref() != Some(&generation);
let visible_change = (stale && !report.eval_items.is_empty())
|| !report
.static_items
.iter()
.map(|item| &item.value)
.eq(items.iter().map(|item| &item.value));
if stale {
report.eval_items.clear();
}
if stale || report.static_items != items || report.header_action != header {
report.action_id = id;
}
report.generation = Some(generation);
report.static_items = items;
report.header_action = header;
if visible_change || report.result_id == 0 {
report.result_id = id;
self.publish_diagnostics(&uri);
if visible_change {
self.refresh_diagnostics();
}
}
}
}
fn publish_diagnostics(&mut self, uri: &str) {
if self.pull_diagnostics() {
return;
}
let current = self.generation(uri);
let Some(report) = self.diagnostics.docs.get_mut(uri) else {
return;
};
let Some(completed) = report.generation.clone() else {
return;
};
if !accept_diagnostics(current, completed) {
return;
}
let diagnostics = report.items();
if diagnostics.is_empty() && !report.published {
return;
}
let version = self.documents.get(uri).expect("open document").version;
let mut params = json!({"uri": uri, "diagnostics": diagnostics});
if self.has_versioned_diagnostics() {
params["version"] = json!(version);
}
self.diagnostics
.docs
.get_mut(uri)
.expect("open document")
.published = !params["diagnostics"]
.as_array()
.expect("diagnostics array")
.is_empty();
self.outbox.push(json!({
"jsonrpc": "2.0", "method": "textDocument/publishDiagnostics", "params": params
}));
}
fn has_versioned_diagnostics(&self) -> bool {
self.has_capability("/textDocument/publishDiagnostics/versionSupport")
}
fn refresh_diagnostics(&mut self) {
if !self.pull_diagnostics() || !self.has_capability("/workspace/diagnostics/refreshSupport")
{
return;
}
if self.diagnostics.refresh_pending.is_some() {
self.diagnostics.refresh_dirty = true;
return;
}
let id = format!("elsmith:diagnostics:{}", self.next_result());
self.diagnostics.refresh_pending = Some(id.clone());
self.outbox.push(json!({
"jsonrpc": "2.0", "id": id, "method": "workspace/diagnostic/refresh"
}));
}
pub(super) fn diagnostic_response(&mut self, id: &str, succeeded: bool) -> bool {
if self.diagnostics.refresh_pending.as_deref() == Some(id) {
self.diagnostics.refresh_pending = None;
if std::mem::take(&mut self.diagnostics.refresh_dirty) && succeeded {
self.refresh_diagnostics();
}
return true;
}
if let Some(running) = &mut self.diagnostics.running
&& running.progress_id == id
{
if succeeded && !running.progress_started {
running.progress_started = true;
self.outbox.push(json!({
"jsonrpc": "2.0", "method": "$/progress",
"params": {"token": id, "value": {"kind": "begin", "title": "Checking Emacs Lisp", "cancellable": true}}
}));
}
return true;
}
id.starts_with("elsmith:progress:")
}
pub(super) fn diagnostic_request(&self, params: &Value) -> Response {
let uri = target_uri(params).ok_or((-32602, "Expected a text document URI"))?;
let previous = params.get("previousResultId").and_then(Value::as_str);
Ok(self.diagnostic_report(uri, previous))
}
fn diagnostic_report(&self, uri: &str, previous: Option<&str>) -> Value {
let current = self.generation(uri);
if let Some(report) = self.diagnostics.docs.get(uri)
&& let Some(completed) = report.generation.clone()
&& accept_diagnostics(current, completed)
{
let id = report.result_id.to_string();
return if previous == Some(&id) {
json!({"kind": "unchanged", "resultId": id})
} else {
json!({"kind": "full", "resultId": id, "items": report.items()})
};
}
let world = self.world().expect("initialized session");
let items = world
.view(uri)
.map_or_else(Vec::new, |view| diagnostics::collect(&world, view).0);
json!({"kind": "full", "items": items.into_iter().map(|item| item.value).collect::<Vec<_>>()})
}
pub(super) fn workspace_diagnostics(&self, params: &Value) -> Response {
let previous: HashMap<_, _> = params
.get("previousResultIds")
.and_then(Value::as_array)
.ok_or((-32602, "Expected an array of previous diagnostic results"))?
.iter()
.map(|item| {
item.get("uri")
.and_then(Value::as_str)
.zip(item.get("value").and_then(Value::as_str))
.ok_or((-32602, "Invalid previous diagnostic result"))
})
.collect::<Result<_, _>>()?;
let indexed = self
.workspace
.get()
.into_iter()
.flat_map(|workspace| workspace.files())
.filter(|file| !file.dependency)
.map(|file| file.uri.as_str());
let uris: BTreeSet<_> = self
.diagnostics
.docs
.keys()
.map(String::as_str)
.chain(indexed)
.chain(previous.keys().copied())
.collect();
let items: Vec<_> = uris
.into_iter()
.map(|uri| {
let mut report = self.diagnostic_report(uri, previous.get(uri).copied());
report["uri"] = json!(uri);
report["version"] = json!(self.documents.get(uri).map(|document| document.version));
report
})
.collect();
Ok(json!({"items": items}))
}
pub(super) fn code_actions(&self, params: &Value) -> Response {
let uri = target_uri(params).ok_or((-32602, "Expected a text document URI"))?;
let (start, end) = params
.get("range")
.and_then(range)
.ok_or((-32602, "Expected a range"))?;
let Some(report) = self.diagnostics.docs.get(uri) else {
return Ok(json!([]));
};
let lazy = self.has_capability("/textDocument/codeAction/dataSupport")
&& self
.client
.pointer("/textDocument/codeAction/resolveSupport/properties")
.and_then(Value::as_array)
.is_some_and(|properties| properties.iter().any(|property| property == "edit"));
let only = params.pointer("/context/only").and_then(Value::as_array);
let actions: Vec<_> = report
.actions()
.filter(|(_, diagnostic, action)| {
only.is_none_or(|kinds| {
kinds.iter().filter_map(Value::as_str).any(|kind| {
action.kind == kind
|| action
.kind
.strip_prefix(kind)
.is_some_and(|suffix| suffix.starts_with('.'))
})
}) && diagnostic.is_none_or(|diagnostic| {
range(&diagnostic["range"]).is_some_and(|(a, b)| a <= end && start <= b)
})
})
.map(|(i, diagnostic, action)| {
let mut item = json!({"title": action.title, "kind": action.kind});
if let Some(diagnostic) = diagnostic {
item["diagnostics"] = json!([diagnostic]);
}
if lazy {
item["data"] = json!({"uri": uri, "snapshot": report.action_id, "action": i});
} else {
item["edit"] = self.action_edit(uri, action);
}
item
})
.collect();
Ok(json!(actions))
}
pub(super) fn resolve_code_action(&self, mut item: Value) -> Response {
let data = item
.get("data")
.ok_or((-32602, "Expected code action data"))?;
let uri = data
.get("uri")
.and_then(Value::as_str)
.ok_or((-32602, "Expected a text document URI"))?;
let snapshot = data.get("snapshot").and_then(Value::as_u64);
let index = data.get("action").and_then(Value::as_u64);
let report = self
.diagnostics
.docs
.get(uri)
.filter(|report| Some(report.action_id) == snapshot)
.ok_or(CHANGED)?;
let (_, _, action) = report
.actions()
.find(|(i, _, _)| Some(*i as u64) == index)
.ok_or((-32602, "Unknown code action"))?;
if item.get("title").and_then(Value::as_str) != Some(&action.title)
|| item.get("kind").and_then(Value::as_str) != Some(action.kind)
{
return Err((-32602, "Code action does not match its data"));
}
let edit = self.action_edit(uri, action);
item["edit"] = edit;
Ok(item)
}
fn action_edit(&self, uri: &str, action: &Action) -> Value {
if self.has_capability("/workspace/workspaceEdit/documentChanges") {
let version = self.documents.get(uri).map(|doc| doc.version);
json!({"documentChanges": [{"textDocument": {"uri": uri, "version": version}, "edits": action.edit}]})
} else {
json!({"changes": {uri: action.edit}})
}
}
fn oracle_input(&self, uri: &str, form: Option<String>) -> Option<Input> {
let world = self.world()?;
let catalog = world.catalog?;
let view = world.view(uri)?;
let original = file_path(uri)?;
let file = original.canonicalize().ok()?;
let roots = &world.workspace?.environments;
let env = self
.workspaces
.iter()
.filter(|root| original.starts_with(root))
.max_by_key(|root| root.components().count())
.and_then(|root| root.canonicalize().ok())
.and_then(|root| roots.iter().find(|env| env.root == root))
.or_else(|| {
roots
.iter()
.filter(|env| file.starts_with(&env.root))
.max_by_key(|env| env.root.components().count())
})?;
if file.extension()? != "el"
|| view.tree.errors() != 0
|| !self.trust.permits(&env.root, &[&file])
|| (form.is_none() && !matches_disk(&file, view.text))
{
return None;
}
let mut load_paths: Vec<_> = env
.load_paths
.iter()
.map(|entry| entry.path.clone())
.collect();
if let Some(parent) = file.parent()
&& !load_paths.iter().any(|dir| dir == parent)
{
load_paths.push(parent.to_owned());
}
let targets: Vec<_> = load_paths.iter().map(PathBuf::as_path).collect();
if !self.trust.permits(&env.root, &targets) {
return None;
}
let views = world.views();
let mut pending = vec![view.analysis];
let mut visited = HashSet::from([file.clone()]);
while let Some(analysis) = pending.pop() {
for import in &analysis.imports {
let mut candidates = dependency_paths(&load_paths, &import.file);
if let Some(feature) = &import.feature {
candidates.extend(
views
.iter()
.filter(|view| {
view.analysis.definitions.iter().any(|definition| {
definition.space == Space::Feature
&& &definition.name == feature
})
})
.filter_map(|view| file_path(view.uri)),
);
}
for path in candidates {
if !self.trust.permits(&env.root, &[&path]) {
return None;
}
let canonical = path.canonicalize().ok()?;
if !visited.insert(canonical.clone()) {
continue;
}
if let Some(dependency) = views.iter().find(|view| {
file_path(view.uri)
.and_then(|file| file.canonicalize().ok())
.as_ref()
== Some(&canonical)
}) {
if self.documents.get(dependency.uri).is_some()
&& !matches_disk(&canonical, dependency.text)
{
return None;
}
pending.push(dependency.analysis);
}
}
}
}
Some(Input {
emacs: catalog.emacs.clone(),
file,
load_paths,
text: view.text.to_owned(),
form,
})
}
fn start_oracle(
&mut self,
uri: String,
generation: Generation,
input: &Input,
expansion: Option<Expansion>,
) -> std::io::Result<()> {
let job = Job::start(input)?;
let progress_id = format!("elsmith:progress:{}", self.next_result());
if self.has_capability("/window/workDoneProgress") {
self.outbox.push(json!({
"jsonrpc": "2.0", "id": progress_id, "method": "window/workDoneProgress/create",
"params": {"token": progress_id}
}));
}
self.diagnostics.running = Some(Running {
job,
uri,
generation,
progress_id,
progress_started: false,
expansion,
});
Ok(())
}
fn end_progress(&mut self, running: &Running) {
if running.progress_started {
self.outbox.push(json!({
"jsonrpc": "2.0", "method": "$/progress",
"params": {"token": running.progress_id, "value": {"kind": "end"}}
}));
}
}
pub(super) fn stop_oracle(&mut self, reason: (i32, &'static str)) {
if let Some(mut running) = self.diagnostics.running.take() {
self.end_progress(&running);
if let Some(expansion) = running.expansion.take()
&& let Some(request) = self.pending.remove(&expansion.id)
&& request.claim(reason.0 == -32800).is_some()
{
self.outbox
.push(error(&expansion.raw_id, reason.0, reason.1));
}
}
}
pub(super) fn cancel_oracle(&mut self, id: Option<&Id>, token: Option<&str>) -> bool {
let cancel = self.diagnostics.running.as_ref().is_some_and(|job| {
token == Some(job.progress_id.as_str()) && job.progress_started
|| job
.expansion
.as_ref()
.is_some_and(|expansion| id == Some(&expansion.id))
});
if cancel {
self.stop_oracle((-32800, "Request cancelled"));
}
cancel
}
pub(super) fn oracle_pending(&self) -> bool {
self.diagnostics.running.is_some()
|| self
.diagnostics
.saved
.values()
.any(|saved| saved.elapsed() < SAVE_DEBOUNCE)
}
pub(super) fn poll_oracle(&mut self) {
if let Some(running) = &mut self.diagnostics.running {
let result = match running.job.poll() {
Ok(None) => return,
Ok(Some(result)) => Ok(result),
Err(err) => Err(err),
};
let mut running = self.diagnostics.running.take().expect("oracle was running");
self.end_progress(&running);
if !accept_diagnostics(self.generation(&running.uri), running.generation) {
return;
}
if let Some(expansion) = running.expansion.take() {
if let Some(request) = self.pending.remove(&expansion.id)
&& request.claim(false).is_some()
{
self.outbox.push(match result {
Ok(result) => {
self.diagnostics
.expansion_cache
.insert((running.uri, expansion.form), result.clone());
json!({"jsonrpc": "2.0", "id": expansion.raw_id, "result": result})
}
Err(err) => {
let _ = writeln!(self.log, "Emacs macro expansion failed: {err}");
error(&expansion.raw_id, -32603, "Emacs macro expansion failed")
}
});
}
} else {
match result.and_then(|result| {
serde_json::from_value::<Report>(result).map_err(std::io::Error::from)
}) {
Ok(oracle) => {
let (status, count, message) = oracle.package_status();
let _ = writeln!(
self.log,
"package-lint: {status}, {count} findings{}",
message.map_or(String::new(), |message| format!(" ({message})"))
);
let doc = self
.documents
.get(&running.uri)
.expect("accepted open document");
let world = self.world().expect("initialized session");
let items = oracle.diagnostics(&doc.text, world.encoding);
let id = self.next_result();
let report = self
.diagnostics
.docs
.get_mut(&running.uri)
.expect("accepted open document");
if report.eval_items != items {
report.eval_items = items;
report.result_id = id;
self.publish_diagnostics(&running.uri);
self.refresh_diagnostics();
}
}
Err(err) => {
let _ = writeln!(self.log, "Emacs diagnostics failed: {err}");
}
}
}
}
let uris: Vec<_> = self
.diagnostics
.saved
.iter()
.filter(|(_, saved)| saved.elapsed() >= SAVE_DEBOUNCE)
.map(|(uri, _)| uri.clone())
.collect();
for uri in uris {
let Some(generation) = self.generation(&uri) else {
continue;
};
if self.diagnostics.attempted.get(&uri) == Some(&generation) {
continue;
}
if !self.loaders_ready() {
break;
}
self.diagnostics
.attempted
.insert(uri.clone(), generation.clone());
let Some(input) = self.oracle_input(&uri, None) else {
continue;
};
match self.start_oracle(uri, generation, &input, None) {
Ok(()) => break,
Err(err) => {
let _ = writeln!(self.log, "Could not start Emacs diagnostics: {err}");
}
}
}
}
pub(super) fn expand_macro(
&mut self,
params: &Value,
id: Id,
raw_id: Value,
) -> Result<Option<Value>, (i32, &'static str)> {
let args = params
.get("arguments")
.and_then(Value::as_array)
.filter(|args| args.len() == 1)
.ok_or((-32602, "Expected one macro location"))?;
let uri = args[0]
.get("uri")
.and_then(Value::as_str)
.ok_or((-32602, "Expected a text document URI"))?;
let position =
serde_json::from_value(args[0].get("position").cloned().unwrap_or(Value::Null))
.map_err(|_| (-32602, "Expected a position"))?;
self.ensure_loaded();
self.check_trust(false);
let generation = self
.generation(uri)
.ok_or((-32602, "Open the document before expanding a macro"))?;
let world = self.world().expect("initialized session");
let view = world.view(uri).ok_or((-32602, "Unknown document"))?;
let lines = crate::navigation::Lines::new(view.text, world.encoding);
let offset = lines
.offset(position)
.ok_or((-32602, "Invalid macro position"))?;
let forms = forms(view.tree);
let mut calls = Vec::new();
crate::intel::World::calls(&forms, &mut calls);
let call = calls.into_iter().find(|call| {
let (start, end) = call[0].range();
start <= offset && offset < end
});
let call = call.ok_or((-32602, "Select the macro name in a call"))?;
let (start, _) = call[0].range();
let site = view
.analysis
.occurrence_at(start)
.filter(|site| {
site.start == start
&& site.role == Role::Reference
&& site.space == Space::Function
&& site.binder.is_none()
})
.ok_or((-32602, "Select a project macro"))?;
let info = world
.info(Some(view), &site.name, Space::Function)
.filter(|info| info.kind == Some(Kind::Macro) && info.source != "emacs")
.ok_or((-32602, "Select a project macro"))?;
if info.feature.as_ref().is_some_and(|feature| {
!view
.analysis
.imports
.iter()
.any(|import| import.feature.as_ref() == Some(feature))
}) {
return Err((-32602, "Require the macro's feature before expanding it"));
}
let form = call_range(view.text, &forms, start)
.ok_or((-32602, "Unknown macro call"))?
.to_owned();
let key = (uri.to_owned(), form.clone());
let input = self.oracle_input(uri, Some(form.clone())).ok_or((
-32602,
"Macro expansion requires a trusted workspace with saved dependencies",
))?;
if let Some(expanded) = self.diagnostics.expansion_cache.get(&key) {
return Ok(Some(expanded.clone()));
}
if self
.diagnostics
.running
.as_ref()
.is_some_and(|job| job.expansion.is_some())
{
return Err((-32603, "Another macro expansion is in progress"));
}
if let Some(running) = &self.diagnostics.running {
self.diagnostics.attempted.remove(&running.uri);
}
self.stop_oracle((-32800, "Request cancelled"));
self.start_oracle(
uri.to_owned(),
generation,
&input,
Some(Expansion { form, id, raw_id }),
)
.map_err(|_| (-32603, "Could not start Emacs"))?;
Ok(None)
}
}
fn matches_disk(path: &Path, text: &str) -> bool {
fs::read_to_string(path)
.is_ok_and(|disk| disk == text || disk.replace("\r\n", "\n") == text.replace("\r\n", "\n"))
}
fn dependency_paths(load_paths: &[PathBuf], filename: &str) -> Vec<PathBuf> {
load_paths
.iter()
.find_map(|dir| {
let path = dir.join(filename);
let paths: Vec<_> = ["", ".el", ".elc", ".el.gz", ".elc.gz", ".so", ".dylib"]
.into_iter()
.map(|suffix| {
let mut name = path.as_os_str().to_owned();
name.push(suffix);
PathBuf::from(name)
})
.filter(|path| path.is_file())
.collect();
(!paths.is_empty()).then_some(paths)
})
.unwrap_or_default()
}
fn call_range<'a>(text: &'a str, forms: &[crate::analysis::Form], head: usize) -> Option<&'a str> {
use crate::analysis::Form;
for form in forms {
let (start, end) = form.range();
if !(start < head && head < end) {
continue;
}
if let Some(items) = form.items() {
if items.first().is_some_and(|item| item.range().0 == head) {
return text.get(start..end);
}
return call_range(text, items, head);
}
if let Form::Prefixed {
inner: Some(inner), ..
} = form
{
return call_range(text, std::slice::from_ref(inner), head);
}
}
None
}