use std::path::{Path, PathBuf};
use std::sync::Arc;
use vvv_core::{
Address, Language, LanguageId, Layout, Project, ResolveError, Semantics, Surgery, Symbol,
SymbolKind,
};
use crate::{EngineError, Reach};
#[derive(Clone)]
pub struct Namespace {
language: Arc<dyn Language>,
cancellation: Option<crate::ReadCancellation>,
project: Arc<Project>,
pub(super) sources:
Arc<std::collections::BTreeMap<PathBuf, Arc<super::candidate::SourceFacts>>>,
}
impl Namespace {
pub(super) fn new(
language: Arc<dyn Language>,
cancellation: Option<crate::ReadCancellation>,
project: Arc<Project>,
sources: Arc<std::collections::BTreeMap<PathBuf, Arc<super::candidate::SourceFacts>>>,
) -> Self {
Self {
language,
cancellation,
project,
sources,
}
}
pub(super) fn check_read(&self) -> Result<(), EngineError> {
self.cancellation
.as_ref()
.map_or(Ok(()), crate::ReadCancellation::check)
}
pub fn id(&self) -> LanguageId {
self.language.id()
}
pub fn language(&self) -> &Arc<dyn Language> {
&self.language
}
pub fn layout(&self) -> &dyn Layout {
self.language
.layout()
.expect("a namespace exists only for a language with a layout")
}
pub fn surgery(&self) -> Result<&dyn Surgery, EngineError> {
self.language
.surgery()
.ok_or_else(|| EngineError::NoLayout(self.id()))
}
pub fn semantics(&self) -> &'static Semantics {
self.language.semantics()
}
pub fn project(&self) -> &Arc<Project> {
&self.project
}
pub(super) fn module_sources(
&self,
module: &Address,
) -> Vec<Arc<super::candidate::SourceFacts>> {
self.layout()
.candidates(self.project(), module)
.into_iter()
.filter_map(|path| self.sources.get(&path).cloned())
.filter(|source| self.address(source.path()).as_ref().ok() == Some(module))
.collect()
}
pub fn address(&self, path: &Path) -> Result<Address, ResolveError> {
self.layout().address(&self.project, path)
}
pub fn resolve(&self, from: &Path, import: &vvv_core::ModulePath) -> Option<Address> {
self.layout().resolve(&self.project, from, import)
}
pub fn is_addressable(&self, kind: SymbolKind) -> bool {
self.semantics().is_addressable(kind)
}
pub fn address_of(&self, module: &Address, symbol: &Symbol) -> Option<Address> {
self.is_addressable(symbol.kind)
.then(|| module.join(symbol.name.as_str()))
}
pub fn reach(&self, module: &Address, symbol: &Symbol) -> Reach {
Reach::of(self.semantics().reach_kind(symbol.modifier()), module, None)
}
pub fn file_of(&self, address: &Address) -> Option<PathBuf> {
let mut at = Some(address.clone());
while let Some(a) = at {
if let Some(file) = self
.layout()
.candidates(&self.project, &a)
.into_iter()
.find(|p| self.project.files.contains(p))
{
return Some(file);
}
at = a.parent();
}
None
}
}