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::{DeprecationSink, StrResult, bail};
8use crate::foundations::{Content, Scope, Value, repr, ty};
9
10/// A collection of variables and functions that are commonly related to
11/// a single theme.
12///
13/// A module can
14/// - be built-in
15/// - stem from a [file import]($scripting/#modules)
16/// - stem from a [package import]($scripting/#packages) (and thus indirectly
17///   its entrypoint file)
18/// - result from a call to the [plugin]($plugin) function
19///
20/// You can access definitions from the module using [field access
21/// notation]($scripting/#fields) and interact with it using the [import and
22/// include syntaxes]($scripting/#modules).
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/// [conditionally access]($category/foundations/std/#conditional-access)
38/// definitions in a module.
39///
40/// ```example
41/// #("table" in std) \
42/// #("nope" in std)
43/// ```
44///
45/// Alternatively, it is possible to convert a module to a dictionary, and
46/// therefore access its contents dynamically, using the [dictionary
47/// constructor]($dictionary/#constructor).
48#[ty(cast)]
49#[derive(Clone, Hash)]
50#[allow(clippy::derived_hash_with_manual_eq)]
51pub struct Module {
52    /// The module's name.
53    name: Option<EcoString>,
54    /// The reference-counted inner fields.
55    inner: Arc<Repr>,
56}
57
58/// The internal representation.
59#[derive(Debug, Clone, Hash)]
60struct Repr {
61    /// The top-level definitions that were bound in this module.
62    scope: Scope,
63    /// The module's layoutable contents.
64    content: Content,
65    /// The id of the file which defines the module, if any.
66    file_id: Option<FileId>,
67}
68
69impl Module {
70    /// Create a new module.
71    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    /// Create a new anonymous module without a name.
79    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    /// Update the module's name.
87    pub fn with_name(mut self, name: impl Into<EcoString>) -> Self {
88        self.name = Some(name.into());
89        self
90    }
91
92    /// Update the module's scope.
93    pub fn with_scope(mut self, scope: Scope) -> Self {
94        Arc::make_mut(&mut self.inner).scope = scope;
95        self
96    }
97
98    /// Update the module's content.
99    pub fn with_content(mut self, content: Content) -> Self {
100        Arc::make_mut(&mut self.inner).content = content;
101        self
102    }
103
104    /// Update the module's file id.
105    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    /// Get the module's name.
111    pub fn name(&self) -> Option<&EcoString> {
112        self.name.as_ref()
113    }
114
115    /// Access the module's scope.
116    pub fn scope(&self) -> &Scope {
117        &self.inner.scope
118    }
119
120    /// Access the module's file id.
121    ///
122    /// Some modules are not associated with a file, like the built-in modules.
123    pub fn file_id(&self) -> Option<FileId> {
124        self.inner.file_id
125    }
126
127    /// Access the module's scope, mutably.
128    pub fn scope_mut(&mut self) -> &mut Scope {
129        &mut Arc::make_mut(&mut self.inner).scope
130    }
131
132    /// Try to access a definition in the module.
133    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    /// Extract the module's content.
144    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}