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::{StrResult, WarningSink, bail};
8use crate::foundations::{Content, Repr, Scope, Value, ty};
9
10#[ty(cast)]
48#[derive(Clone, Hash)]
49pub struct Module {
50 name: Option<EcoString>,
52 inner: Arc<ModuleInner>,
54}
55
56#[derive(Debug, Clone, Hash)]
58struct ModuleInner {
59 scope: Scope,
61 content: Content,
63 file_id: Option<FileId>,
65}
66
67impl Module {
68 pub fn new(name: impl Into<EcoString>, scope: Scope) -> Self {
70 Self {
71 name: Some(name.into()),
72 inner: Arc::new(ModuleInner {
73 scope,
74 content: Content::empty(),
75 file_id: None,
76 }),
77 }
78 }
79
80 pub fn anonymous(scope: Scope) -> Self {
82 Self {
83 name: None,
84 inner: Arc::new(ModuleInner {
85 scope,
86 content: Content::empty(),
87 file_id: None,
88 }),
89 }
90 }
91
92 pub fn with_name(mut self, name: impl Into<EcoString>) -> Self {
94 self.name = Some(name.into());
95 self
96 }
97
98 pub fn with_scope(mut self, scope: Scope) -> Self {
100 Arc::make_mut(&mut self.inner).scope = scope;
101 self
102 }
103
104 pub fn with_content(mut self, content: Content) -> Self {
106 Arc::make_mut(&mut self.inner).content = content;
107 self
108 }
109
110 pub fn with_file_id(mut self, file_id: FileId) -> Self {
112 Arc::make_mut(&mut self.inner).file_id = Some(file_id);
113 self
114 }
115
116 pub fn name(&self) -> Option<&EcoString> {
118 self.name.as_ref()
119 }
120
121 pub fn scope(&self) -> &Scope {
123 &self.inner.scope
124 }
125
126 pub fn file_id(&self) -> Option<FileId> {
130 self.inner.file_id
131 }
132
133 pub fn scope_mut(&mut self) -> &mut Scope {
135 &mut Arc::make_mut(&mut self.inner).scope
136 }
137
138 pub fn field(&self, field: &str, sink: impl WarningSink) -> StrResult<&Value> {
140 match self.scope().get(field) {
141 Some(binding) => Ok(binding.read_checked(sink)),
142 None => match &self.name {
143 Some(name) => bail!("module `{name}` does not contain `{field}`"),
144 None => bail!("module does not contain `{field}`"),
145 },
146 }
147 }
148
149 pub fn content(self) -> Content {
151 match Arc::try_unwrap(self.inner) {
152 Ok(repr) => repr.content,
153 Err(arc) => arc.content.clone(),
154 }
155 }
156}
157
158impl Debug for Module {
159 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
160 f.debug_struct("Module")
161 .field("name", &self.name)
162 .field("scope", &self.inner.scope)
163 .field("content", &self.inner.content)
164 .finish()
165 }
166}
167
168impl Repr for Module {
169 fn repr(&self) -> EcoString {
170 match &self.name {
171 Some(module) => eco_format!("<module {module}>"),
172 None => "<module>".into(),
173 }
174 }
175}
176
177impl PartialEq for Module {
178 fn eq(&self, other: &Self) -> bool {
179 self.name == other.name && Arc::ptr_eq(&self.inner, &other.inner)
180 }
181}