use super::refs::{FileRefs, Place};
use super::spelling::Spelling;
use super::symbols::{self, Entry, Sym, SymbolIndex};
use super::{lines_of, position_at, read_lossy};
use lsp_types::{
CallHierarchyIncomingCall, CallHierarchyItem, CallHierarchyOutgoingCall, Position, Range,
SymbolKind, Uri,
};
use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
pub struct Ctx<'a> {
pub root: &'a Path,
pub spelling: &'a Spelling<'a>,
}
impl Ctx<'_> {
fn uri_for(&self, canonical: &Path) -> Option<Uri> {
self.spelling.client_uri_canonical(canonical)
}
}
pub enum Which {
Function {
at: [(usize, usize); 2],
name: String,
},
Chunk,
}
pub fn data_of(sym: &Sym) -> Value {
json!({
"at": [[sym.at[0].0, sym.at[0].1], [sym.at[1].0, sym.at[1].1]],
"name": sym.name,
})
}
fn chunk_data() -> Value {
json!({ "chunk": true })
}
pub fn which(data: &Value) -> Option<Which> {
if data.get("chunk") == Some(&Value::Bool(true)) {
return Some(Which::Chunk);
}
let pair = |v: &Value| Some((v[0].as_u64()? as usize, v[1].as_u64()? as usize));
let at = data.get("at")?;
Some(Which::Function {
at: [pair(&at[0])?, pair(&at[1])?],
name: data.get("name")?.as_str()?.to_string(),
})
}
pub fn item(uri: Uri, sym: &Sym) -> CallHierarchyItem {
CallHierarchyItem {
name: sym.name.clone(),
kind: sym.kind,
tags: None,
detail: sym.detail.clone(),
uri,
range: sym.full,
selection_range: sym.range,
data: Some(data_of(sym)),
}
}
fn chunk_item(ctx: &Ctx, canonical: &Path, e: &Entry, uri: Uri) -> CallHierarchyItem {
let name = canonical
.strip_prefix(ctx.root)
.ok()
.or_else(|| canonical.file_name().map(Path::new))
.unwrap_or(canonical)
.display()
.to_string();
let text = read_lossy(&e.path);
let lines = lines_of(&text);
let end = position_at(
&lines,
lines.len().max(1),
lines.last().map_or(1, |l| l.len() + 1),
);
CallHierarchyItem {
name,
kind: SymbolKind::FILE,
tags: None,
detail: None,
uri,
range: Range::new(Position::new(0, 0), end),
selection_range: Range::default(),
data: Some(chunk_data()),
}
}
pub fn places(file: &Path, sym: &Sym) -> Vec<Place> {
let file: Arc<Path> = file.into();
let mut at = vec![sym.at[0], sym.at[1]];
at.extend(sym.same.map(|pair| pair[1]));
at.into_iter()
.map(|(line, col)| Place {
file: file.clone(),
line,
col,
})
.collect()
}
pub fn resolve<'a>(
index: &'a SymbolIndex,
canonical: &Path,
data: &Value,
) -> Option<(&'a Entry, &'a FileRefs, Option<usize>)> {
let e = index.entry(canonical)?;
let fr = e.refs.as_ref()?;
match which(data)? {
Which::Chunk => Some((e, fr, None)),
Which::Function { at, name } => {
let i = fr
.syms
.iter()
.position(|s| s.is_function() && s.at == at && s.name == name)?;
Some((e, fr, Some(i)))
}
}
}
pub fn incoming(
index: &SymbolIndex,
ctx: &Ctx,
class: &[Place],
) -> (Vec<CallHierarchyIncomingCall>, bool) {
let (mut out, mut gone) = (Vec::new(), false);
for (canonical, e) in index.iter() {
let Some(fr) = &e.refs else {
continue;
};
let mut groups: BTreeMap<Option<usize>, Vec<Range>> = BTreeMap::new();
for r in fr
.refs
.iter()
.filter(|r| r.call && class.contains(&r.declared))
{
groups
.entry(fr.enclosing(r.range.start))
.or_default()
.push(r.range);
}
if groups.is_empty() {
continue;
}
let Some(uri) = e.path.is_file().then(|| ctx.uri_for(canonical)).flatten() else {
gone = true;
continue;
};
for (from, from_ranges) in groups {
out.push(CallHierarchyIncomingCall {
from: match from {
Some(i) => item(uri.clone(), &fr.syms[i]),
None => chunk_item(ctx, canonical, e, uri.clone()),
},
from_ranges,
});
}
}
(out, gone)
}
pub fn outgoing(
index: &SymbolIndex,
ctx: &Ctx,
fr: &FileRefs,
from: Option<usize>,
) -> (Vec<CallHierarchyOutgoingCall>, bool) {
let mut groups: BTreeMap<(PathBuf, usize), Vec<Range>> = BTreeMap::new();
for r in fr
.refs
.iter()
.filter(|r| r.call && fr.enclosing(r.range.start) == from)
{
let Some(to) = index.entry(&r.declared.file).and_then(|e| e.refs.as_ref()) else {
continue;
};
let Some(i) = symbols::find(&to.syms, (r.declared.line, r.declared.col)) else {
continue;
};
if to.syms[i].is_function() {
groups
.entry((r.declared.file.to_path_buf(), i))
.or_default()
.push(r.range);
}
}
let (mut out, mut gone) = (Vec::new(), false);
for ((file, i), from_ranges) in groups {
let Some(e) = index.entry(&file) else {
continue;
};
let Some(sym) = e
.refs
.as_ref()
.and_then(|f| f.syms.get(i))
.filter(|_| e.path.is_file())
else {
gone = true;
continue;
};
if let Some(uri) = ctx.uri_for(&file) {
out.push(CallHierarchyOutgoingCall {
to: item(uri, sym),
from_ranges,
});
}
}
(out, gone)
}