use std::fmt::{self, Debug, Formatter};
use std::sync::Arc;
use ecow::{EcoString, eco_format};
use typst_syntax::FileId;
use crate::diag::{DeprecationSink, StrResult, bail};
use crate::foundations::{Content, Scope, Value, repr, ty};
#[ty(cast)]
#[derive(Clone, Hash)]
#[allow(clippy::derived_hash_with_manual_eq)]
pub struct Module {
name: Option<EcoString>,
inner: Arc<Repr>,
}
#[derive(Debug, Clone, Hash)]
struct Repr {
scope: Scope,
content: Content,
file_id: Option<FileId>,
}
impl Module {
pub fn new(name: impl Into<EcoString>, scope: Scope) -> Self {
Self {
name: Some(name.into()),
inner: Arc::new(Repr { scope, content: Content::empty(), file_id: None }),
}
}
pub fn anonymous(scope: Scope) -> Self {
Self {
name: None,
inner: Arc::new(Repr { scope, content: Content::empty(), file_id: None }),
}
}
pub fn with_name(mut self, name: impl Into<EcoString>) -> Self {
self.name = Some(name.into());
self
}
pub fn with_scope(mut self, scope: Scope) -> Self {
Arc::make_mut(&mut self.inner).scope = scope;
self
}
pub fn with_content(mut self, content: Content) -> Self {
Arc::make_mut(&mut self.inner).content = content;
self
}
pub fn with_file_id(mut self, file_id: FileId) -> Self {
Arc::make_mut(&mut self.inner).file_id = Some(file_id);
self
}
pub fn name(&self) -> Option<&EcoString> {
self.name.as_ref()
}
pub fn scope(&self) -> &Scope {
&self.inner.scope
}
pub fn file_id(&self) -> Option<FileId> {
self.inner.file_id
}
pub fn scope_mut(&mut self) -> &mut Scope {
&mut Arc::make_mut(&mut self.inner).scope
}
pub fn field(&self, field: &str, sink: impl DeprecationSink) -> StrResult<&Value> {
match self.scope().get(field) {
Some(binding) => Ok(binding.read_checked(sink)),
None => match &self.name {
Some(name) => bail!("module `{name}` does not contain `{field}`"),
None => bail!("module does not contain `{field}`"),
},
}
}
pub fn content(self) -> Content {
match Arc::try_unwrap(self.inner) {
Ok(repr) => repr.content,
Err(arc) => arc.content.clone(),
}
}
}
impl Debug for Module {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_struct("Module")
.field("name", &self.name)
.field("scope", &self.inner.scope)
.field("content", &self.inner.content)
.finish()
}
}
impl repr::Repr for Module {
fn repr(&self) -> EcoString {
match &self.name {
Some(module) => eco_format!("<module {module}>"),
None => "<module>".into(),
}
}
}
impl PartialEq for Module {
fn eq(&self, other: &Self) -> bool {
self.name == other.name && Arc::ptr_eq(&self.inner, &other.inner)
}
}