Skip to main content

typst_library/foundations/
module.rs

1use 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/// A collection of variables and functions that are commonly related to a
11/// single theme.
12///
13/// A module can
14/// - be built-in
15/// - stem from a @reference:scripting:modules[file import]
16/// - stem from a @reference:scripting:packages[package import] (and thus
17///   indirectly its entrypoint file)
18/// - result from a call to the @plugin[plugin] function
19///
20/// You can access definitions from the module using
21/// @reference:scripting:fields[field access notation] and interact with it
22/// using the @reference:scripting:modules[import and include syntaxes].
23///
24/// ```example
25/// <<< #import "utils.typ"
26/// <<< #utils.add(2, 5)
27///
28/// <<< #import utils: sub
29/// <<< #sub(1, 4)
30/// >>> #7
31/// >>>
32/// >>> #(-3)
33/// ```
34///
35/// You can check whether a definition is present in a module using the `{in}`
36/// operator, with a string on the left-hand side. This can be useful to
37/// @std:conditional-access[conditionally access] definitions in a module.
38///
39/// ```example
40/// #("table" in std) \
41/// #("nope" in std)
42/// ```
43///
44/// Alternatively, it is possible to convert a module to a dictionary, and
45/// therefore access its contents dynamically, using the
46/// @dictionary.constructor[dictionary constructor].
47#[ty(cast)]
48#[derive(Clone, Hash)]
49pub struct Module {
50    /// The module's name.
51    name: Option<EcoString>,
52    /// The reference-counted inner fields.
53    inner: Arc<ModuleInner>,
54}
55
56/// The internal representation of a [`Module`].
57#[derive(Debug, Clone, Hash)]
58struct ModuleInner {
59    /// The top-level definitions that were bound in this module.
60    scope: Scope,
61    /// The module's layoutable contents.
62    content: Content,
63    /// The id of the file which defines the module, if any.
64    file_id: Option<FileId>,
65}
66
67impl Module {
68    /// Create a new module.
69    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    /// Create a new anonymous module without a name.
81    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    /// Update the module's name.
93    pub fn with_name(mut self, name: impl Into<EcoString>) -> Self {
94        self.name = Some(name.into());
95        self
96    }
97
98    /// Update the module's scope.
99    pub fn with_scope(mut self, scope: Scope) -> Self {
100        Arc::make_mut(&mut self.inner).scope = scope;
101        self
102    }
103
104    /// Update the module's content.
105    pub fn with_content(mut self, content: Content) -> Self {
106        Arc::make_mut(&mut self.inner).content = content;
107        self
108    }
109
110    /// Update the module's file id.
111    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    /// Get the module's name.
117    pub fn name(&self) -> Option<&EcoString> {
118        self.name.as_ref()
119    }
120
121    /// Access the module's scope.
122    pub fn scope(&self) -> &Scope {
123        &self.inner.scope
124    }
125
126    /// Access the module's file id.
127    ///
128    /// Some modules are not associated with a file, like the built-in modules.
129    pub fn file_id(&self) -> Option<FileId> {
130        self.inner.file_id
131    }
132
133    /// Access the module's scope, mutably.
134    pub fn scope_mut(&mut self) -> &mut Scope {
135        &mut Arc::make_mut(&mut self.inner).scope
136    }
137
138    /// Try to access a definition in the module.
139    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    /// Extract the module's content.
150    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}