use std::path::Path;
use std::sync::{Arc, OnceLock, RwLock};
use super::{Declared, Fragment, Namespace, Scope};
use crate::{Match, MatchId, Placed, RelPath, SourceFile};
use vvv_core::{Facts, Language, LanguageId, Project, Query, RawMatch, SearchError};
use crate::EngineError;
#[derive(Clone)]
pub struct Candidate {
pub(super) source: Arc<SourceFacts>,
fragment: Arc<PerBuild<Fragment>>,
scope: Arc<PerBuild<Scope>>,
}
pub(super) struct SourceFacts {
file: Arc<SourceFile>,
language: Arc<dyn Language>,
facts: OnceLock<Result<Facts, SearchError>>,
}
impl SourceFacts {
pub(super) fn file(&self) -> &SourceFile {
&self.file
}
pub(super) fn path(&self) -> &Path {
self.file.path()
}
pub(super) fn facts(&self) -> Result<&Facts, EngineError> {
self.facts
.get_or_init(|| self.file.facts(self.language.as_ref()))
.as_ref()
.map_err(|source| EngineError::Search {
path: self.path().into(),
source: source.clone(),
})
}
}
struct PerBuild<T> {
slot: RwLock<Option<(Arc<Project>, Arc<T>)>>,
}
impl<T> PerBuild<T> {
fn empty() -> Self {
Self {
slot: RwLock::new(None),
}
}
fn get_or_build(
&self,
project: &Arc<Project>,
valid: impl Fn(&T) -> bool,
build: impl FnOnce() -> Result<T, EngineError>,
) -> Result<Arc<T>, EngineError> {
if let Some((_, value)) = self
.slot
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.as_ref()
.filter(|(built, value)| Arc::ptr_eq(built, project) && valid(value))
{
return Ok(value.clone());
}
let value = Arc::new(build()?);
*self
.slot
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) =
Some((project.clone(), value.clone()));
Ok(value)
}
}
impl Candidate {
pub(crate) fn placed(&self, declared: &Declared) -> Placed {
Placed {
path: self.path().into(),
symbol: declared.symbol.clone(),
start: self
.file()
.source()
.position(declared.symbol.name_span.start),
address: declared.address.clone(),
reach: declared.reach.clone(),
}
}
pub fn new(file: SourceFile, language: Arc<dyn Language>) -> Self {
Self {
source: Arc::new(SourceFacts {
file: Arc::new(file),
language,
facts: OnceLock::new(),
}),
fragment: Arc::new(PerBuild::empty()),
scope: Arc::new(PerBuild::empty()),
}
}
pub fn fragment(&self, ns: &Namespace) -> Result<Arc<Fragment>, EngineError> {
self.fragment.get_or_build(
ns.project(),
|fragment| fragment.is_current(ns),
|| Fragment::build(&self.source, ns),
)
}
pub fn scope(&self, ns: &Namespace) -> Result<Arc<Scope>, EngineError> {
let fragment = self.fragment(ns)?;
self.scope.get_or_build(
ns.project(),
|scope| scope.is_current(&fragment),
|| Ok(Scope::new(ns, self.path(), &fragment)),
)
}
pub fn facts(&self) -> Result<&Facts, EngineError> {
self.source.facts()
}
pub fn file(&self) -> &SourceFile {
&self.source.file
}
pub fn path(&self) -> &Path {
self.source.file.path()
}
pub fn text(&self) -> &str {
self.source.file.text()
}
pub fn language(&self) -> LanguageId {
self.source.language.id()
}
pub fn contains_all(&self, words: &[&str]) -> bool {
let text = self.source.file.text();
let is_word = |b: u8| b.is_ascii_alphanumeric() || b == b'_' || !b.is_ascii();
words.iter().all(|word| {
text.match_indices(word).any(|(start, _)| {
let end = start + word.len();
let before = start.checked_sub(1).map(|i| text.as_bytes()[i]);
let after = text.as_bytes().get(end).copied();
!before.is_some_and(is_word) && !after.is_some_and(is_word)
})
})
}
pub fn find(&self, query: &Query) -> Result<Vec<Match>, EngineError> {
let raw = self
.file()
.find(self.source.language.as_ref(), query)
.map_err(|source| self.failed(source))?;
Ok(raw.into_iter().map(|raw| self.locate(raw)).collect())
}
pub(crate) fn validate_matches(
&self,
query: &Query,
matches: &[Match],
) -> Result<(), EngineError> {
if query.language().is_some_and(|id| *id != self.language()) {
return Err(crate::ApplyError::Stale {
path: self.path().into(),
}
.into());
}
let current = self.find(query)?;
if matches
.iter()
.any(|held| !current.iter().any(|fresh| held.same_source_match(fresh)))
{
return Err(crate::ApplyError::Stale {
path: self.path().into(),
}
.into());
}
Ok(())
}
pub fn references(&self, name: &str) -> Result<Vec<Match>, EngineError> {
let facts = self.facts()?;
Ok(facts
.tokens_named(name)
.map(|(span, kind)| {
let raw = RawMatch::plain(span, kind, &self.text()[span.start..span.end]);
self.locate(raw)
})
.collect())
}
pub(crate) fn locate(&self, raw: RawMatch) -> Match {
let file = self.file();
let source = file.source();
let start = source.position(raw.span.start);
let path = RelPath::from(file.path());
Match {
content: Some(file.content_id()),
id: MatchId::derive(&path, raw.span, &raw.text),
path,
language: self.language(),
span: raw.span,
start,
end: source.position(raw.span.end),
line: source
.line(start.line as usize)
.unwrap_or_default()
.to_owned(),
kind: raw.kind,
text: raw.text,
captures: raw.captures,
symbol: raw.symbol,
role: raw.role,
address: None,
}
}
fn failed(&self, source: SearchError) -> EngineError {
EngineError::Search {
path: self.path().into(),
source,
}
}
}