typst_library/foundations/
module.rs1use std::fmt::{self, Debug, Formatter};
2use std::sync::Arc;
3
4use ecow::{eco_format, EcoString};
5use typst_syntax::FileId;
6
7use crate::diag::{bail, DeprecationSink, StrResult};
8use crate::foundations::{repr, ty, Content, Scope, Value};
9
10#[ty(cast)]
37#[derive(Clone, Hash)]
38#[allow(clippy::derived_hash_with_manual_eq)]
39pub struct Module {
40 name: Option<EcoString>,
42 inner: Arc<Repr>,
44}
45
46#[derive(Debug, Clone, Hash)]
48struct Repr {
49 scope: Scope,
51 content: Content,
53 file_id: Option<FileId>,
55}
56
57impl Module {
58 pub fn new(name: impl Into<EcoString>, scope: Scope) -> Self {
60 Self {
61 name: Some(name.into()),
62 inner: Arc::new(Repr { scope, content: Content::empty(), file_id: None }),
63 }
64 }
65
66 pub fn anonymous(scope: Scope) -> Self {
68 Self {
69 name: None,
70 inner: Arc::new(Repr { scope, content: Content::empty(), file_id: None }),
71 }
72 }
73
74 pub fn with_name(mut self, name: impl Into<EcoString>) -> Self {
76 self.name = Some(name.into());
77 self
78 }
79
80 pub fn with_scope(mut self, scope: Scope) -> Self {
82 Arc::make_mut(&mut self.inner).scope = scope;
83 self
84 }
85
86 pub fn with_content(mut self, content: Content) -> Self {
88 Arc::make_mut(&mut self.inner).content = content;
89 self
90 }
91
92 pub fn with_file_id(mut self, file_id: FileId) -> Self {
94 Arc::make_mut(&mut self.inner).file_id = Some(file_id);
95 self
96 }
97
98 pub fn name(&self) -> Option<&EcoString> {
100 self.name.as_ref()
101 }
102
103 pub fn scope(&self) -> &Scope {
105 &self.inner.scope
106 }
107
108 pub fn file_id(&self) -> Option<FileId> {
112 self.inner.file_id
113 }
114
115 pub fn scope_mut(&mut self) -> &mut Scope {
117 &mut Arc::make_mut(&mut self.inner).scope
118 }
119
120 pub fn field(&self, field: &str, sink: impl DeprecationSink) -> StrResult<&Value> {
122 match self.scope().get(field) {
123 Some(binding) => Ok(binding.read_checked(sink)),
124 None => match &self.name {
125 Some(name) => bail!("module `{name}` does not contain `{field}`"),
126 None => bail!("module does not contain `{field}`"),
127 },
128 }
129 }
130
131 pub fn content(self) -> Content {
133 match Arc::try_unwrap(self.inner) {
134 Ok(repr) => repr.content,
135 Err(arc) => arc.content.clone(),
136 }
137 }
138}
139
140impl Debug for Module {
141 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
142 f.debug_struct("Module")
143 .field("name", &self.name)
144 .field("scope", &self.inner.scope)
145 .field("content", &self.inner.content)
146 .finish()
147 }
148}
149
150impl repr::Repr for Module {
151 fn repr(&self) -> EcoString {
152 match &self.name {
153 Some(module) => eco_format!("<module {module}>"),
154 None => "<module>".into(),
155 }
156 }
157}
158
159impl PartialEq for Module {
160 fn eq(&self, other: &Self) -> bool {
161 self.name == other.name && Arc::ptr_eq(&self.inner, &other.inner)
162 }
163}