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