kcl_lib/
lib.rs

1//! Rust support for KCL (aka the KittyCAD Language).
2//!
3//! KCL is written in Rust. This crate contains the compiler tooling (e.g. parser, lexer, code generation),
4//! the standard library implementation, a LSP implementation, generator for the docs, and more.
5#![recursion_limit = "1024"]
6#![allow(clippy::boxed_local)]
7
8#[allow(unused_macros)]
9macro_rules! println {
10    ($($rest:tt)*) => {
11        #[cfg(all(feature = "disable-println", not(test)))]
12        {
13            let _ = format!($($rest)*);
14        }
15        #[cfg(any(not(feature = "disable-println"), test))]
16        std::println!($($rest)*)
17    }
18}
19
20#[allow(unused_macros)]
21macro_rules! eprintln {
22    ($($rest:tt)*) => {
23        #[cfg(all(feature = "disable-println", not(test)))]
24        {
25            let _ = format!($($rest)*);
26        }
27        #[cfg(any(not(feature = "disable-println"), test))]
28        std::eprintln!($($rest)*)
29    }
30}
31
32#[allow(unused_macros)]
33macro_rules! print {
34    ($($rest:tt)*) => {
35        #[cfg(all(feature = "disable-println", not(test)))]
36        {
37            let _ = format!($($rest)*);
38        }
39        #[cfg(any(not(feature = "disable-println"), test))]
40        std::print!($($rest)*)
41    }
42}
43
44#[allow(unused_macros)]
45macro_rules! eprint {
46    ($($rest:tt)*) => {
47        #[cfg(all(feature = "disable-println", not(test)))]
48        {
49            let _ = format!($($rest)*);
50        }
51        #[cfg(any(not(feature = "disable-println"), test))]
52        std::eprint!($($rest)*)
53    }
54}
55#[cfg(feature = "dhat-heap")]
56#[global_allocator]
57static ALLOC: dhat::Alloc = dhat::Alloc;
58
59mod coredump;
60mod docs;
61mod engine;
62mod errors;
63mod execution;
64mod fmt;
65mod fs;
66pub mod lint;
67mod log;
68mod lsp;
69mod modules;
70mod parsing;
71mod settings;
72#[cfg(test)]
73mod simulation_tests;
74mod source_range;
75pub mod std;
76#[cfg(not(target_arch = "wasm32"))]
77pub mod test_server;
78mod thread;
79mod unparser;
80#[cfg(test)]
81mod variant_name;
82pub mod walk;
83#[cfg(target_arch = "wasm32")]
84mod wasm;
85
86pub use coredump::CoreDump;
87pub use engine::{AsyncTasks, EngineManager, EngineStats};
88pub use errors::{
89    BacktraceItem, CompilationError, ConnectionError, ExecError, KclError, KclErrorWithOutputs, Report,
90    ReportWithOutputs,
91};
92pub use execution::{
93    bust_cache, clear_mem_cache,
94    typed_path::TypedPath,
95    types::{UnitAngle, UnitLen},
96    ExecOutcome, ExecState, ExecutorContext, ExecutorSettings, MetaSettings, Point2d,
97};
98pub use lsp::{
99    copilot::Backend as CopilotLspBackend,
100    kcl::{Backend as KclLspBackend, Server as KclLspServerSubCommand},
101};
102pub use modules::ModuleId;
103pub use parsing::ast::types::{FormatOptions, NodePath, Step as NodePathStep};
104pub use settings::types::{project::ProjectConfiguration, Configuration, UnitLength};
105pub use source_range::SourceRange;
106#[cfg(not(target_arch = "wasm32"))]
107pub use unparser::{recast_dir, walk_dir};
108
109// Rather than make executor public and make lots of it pub(crate), just re-export into a new module.
110// Ideally we wouldn't export these things at all, they should only be used for testing.
111pub mod exec {
112    #[cfg(feature = "artifact-graph")]
113    pub use crate::execution::ArtifactCommand;
114    pub use crate::execution::{
115        types::{NumericType, UnitAngle, UnitLen, UnitType},
116        DefaultPlanes, IdGenerator, KclValue, PlaneType, Sketch,
117    };
118}
119
120#[cfg(target_arch = "wasm32")]
121pub mod wasm_engine {
122    pub use crate::{
123        coredump::wasm::{CoreDumpManager, CoreDumper},
124        engine::conn_wasm::{EngineCommandManager, EngineConnection, ResponseContext},
125        fs::wasm::{FileManager, FileSystemManager},
126    };
127}
128
129pub mod mock_engine {
130    pub use crate::engine::conn_mock::EngineConnection;
131}
132
133#[cfg(not(target_arch = "wasm32"))]
134pub mod native_engine {
135    pub use crate::engine::conn::EngineConnection;
136}
137
138pub mod std_utils {
139    pub use crate::std::utils::{get_tangential_arc_to_info, is_points_ccw_wasm, TangentialArcInfoInput};
140}
141
142pub mod pretty {
143    pub use crate::{
144        fmt::{format_number_literal, human_display_number},
145        parsing::token::NumericSuffix,
146    };
147}
148
149#[cfg(feature = "cli")]
150use clap::ValueEnum;
151use serde::{Deserialize, Serialize};
152
153#[allow(unused_imports)]
154use crate::log::{log, logln};
155
156lazy_static::lazy_static! {
157
158    pub static ref IMPORT_FILE_EXTENSIONS: Vec<String> = {
159        let mut import_file_extensions = vec!["stp".to_string(), "glb".to_string(), "fbxb".to_string()];
160        #[cfg(feature = "cli")]
161        let named_extensions = kittycad::types::FileImportFormat::value_variants()
162            .iter()
163            .map(|x| format!("{}", x))
164            .collect::<Vec<String>>();
165        #[cfg(not(feature = "cli"))]
166        let named_extensions = vec![]; // We don't really need this outside of the CLI.
167        // Add all the default import formats.
168        import_file_extensions.extend_from_slice(&named_extensions);
169        import_file_extensions
170    };
171
172    pub static ref RELEVANT_FILE_EXTENSIONS: Vec<String> = {
173        let mut relevant_extensions = IMPORT_FILE_EXTENSIONS.clone();
174        relevant_extensions.push("kcl".to_string());
175        relevant_extensions
176    };
177}
178
179#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
180pub struct Program {
181    #[serde(flatten)]
182    pub ast: parsing::ast::types::Node<parsing::ast::types::Program>,
183    // The ui doesn't need to know about this.
184    // It's purely used for saving the contents of the original file, so we can use it for errors.
185    // Because in the case of the root file, we don't want to read the file from disk again.
186    #[serde(skip)]
187    pub original_file_contents: String,
188}
189
190#[cfg(any(test, feature = "lsp-test-util"))]
191pub use lsp::test_util::copilot_lsp_server;
192#[cfg(any(test, feature = "lsp-test-util"))]
193pub use lsp::test_util::kcl_lsp_server;
194
195impl Program {
196    pub fn parse(input: &str) -> Result<(Option<Program>, Vec<CompilationError>), KclError> {
197        let module_id = ModuleId::default();
198        let tokens = parsing::token::lex(input, module_id)?;
199        let (ast, errs) = parsing::parse_tokens(tokens).0?;
200
201        Ok((
202            ast.map(|ast| Program {
203                ast,
204                original_file_contents: input.to_string(),
205            }),
206            errs,
207        ))
208    }
209
210    pub fn parse_no_errs(input: &str) -> Result<Program, KclError> {
211        let module_id = ModuleId::default();
212        let tokens = parsing::token::lex(input, module_id)?;
213        let ast = parsing::parse_tokens(tokens).parse_errs_as_err()?;
214
215        Ok(Program {
216            ast,
217            original_file_contents: input.to_string(),
218        })
219    }
220
221    pub fn compute_digest(&mut self) -> parsing::ast::digest::Digest {
222        self.ast.compute_digest()
223    }
224
225    /// Get the meta settings for the kcl file from the annotations.
226    pub fn meta_settings(&self) -> Result<Option<crate::MetaSettings>, KclError> {
227        self.ast.meta_settings()
228    }
229
230    /// Change the meta settings for the kcl file.
231    pub fn change_default_units(
232        &self,
233        length_units: Option<execution::types::UnitLen>,
234        angle_units: Option<execution::types::UnitAngle>,
235    ) -> Result<Self, KclError> {
236        Ok(Self {
237            ast: self.ast.change_default_units(length_units, angle_units)?,
238            original_file_contents: self.original_file_contents.clone(),
239        })
240    }
241
242    pub fn is_empty_or_only_settings(&self) -> bool {
243        self.ast.is_empty_or_only_settings()
244    }
245
246    pub fn lint_all(&self) -> Result<Vec<lint::Discovered>, anyhow::Error> {
247        self.ast.lint_all()
248    }
249
250    pub fn lint<'a>(&'a self, rule: impl lint::Rule<'a>) -> Result<Vec<lint::Discovered>, anyhow::Error> {
251        self.ast.lint(rule)
252    }
253
254    pub fn node_path_from_range(&self, cached_body_items: usize, range: SourceRange) -> Option<NodePath> {
255        NodePath::from_range(&self.ast, cached_body_items, range)
256    }
257
258    pub fn recast(&self) -> String {
259        // Use the default options until we integrate into the UI the ability to change them.
260        self.ast.recast(&Default::default(), 0)
261    }
262
263    pub fn recast_with_options(&self, options: &FormatOptions) -> String {
264        self.ast.recast(options, 0)
265    }
266
267    /// Create an empty program.
268    pub fn empty() -> Self {
269        Self {
270            ast: parsing::ast::types::Node::no_src(parsing::ast::types::Program::default()),
271            original_file_contents: String::new(),
272        }
273    }
274}
275
276#[inline]
277fn try_f64_to_usize(f: f64) -> Option<usize> {
278    let i = f as usize;
279    if i as f64 == f {
280        Some(i)
281    } else {
282        None
283    }
284}
285
286#[inline]
287fn try_f64_to_u32(f: f64) -> Option<u32> {
288    let i = f as u32;
289    if i as f64 == f {
290        Some(i)
291    } else {
292        None
293    }
294}
295
296#[inline]
297fn try_f64_to_u64(f: f64) -> Option<u64> {
298    let i = f as u64;
299    if i as f64 == f {
300        Some(i)
301    } else {
302        None
303    }
304}
305
306#[inline]
307fn try_f64_to_i64(f: f64) -> Option<i64> {
308    let i = f as i64;
309    if i as f64 == f {
310        Some(i)
311    } else {
312        None
313    }
314}
315
316/// Get the version of the KCL library.
317pub fn version() -> &'static str {
318    env!("CARGO_PKG_VERSION")
319}
320
321#[cfg(test)]
322mod test {
323    use super::*;
324
325    #[test]
326    fn convert_int() {
327        assert_eq!(try_f64_to_usize(0.0), Some(0));
328        assert_eq!(try_f64_to_usize(42.0), Some(42));
329        assert_eq!(try_f64_to_usize(0.00000000001), None);
330        assert_eq!(try_f64_to_usize(-1.0), None);
331        assert_eq!(try_f64_to_usize(f64::NAN), None);
332        assert_eq!(try_f64_to_usize(f64::INFINITY), None);
333        assert_eq!(try_f64_to_usize((0.1 + 0.2) * 10.0), None);
334
335        assert_eq!(try_f64_to_u32(0.0), Some(0));
336        assert_eq!(try_f64_to_u32(42.0), Some(42));
337        assert_eq!(try_f64_to_u32(0.00000000001), None);
338        assert_eq!(try_f64_to_u32(-1.0), None);
339        assert_eq!(try_f64_to_u32(f64::NAN), None);
340        assert_eq!(try_f64_to_u32(f64::INFINITY), None);
341        assert_eq!(try_f64_to_u32((0.1 + 0.2) * 10.0), None);
342
343        assert_eq!(try_f64_to_u64(0.0), Some(0));
344        assert_eq!(try_f64_to_u64(42.0), Some(42));
345        assert_eq!(try_f64_to_u64(0.00000000001), None);
346        assert_eq!(try_f64_to_u64(-1.0), None);
347        assert_eq!(try_f64_to_u64(f64::NAN), None);
348        assert_eq!(try_f64_to_u64(f64::INFINITY), None);
349        assert_eq!(try_f64_to_u64((0.1 + 0.2) * 10.0), None);
350
351        assert_eq!(try_f64_to_i64(0.0), Some(0));
352        assert_eq!(try_f64_to_i64(42.0), Some(42));
353        assert_eq!(try_f64_to_i64(0.00000000001), None);
354        assert_eq!(try_f64_to_i64(-1.0), Some(-1));
355        assert_eq!(try_f64_to_i64(f64::NAN), None);
356        assert_eq!(try_f64_to_i64(f64::INFINITY), None);
357        assert_eq!(try_f64_to_i64((0.1 + 0.2) * 10.0), None);
358    }
359}