use std::collections::{BTreeMap, HashMap, HashSet};
use serde::Deserialize;
use serde_json::{Value, json};
use crate::analysis::{Occurrence, Role, Space, macro_definition};
use crate::catalog::Kind;
use crate::intel::{View, World};
use crate::navigation::Lines;
use crate::position::Position;
type Span = (usize, usize);
#[derive(Clone, Copy)]
struct Function<'a> {
view: View<'a>,
name: &'a str,
range: Span,
selection: Span,
binder: Option<usize>,
body_start: usize,
}
impl Function<'_> {
fn contains(self, offset: usize) -> bool {
self.body_start <= offset && offset < self.range.1
}
fn item(self, world: &World) -> Value {
let lines = Lines::new(self.view.text, world.encoding);
json!({
"name": self.name,
"kind": 12,
"uri": self.view.uri,
"range": lines.range(self.range.0, self.range.1),
"selectionRange": lines.range(self.selection.0, self.selection.1),
})
}
}
struct Functions<'a> {
files: Vec<View<'a>>,
by_file: HashMap<&'a str, Vec<Function<'a>>>,
globals: HashMap<&'a str, Vec<Function<'a>>>,
macros: HashSet<&'a str>,
}
impl<'a> Functions<'a> {
fn new(world: &World<'a>) -> Self {
let mut files = world.views();
files.sort_unstable_by_key(|view| view.uri);
let mut by_file = HashMap::new();
let mut globals: HashMap<_, Vec<_>> = HashMap::new();
let mut macros = HashSet::new();
for &view in &files {
let mut items = Vec::new();
for def in &view.analysis.definitions {
if def.space == Space::Function && macro_definition(&def.kind) {
macros.insert(def.name.as_str());
}
if def.space != Space::Function
|| def.declaration
|| !matches!(
def.kind.as_str(),
"defun"
| "cl-defun"
| "defsubst"
| "cl-defsubst"
| "iter-defun"
| "cl-iter-defun"
| "cl-defmethod"
)
{
continue;
}
let function = Function {
view,
name: &def.name,
range: def.range,
selection: def.selection,
binder: None,
body_start: def.range.0,
};
globals.entry(function.name).or_default().push(function);
items.push(function);
}
for function in &view.analysis.local_functions {
let binder = &view.analysis.binders[function.binder];
if view
.analysis
.opaque
.iter()
.any(|&(start, end)| start <= binder.start && binder.end <= end)
{
continue;
}
items.push(Function {
view,
name: &binder.name,
range: function.range,
selection: (binder.start, binder.end),
binder: Some(function.binder),
body_start: function.body_start,
});
}
by_file.insert(view.uri, items);
}
Self {
files,
by_file,
globals,
macros,
}
}
fn file(&self, uri: &str) -> &[Function<'a>] {
self.by_file.get(uri).map_or(&[], Vec::as_slice)
}
fn target(&self, view: View, occ: &Occurrence) -> Option<Function<'a>> {
if occ.space != Space::Function || !occ.certain || occ.role == Role::Quoted {
return None;
}
if let Some(id) = occ.binder {
return self
.file(view.uri)
.iter()
.copied()
.find(|function| function.binder == Some(id));
}
let functions = self.globals.get(occ.name.as_str())?;
let mut here = functions
.iter()
.copied()
.filter(|function| function.view.uri == view.uri);
if let Some(function) = here.next() {
return here.next().is_none().then_some(function);
}
(functions.len() == 1).then_some(functions[0])
}
fn calls(&self, world: &World, view: View<'a>) -> Vec<&'a Occurrence> {
let mut opaque = view.analysis.opaque.clone();
opaque.extend(
view.analysis
.unmodeled_calls
.iter()
.filter_map(|&(site, range)| {
let occ = &view.analysis.occurrences[site];
(occ.binder.is_none()
&& (self.macros.contains(occ.name.as_str())
|| world.catalog.and_then(|catalog| catalog.kind(&occ.name))
== Some(Kind::Macro)))
.then_some(range)
}),
);
view.analysis
.calls
.iter()
.map(|&index| &view.analysis.occurrences[index])
.filter(|occ| {
occ.certain
&& !opaque
.iter()
.any(|&(start, end)| start <= occ.start && occ.end <= end)
})
.collect()
}
fn owner(&self, view: View, offset: usize) -> Option<Function<'a>> {
self.file(view.uri)
.iter()
.copied()
.filter(|function| function.contains(offset))
.min_by_key(|function| function.range.1 - function.range.0)
}
}
pub(crate) fn prepare(world: &World, uri: &str, position: Position) -> Option<Value> {
let view = world.view(uri)?;
let offset = Lines::new(view.text, world.encoding).offset(position)?;
let functions = Functions::new(world);
let target = if let Some(occ) = view.analysis.occurrence_at(offset) {
functions.target(view, occ)
} else {
functions.owner(view, offset)
}?;
Some(json!([target.item(world)]))
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct Item {
uri: String,
name: String,
selection_range: Selection,
}
#[derive(Deserialize)]
struct Selection {
start: Position,
end: Position,
}
pub(crate) fn calls(world: &World, item: Item, incoming: bool) -> Option<Value> {
let functions = Functions::new(world);
let view = world.view(&item.uri)?;
let lines = Lines::new(view.text, world.encoding);
let selection = (
lines.offset(item.selection_range.start)?,
lines.offset(item.selection_range.end)?,
);
let selected = functions
.file(view.uri)
.iter()
.copied()
.find(|function| function.selection == selection && function.name == item.name)?;
let selected_key = (selected.view.uri, selected.selection);
let mut grouped: BTreeMap<_, (Function<'_>, Vec<Span>)> = BTreeMap::new();
let files = if incoming {
functions.files.as_slice()
} else {
std::slice::from_ref(&view)
};
for &file in files {
for occ in functions.calls(world, file) {
let Some(owner) = functions.owner(file, occ.start) else {
continue;
};
let Some(callee) = functions.target(file, occ) else {
continue;
};
let (source, other) = if incoming {
(callee, owner)
} else {
(owner, callee)
};
if (source.view.uri, source.selection) == selected_key {
grouped
.entry((other.view.uri, other.selection))
.or_insert_with(|| (other, Vec::new()))
.1
.push((occ.start, occ.end));
}
}
}
let result: Vec<_> = grouped
.into_values()
.map(|(other, mut ranges)| {
let source = if incoming { other } else { selected };
let lines = Lines::new(source.view.text, world.encoding);
ranges.sort_unstable();
ranges.dedup();
let ranges: Vec<_> = ranges
.into_iter()
.map(|(start, end)| lines.range(start, end))
.collect();
json!({(if incoming {"from"} else {"to"}): other.item(world), "fromRanges": ranges})
})
.collect();
Some(json!(result))
}