1#![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 project;
72mod settings;
73#[cfg(test)]
74mod simulation_tests;
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 ExecOutcome, ExecState, ExecutorContext, ExecutorSettings, MetaSettings, Point2d, bust_cache, clear_mem_cache,
94 typed_path::TypedPath,
95};
96pub use kcl_error::SourceRange;
97pub use lsp::{
98 ToLspRange,
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 project::ProjectManager;
105pub use settings::types::{Configuration, project::ProjectConfiguration};
106#[cfg(not(target_arch = "wasm32"))]
107pub use unparser::{recast_dir, walk_dir};
108
109pub mod exec {
112 #[cfg(feature = "artifact-graph")]
113 pub use crate::execution::{ArtifactCommand, Operation};
114 pub use crate::execution::{
115 DefaultPlanes, IdGenerator, KclValue, PlaneType, Sketch,
116 types::{NumericType, UnitType},
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::{TangentialArcInfoInput, get_tangential_arc_to_info, is_points_ccw_wasm};
140}
141
142pub mod pretty {
143 pub use crate::{
144 fmt::{format_number_literal, format_number_value, 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![]; 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 #[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 (ast, errs) = parsing::parse_str(input, module_id).0?;
199
200 Ok((
201 ast.map(|ast| Program {
202 ast,
203 original_file_contents: input.to_string(),
204 }),
205 errs,
206 ))
207 }
208
209 pub fn parse_no_errs(input: &str) -> Result<Program, KclError> {
210 let module_id = ModuleId::default();
211 let ast = parsing::parse_str(input, module_id).parse_errs_as_err()?;
212
213 Ok(Program {
214 ast,
215 original_file_contents: input.to_string(),
216 })
217 }
218
219 pub fn compute_digest(&mut self) -> parsing::ast::digest::Digest {
220 self.ast.compute_digest()
221 }
222
223 pub fn meta_settings(&self) -> Result<Option<crate::MetaSettings>, KclError> {
225 self.ast.meta_settings()
226 }
227
228 pub fn change_default_units(
230 &self,
231 length_units: Option<kittycad_modeling_cmds::units::UnitLength>,
232 ) -> Result<Self, KclError> {
233 Ok(Self {
234 ast: self.ast.change_default_units(length_units)?,
235 original_file_contents: self.original_file_contents.clone(),
236 })
237 }
238
239 pub fn is_empty_or_only_settings(&self) -> bool {
240 self.ast.is_empty_or_only_settings()
241 }
242
243 pub fn lint_all(&self) -> Result<Vec<lint::Discovered>, anyhow::Error> {
244 self.ast.lint_all()
245 }
246
247 pub fn lint<'a>(&'a self, rule: impl lint::Rule<'a>) -> Result<Vec<lint::Discovered>, anyhow::Error> {
248 self.ast.lint(rule)
249 }
250
251 pub fn node_path_from_range(&self, cached_body_items: usize, range: SourceRange) -> Option<NodePath> {
252 NodePath::from_range(&self.ast, cached_body_items, range)
253 }
254
255 pub fn recast(&self) -> String {
256 self.ast.recast_top(&Default::default(), 0)
258 }
259
260 pub fn recast_with_options(&self, options: &FormatOptions) -> String {
261 self.ast.recast_top(options, 0)
262 }
263
264 pub fn empty() -> Self {
266 Self {
267 ast: parsing::ast::types::Node::no_src(parsing::ast::types::Program::default()),
268 original_file_contents: String::new(),
269 }
270 }
271}
272
273#[inline]
274fn try_f64_to_usize(f: f64) -> Option<usize> {
275 let i = f as usize;
276 if i as f64 == f { Some(i) } else { None }
277}
278
279#[inline]
280fn try_f64_to_u32(f: f64) -> Option<u32> {
281 let i = f as u32;
282 if i as f64 == f { Some(i) } else { None }
283}
284
285#[inline]
286fn try_f64_to_u64(f: f64) -> Option<u64> {
287 let i = f as u64;
288 if i as f64 == f { Some(i) } else { None }
289}
290
291#[inline]
292fn try_f64_to_i64(f: f64) -> Option<i64> {
293 let i = f as i64;
294 if i as f64 == f { Some(i) } else { None }
295}
296
297pub fn version() -> &'static str {
299 env!("CARGO_PKG_VERSION")
300}
301
302#[cfg(test)]
303mod test {
304 use super::*;
305
306 #[test]
307 fn convert_int() {
308 assert_eq!(try_f64_to_usize(0.0), Some(0));
309 assert_eq!(try_f64_to_usize(42.0), Some(42));
310 assert_eq!(try_f64_to_usize(0.00000000001), None);
311 assert_eq!(try_f64_to_usize(-1.0), None);
312 assert_eq!(try_f64_to_usize(f64::NAN), None);
313 assert_eq!(try_f64_to_usize(f64::INFINITY), None);
314 assert_eq!(try_f64_to_usize((0.1 + 0.2) * 10.0), None);
315
316 assert_eq!(try_f64_to_u32(0.0), Some(0));
317 assert_eq!(try_f64_to_u32(42.0), Some(42));
318 assert_eq!(try_f64_to_u32(0.00000000001), None);
319 assert_eq!(try_f64_to_u32(-1.0), None);
320 assert_eq!(try_f64_to_u32(f64::NAN), None);
321 assert_eq!(try_f64_to_u32(f64::INFINITY), None);
322 assert_eq!(try_f64_to_u32((0.1 + 0.2) * 10.0), None);
323
324 assert_eq!(try_f64_to_u64(0.0), Some(0));
325 assert_eq!(try_f64_to_u64(42.0), Some(42));
326 assert_eq!(try_f64_to_u64(0.00000000001), None);
327 assert_eq!(try_f64_to_u64(-1.0), None);
328 assert_eq!(try_f64_to_u64(f64::NAN), None);
329 assert_eq!(try_f64_to_u64(f64::INFINITY), None);
330 assert_eq!(try_f64_to_u64((0.1 + 0.2) * 10.0), None);
331
332 assert_eq!(try_f64_to_i64(0.0), Some(0));
333 assert_eq!(try_f64_to_i64(42.0), Some(42));
334 assert_eq!(try_f64_to_i64(0.00000000001), None);
335 assert_eq!(try_f64_to_i64(-1.0), Some(-1));
336 assert_eq!(try_f64_to_i64(f64::NAN), None);
337 assert_eq!(try_f64_to_i64(f64::INFINITY), None);
338 assert_eq!(try_f64_to_i64((0.1 + 0.2) * 10.0), None);
339 }
340}