use super::symbols::{self, Sym};
use super::{canonical, position_at};
use htl::typeindex::{TypeIndex, Use};
use lsp_types::{Position, Range};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Place {
pub file: Arc<Path>,
pub line: usize,
pub col: usize,
}
impl Place {
pub fn of(declared: &htl::typeindex::Place) -> Option<Self> {
let path = canonical(&declared.file);
path.is_file().then(|| Self {
file: path.into(),
line: declared.line,
col: declared.col,
})
}
}
#[derive(Debug, Clone)]
pub struct Ref {
pub line: usize,
pub col: usize,
pub range: Range,
pub declared: Place,
pub call: bool,
}
#[derive(Debug, Clone, Default)]
pub struct FileRefs {
pub refs: Vec<Ref>,
pub syms: Vec<Sym>,
pub deps: Option<HashSet<PathBuf>>,
}
impl FileRefs {
pub fn enclosing(&self, at: Position) -> Option<usize> {
self.syms
.iter()
.enumerate()
.filter_map(|(i, s)| {
s.body
.filter(|b| s.is_function() && b.start <= at && at <= b.end)
.map(|b| (i, b))
})
.max_by_key(|(_, b)| b.start)
.map(|(i, _)| i)
}
}
pub fn collect(text: &str, types: &TypeIndex, deps: impl IntoIterator<Item = PathBuf>) -> FileRefs {
let lines = super::lines_of(text);
let mut files: HashMap<PathBuf, Option<Arc<Path>>> = HashMap::new();
let mut refs = Vec::new();
for Use {
line,
col,
end,
declared,
call,
} in types.uses(text)
{
let file = files
.entry(declared.file.clone())
.or_insert_with(|| Place::of(&declared).map(|p| p.file))
.clone();
let Some(file) = file else {
continue;
};
refs.push(Ref {
line,
col,
range: Range::new(
position_at(&lines, line, col),
position_at(&lines, line, end),
),
declared: Place {
file,
line: declared.line,
col: declared.col,
},
call,
});
}
FileRefs {
refs,
syms: types
.declarations()
.map(|decls| symbols::flatten(text, decls))
.unwrap_or_default(),
deps: Some(deps.into_iter().collect()),
}
}