kcl_lib/
modules.rs

1use std::fmt;
2
3use anyhow::Result;
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6
7use crate::{
8    errors::{KclError, KclErrorDetails},
9    exec::KclValue,
10    execution::{typed_path::TypedPath, EnvironmentRef, PreImportedGeometry},
11    fs::{FileManager, FileSystem},
12    parsing::ast::types::{ImportPath, Node, Program},
13    source_range::SourceRange,
14};
15
16/// Identifier of a source file.  Uses a u32 to keep the size small.
17#[derive(
18    Debug, Default, Ord, PartialOrd, Eq, PartialEq, Clone, Copy, Hash, Deserialize, Serialize, ts_rs::TS, JsonSchema,
19)]
20#[ts(export)]
21pub struct ModuleId(u32);
22
23impl ModuleId {
24    pub fn from_usize(id: usize) -> Self {
25        Self(u32::try_from(id).expect("module ID should fit in a u32"))
26    }
27
28    pub fn as_usize(&self) -> usize {
29        usize::try_from(self.0).expect("module ID should fit in a usize")
30    }
31
32    /// Top-level file is the one being executed.
33    /// Represented by module ID of 0, i.e. the default value.
34    pub fn is_top_level(&self) -> bool {
35        *self == Self::default()
36    }
37}
38
39impl std::fmt::Display for ModuleId {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        write!(f, "{}", self.0)
42    }
43}
44
45#[derive(Debug, Clone, Default)]
46pub(crate) struct ModuleLoader {
47    /// The stack of import statements for detecting circular module imports.
48    /// If this is empty, we're not currently executing an import statement.
49    pub import_stack: Vec<TypedPath>,
50}
51
52impl ModuleLoader {
53    pub(crate) fn cycle_check(&self, path: &ModulePath, source_range: SourceRange) -> Result<(), KclError> {
54        if self.import_stack.contains(path.expect_path()) {
55            return Err(self.import_cycle_error(path, source_range));
56        }
57        Ok(())
58    }
59
60    pub(crate) fn import_cycle_error(&self, path: &ModulePath, source_range: SourceRange) -> KclError {
61        KclError::new_import_cycle(KclErrorDetails::new(
62            format!(
63                "circular import of modules is not allowed: {} -> {}",
64                self.import_stack
65                    .iter()
66                    .map(|p| p.to_string_lossy())
67                    .collect::<Vec<_>>()
68                    .join(" -> "),
69                path,
70            ),
71            vec![source_range],
72        ))
73    }
74
75    pub(crate) fn enter_module(&mut self, path: &ModulePath) {
76        if let ModulePath::Local { value: ref path } = path {
77            self.import_stack.push(path.clone());
78        }
79    }
80
81    pub(crate) fn leave_module(&mut self, path: &ModulePath) {
82        if let ModulePath::Local { value: ref path } = path {
83            let popped = self.import_stack.pop().unwrap();
84            assert_eq!(path, &popped);
85        }
86    }
87}
88
89pub(crate) fn read_std(mod_name: &str) -> Option<&'static str> {
90    match mod_name {
91        "prelude" => Some(include_str!("../std/prelude.kcl")),
92        "math" => Some(include_str!("../std/math.kcl")),
93        "sketch" => Some(include_str!("../std/sketch.kcl")),
94        "turns" => Some(include_str!("../std/turns.kcl")),
95        "types" => Some(include_str!("../std/types.kcl")),
96        "solid" => Some(include_str!("../std/solid.kcl")),
97        "units" => Some(include_str!("../std/units.kcl")),
98        "array" => Some(include_str!("../std/array.kcl")),
99        "sweep" => Some(include_str!("../std/sweep.kcl")),
100        "appearance" => Some(include_str!("../std/appearance.kcl")),
101        "transform" => Some(include_str!("../std/transform.kcl")),
102        _ => None,
103    }
104}
105
106/// Info about a module.
107#[derive(Debug, Clone, PartialEq, Serialize)]
108pub struct ModuleInfo {
109    /// The ID of the module.
110    pub(crate) id: ModuleId,
111    /// Absolute path of the module's source file.
112    pub(crate) path: ModulePath,
113    pub(crate) repr: ModuleRepr,
114}
115
116impl ModuleInfo {
117    pub(crate) fn take_repr(&mut self) -> ModuleRepr {
118        let mut result = ModuleRepr::Dummy;
119        std::mem::swap(&mut self.repr, &mut result);
120        result
121    }
122
123    pub(crate) fn restore_repr(&mut self, repr: ModuleRepr) {
124        assert!(matches!(&self.repr, ModuleRepr::Dummy));
125        self.repr = repr;
126    }
127}
128
129#[allow(clippy::large_enum_variant)]
130#[derive(Debug, Clone, PartialEq, Serialize)]
131pub enum ModuleRepr {
132    Root,
133    // AST, memory, exported names
134    Kcl(Node<Program>, Option<(Option<KclValue>, EnvironmentRef, Vec<String>)>),
135    Foreign(PreImportedGeometry, Option<KclValue>),
136    Dummy,
137}
138
139#[allow(clippy::large_enum_variant)]
140#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, Hash, ts_rs::TS)]
141#[serde(tag = "type")]
142pub enum ModulePath {
143    // The main file of the project.
144    Main,
145    Local { value: TypedPath },
146    Std { value: String },
147}
148
149impl ModulePath {
150    pub(crate) fn expect_path(&self) -> &TypedPath {
151        match self {
152            ModulePath::Local { value: p } => p,
153            _ => unreachable!(),
154        }
155    }
156
157    pub(crate) async fn source(&self, fs: &FileManager, source_range: SourceRange) -> Result<ModuleSource, KclError> {
158        match self {
159            ModulePath::Local { value: p } => Ok(ModuleSource {
160                source: fs.read_to_string(p, source_range).await?,
161                path: self.clone(),
162            }),
163            ModulePath::Std { value: name } => Ok(ModuleSource {
164                source: read_std(name)
165                    .ok_or_else(|| {
166                        KclError::new_semantic(KclErrorDetails::new(
167                            format!("Cannot find standard library module to import: std::{name}."),
168                            vec![source_range],
169                        ))
170                    })
171                    .map(str::to_owned)?,
172                path: self.clone(),
173            }),
174            ModulePath::Main => unreachable!(),
175        }
176    }
177
178    pub(crate) fn from_import_path(
179        path: &ImportPath,
180        project_directory: &Option<TypedPath>,
181        import_from: &ModulePath,
182    ) -> Result<Self, KclError> {
183        match path {
184            ImportPath::Kcl { filename: path } | ImportPath::Foreign { path } => {
185                let resolved_path = match import_from {
186                    ModulePath::Main => {
187                        if let Some(project_dir) = project_directory {
188                            project_dir.join_typed(path)
189                        } else {
190                            path.clone()
191                        }
192                    }
193                    ModulePath::Local { value } => {
194                        let import_from_dir = value.parent();
195                        let base = import_from_dir.as_ref().or(project_directory.as_ref());
196                        if let Some(dir) = base {
197                            dir.join_typed(path)
198                        } else {
199                            path.clone()
200                        }
201                    }
202                    ModulePath::Std { .. } => {
203                        let message = format!("Cannot import a non-std KCL file from std: {path}.");
204                        debug_assert!(false, "{}", &message);
205                        return Err(KclError::new_internal(KclErrorDetails::new(message, vec![])));
206                    }
207                };
208
209                Ok(ModulePath::Local { value: resolved_path })
210            }
211            ImportPath::Std { path } => Self::from_std_import_path(path),
212        }
213    }
214
215    pub(crate) fn from_std_import_path(path: &[String]) -> Result<Self, KclError> {
216        // For now we only support importing from singly-nested modules inside std.
217        if path.len() != 2 || path[0] != "std" {
218            let message = format!("Invalid std import path: {path:?}.");
219            debug_assert!(false, "{}", &message);
220            return Err(KclError::new_internal(KclErrorDetails::new(message, vec![])));
221        }
222
223        Ok(ModulePath::Std { value: path[1].clone() })
224    }
225}
226
227impl fmt::Display for ModulePath {
228    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229        match self {
230            ModulePath::Main => write!(f, "main"),
231            ModulePath::Local { value: path } => path.fmt(f),
232            ModulePath::Std { value: s } => write!(f, "std::{s}"),
233        }
234    }
235}
236
237#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ts_rs::TS)]
238pub struct ModuleSource {
239    pub path: ModulePath,
240    pub source: String,
241}