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::ImportCycle(KclErrorDetails {
62            message: 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            source_ranges: 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        "transform" => Some(include_str!("../std/transform.kcl")),
100        _ => None,
101    }
102}
103
104/// Info about a module.
105#[derive(Debug, Clone, PartialEq, Serialize)]
106pub struct ModuleInfo {
107    /// The ID of the module.
108    pub(crate) id: ModuleId,
109    /// Absolute path of the module's source file.
110    pub(crate) path: ModulePath,
111    pub(crate) repr: ModuleRepr,
112}
113
114impl ModuleInfo {
115    pub(crate) fn take_repr(&mut self) -> ModuleRepr {
116        let mut result = ModuleRepr::Dummy;
117        std::mem::swap(&mut self.repr, &mut result);
118        result
119    }
120
121    pub(crate) fn restore_repr(&mut self, repr: ModuleRepr) {
122        assert!(matches!(&self.repr, ModuleRepr::Dummy));
123        self.repr = repr;
124    }
125}
126
127#[allow(clippy::large_enum_variant)]
128#[derive(Debug, Clone, PartialEq, Serialize)]
129pub enum ModuleRepr {
130    Root,
131    // AST, memory, exported names
132    Kcl(Node<Program>, Option<(Option<KclValue>, EnvironmentRef, Vec<String>)>),
133    Foreign(PreImportedGeometry, Option<KclValue>),
134    Dummy,
135}
136
137#[allow(clippy::large_enum_variant)]
138#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, Hash, ts_rs::TS)]
139#[serde(tag = "type")]
140pub enum ModulePath {
141    // The main file of the project.
142    Main,
143    Local { value: TypedPath },
144    Std { value: String },
145}
146
147impl ModulePath {
148    pub(crate) fn expect_path(&self) -> &TypedPath {
149        match self {
150            ModulePath::Local { value: p } => p,
151            _ => unreachable!(),
152        }
153    }
154
155    pub(crate) fn std_path(&self) -> Option<String> {
156        match self {
157            ModulePath::Std { value: p } => Some(p.clone()),
158            _ => None,
159        }
160    }
161
162    pub(crate) async fn source(&self, fs: &FileManager, source_range: SourceRange) -> Result<ModuleSource, KclError> {
163        match self {
164            ModulePath::Local { value: p } => Ok(ModuleSource {
165                source: fs.read_to_string(p, source_range).await?,
166                path: self.clone(),
167            }),
168            ModulePath::Std { value: name } => Ok(ModuleSource {
169                source: read_std(name)
170                    .ok_or_else(|| {
171                        KclError::Semantic(KclErrorDetails {
172                            message: format!("Cannot find standard library module to import: std::{name}."),
173                            source_ranges: vec![source_range],
174                        })
175                    })
176                    .map(str::to_owned)?,
177                path: self.clone(),
178            }),
179            ModulePath::Main => unreachable!(),
180        }
181    }
182
183    pub(crate) fn from_import_path(path: &ImportPath, project_directory: &Option<TypedPath>) -> Self {
184        match path {
185            ImportPath::Kcl { filename: path } | ImportPath::Foreign { path } => {
186                let resolved_path = if let Some(project_dir) = project_directory {
187                    project_dir.join(path)
188                } else {
189                    TypedPath::from(path)
190                };
191                ModulePath::Local { value: resolved_path }
192            }
193            ImportPath::Std { path } => {
194                // For now we only support importing from singly-nested modules inside std.
195                assert_eq!(path.len(), 2);
196                assert_eq!(&path[0], "std");
197
198                ModulePath::Std { value: path[1].clone() }
199            }
200        }
201    }
202}
203
204impl fmt::Display for ModulePath {
205    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206        match self {
207            ModulePath::Main => write!(f, "main"),
208            ModulePath::Local { value: path } => path.fmt(f),
209            ModulePath::Std { value: s } => write!(f, "std::{s}"),
210        }
211    }
212}
213
214#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ts_rs::TS)]
215pub struct ModuleSource {
216    pub path: ModulePath,
217    pub source: String,
218}