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>,
project: Arc<Project>,
generation: u64,
}
impl Namespace {
pub(crate) fn new(language: Arc<dyn Language>, project: Arc<Project>, generation: u64) -> Self {
Self {
language,
project,
generation,
}
}
pub fn generation(&self) -> u64 {
self.generation
}
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 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
}
}