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