typst_library/foundations/
module.rs

1use 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/// An module of definitions.
11///
12/// A module
13/// - be built-in
14/// - stem from a [file import]($scripting/#modules)
15/// - stem from a [package import]($scripting/#packages) (and thus indirectly
16///   its entrypoint file)
17/// - result from a call to the [plugin]($plugin) function
18///
19/// You can access definitions from the module using [field access
20/// notation]($scripting/#fields) and interact with it using the [import and
21/// include syntaxes]($scripting/#modules). Alternatively, it is possible to
22/// convert a module to a dictionary, and therefore access its contents
23/// dynamically, using the [dictionary constructor]($dictionary/#constructor).
24///
25/// # Example
26/// ```example
27/// <<< #import "utils.typ"
28/// <<< #utils.add(2, 5)
29///
30/// <<< #import utils: sub
31/// <<< #sub(1, 4)
32/// >>> #7
33/// >>>
34/// >>> #(-3)
35/// ```
36#[ty(cast)]
37#[derive(Clone, Hash)]
38#[allow(clippy::derived_hash_with_manual_eq)]
39pub struct Module {
40    /// The module's name.
41    name: Option<EcoString>,
42    /// The reference-counted inner fields.
43    inner: Arc<Repr>,
44}
45
46/// The internal representation.
47#[derive(Debug, Clone, Hash)]
48struct Repr {
49    /// The top-level definitions that were bound in this module.
50    scope: Scope,
51    /// The module's layoutable contents.
52    content: Content,
53    /// The id of the file which defines the module, if any.
54    file_id: Option<FileId>,
55}
56
57impl Module {
58    /// Create a new module.
59    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    /// Create a new anonymous module without a name.
67    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    /// Update the module's name.
75    pub fn with_name(mut self, name: impl Into<EcoString>) -> Self {
76        self.name = Some(name.into());
77        self
78    }
79
80    /// Update the module's scope.
81    pub fn with_scope(mut self, scope: Scope) -> Self {
82        Arc::make_mut(&mut self.inner).scope = scope;
83        self
84    }
85
86    /// Update the module's content.
87    pub fn with_content(mut self, content: Content) -> Self {
88        Arc::make_mut(&mut self.inner).content = content;
89        self
90    }
91
92    /// Update the module's file id.
93    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    /// Get the module's name.
99    pub fn name(&self) -> Option<&EcoString> {
100        self.name.as_ref()
101    }
102
103    /// Access the module's scope.
104    pub fn scope(&self) -> &Scope {
105        &self.inner.scope
106    }
107
108    /// Access the module's file id.
109    ///
110    /// Some modules are not associated with a file, like the built-in modules.
111    pub fn file_id(&self) -> Option<FileId> {
112        self.inner.file_id
113    }
114
115    /// Access the module's scope, mutably.
116    pub fn scope_mut(&mut self) -> &mut Scope {
117        &mut Arc::make_mut(&mut self.inner).scope
118    }
119
120    /// Try to access a definition in the module.
121    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    /// Extract the module's content.
132    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}