kcl-lib 0.2.144

KittyCAD Language implementation and tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! Rust support for KCL (aka the KittyCAD Language).
//!
//! KCL is written in Rust. This crate contains the compiler tooling (e.g. parser, lexer, code generation),
//! the standard library implementation, a LSP implementation, generator for the docs, and more.
#![recursion_limit = "1024"]
#![allow(clippy::boxed_local)]

#[allow(unused_macros)]
macro_rules! println {
    ($($rest:tt)*) => {
        #[cfg(all(feature = "disable-println", not(test)))]
        {
            let _ = format!($($rest)*);
        }
        #[cfg(any(not(feature = "disable-println"), test))]
        std::println!($($rest)*)
    }
}

#[allow(unused_macros)]
macro_rules! eprintln {
    ($($rest:tt)*) => {
        #[cfg(all(feature = "disable-println", not(test)))]
        {
            let _ = format!($($rest)*);
        }
        #[cfg(any(not(feature = "disable-println"), test))]
        std::eprintln!($($rest)*)
    }
}

#[allow(unused_macros)]
macro_rules! print {
    ($($rest:tt)*) => {
        #[cfg(all(feature = "disable-println", not(test)))]
        {
            let _ = format!($($rest)*);
        }
        #[cfg(any(not(feature = "disable-println"), test))]
        std::print!($($rest)*)
    }
}

#[allow(unused_macros)]
macro_rules! eprint {
    ($($rest:tt)*) => {
        #[cfg(all(feature = "disable-println", not(test)))]
        {
            let _ = format!($($rest)*);
        }
        #[cfg(any(not(feature = "disable-println"), test))]
        std::eprint!($($rest)*)
    }
}
#[cfg(feature = "dhat-heap")]
#[global_allocator]
static ALLOC: dhat::Alloc = dhat::Alloc;

pub mod collections;
mod coredump;
mod docs;
mod engine;
mod errors;
mod execution;
mod fmt;
mod frontend;
mod fs;
pub(crate) mod id;
pub mod lint;
mod log;
mod lsp;
mod modules;
mod parsing;
mod project;
mod settings;
#[cfg(test)]
mod simulation_tests;
pub mod std;
#[cfg(not(target_arch = "wasm32"))]
pub mod test_server;
mod thread;
#[doc(hidden)]
pub mod tooling;
mod unparser;
mod util;
#[cfg(test)]
mod variant_name;
pub mod walk;
#[cfg(target_arch = "wasm32")]
mod wasm;

pub use coredump::CoreDump;
pub use engine::AsyncTasks;
pub use engine::EngineManager;
pub use engine::EngineStats;
pub use errors::BacktraceItem;
pub use errors::CompilationIssue;
pub use errors::ConnectionError;
pub use errors::ExecError;
pub use errors::KclError;
pub use errors::KclErrorWithOutputs;
pub use errors::Report;
pub use errors::ReportWithOutputs;
pub use execution::ConstraintKind;
pub use execution::ExecOutcome;
pub use execution::ExecState;
pub use execution::ExecutorContext;
pub use execution::ExecutorSettings;
pub use execution::MetaSettings;
pub use execution::MockConfig;
pub use execution::Point2d;
pub use execution::SketchConstraintReport;
pub use execution::SketchConstraintStatus;
pub use execution::bust_cache;
pub use execution::clear_mem_cache;
pub use execution::pre_execute_transpile;
pub use execution::transpile_all_old_sketches_to_new;
pub use execution::transpile_old_sketch_to_new;
pub use execution::transpile_old_sketch_to_new_ast;
pub use execution::transpile_old_sketch_to_new_with_execution;
pub use execution::typed_path::TypedPath;
pub use kcl_error::SourceRange;
pub use lsp::ToLspRange;
pub use lsp::copilot::Backend as CopilotLspBackend;
pub use lsp::kcl::Backend as KclLspBackend;
pub use lsp::kcl::Server as KclLspServerSubCommand;
pub use modules::ModuleId;
pub use parsing::ast::types::FormatOptions;
pub use parsing::ast::types::NodePath;
pub use parsing::ast::types::Step as NodePathStep;
pub use project::ProjectManager;
pub use settings::types::Configuration;
pub use settings::types::project::ProjectConfiguration;
#[cfg(not(target_arch = "wasm32"))]
pub use unparser::recast_dir;
#[cfg(not(target_arch = "wasm32"))]
pub use unparser::walk_dir;

// Rather than make executor public and make lots of it pub(crate), just re-export into a new module.
// Ideally we wouldn't export these things at all, they should only be used for testing.
pub mod exec {
    #[cfg(feature = "artifact-graph")]
    pub use crate::execution::ArtifactCommand;
    pub use crate::execution::DefaultPlanes;
    pub use crate::execution::IdGenerator;
    pub use crate::execution::KclValue;
    #[cfg(feature = "artifact-graph")]
    pub use crate::execution::Operation;
    pub use crate::execution::PlaneKind;
    pub use crate::execution::Sketch;
    pub use crate::execution::annotations::WarningLevel;
    pub use crate::execution::types::NumericType;
    pub use crate::execution::types::UnitType;
    pub use crate::util::RetryConfig;
    pub use crate::util::execute_with_retries;
}

#[cfg(target_arch = "wasm32")]
pub mod wasm_engine {
    pub use crate::coredump::wasm::CoreDumpManager;
    pub use crate::coredump::wasm::CoreDumper;
    pub use crate::engine::conn_wasm::EngineCommandManager;
    pub use crate::engine::conn_wasm::EngineConnection;
    pub use crate::engine::conn_wasm::ResponseContext;
    pub use crate::fs::wasm::FileManager;
    pub use crate::fs::wasm::FileSystemManager;
}

pub mod mock_engine {
    pub use crate::engine::conn_mock::EngineConnection;
}

#[cfg(not(target_arch = "wasm32"))]
pub mod native_engine {
    pub use crate::engine::conn::EngineConnection;
}

pub mod std_utils {
    pub use crate::std::utils::TangentialArcInfoInput;
    pub use crate::std::utils::get_tangential_arc_to_info;
    pub use crate::std::utils::is_points_ccw_wasm;
    pub use crate::std::utils::untyped_point_to_unit;
}

pub mod pretty {
    pub use crate::fmt::format_number_literal;
    pub use crate::fmt::format_number_value;
    pub use crate::fmt::human_display_number;
    pub use crate::parsing::token::NumericSuffix;
}

pub mod front {
    pub use crate::frontend::MAX_SKETCH_CHECKPOINTS;
    pub(crate) use crate::frontend::modify::find_defined_names;
    pub(crate) use crate::frontend::modify::next_free_name_using_max;
    pub use crate::frontend::sketch::ExecResult;
    pub use crate::frontend::{
        FrontendState,
        SetProgramOutcome,
        api::{
            Cap, CapKind, EditSketchOutcome, Error, Expr, Face, File, FileId, LifecycleApi, NewSketchOutcome, Number,
            Object, ObjectId, ObjectKind, Plane, ProjectId, RestoreSketchCheckpointOutcome, Result, SceneGraph,
            SceneGraphDelta, Settings, SketchCheckpointId, SketchMutationOutcome, SourceDelta, SourceRef, Version,
            Wall,
        },
        sketch::{
            Angle, Arc, ArcCtor, Circle, CircleCtor, Coincident, Constraint, Distance, EqualRadius,
            ExistingSegmentCtor, Fixed, FixedPoint, Freedom, Horizontal, Line, LineCtor, LinesEqualLength,
            NewSegmentInfo, Parallel, Perpendicular, Point, Point2d, PointCtor, Segment, SegmentCtor, Sketch,
            SketchApi, SketchCtor, StartOrEnd, Tangent, Vertical,
        },
        // Re-export trim module items
        trim::{
            ArcPoint, AttachToEndpoint, CoincidentData, ConstraintToMigrate, Coords2d, EndpointChanged, LineEndpoint,
            TrimDirection, TrimItem, TrimOperation, TrimTermination, TrimTerminations, arc_arc_intersection,
            execute_trim_loop_with_context, get_next_trim_spawn, get_position_coords_for_line,
            get_position_coords_from_arc, get_trim_spawn_terminations, is_point_on_arc, is_point_on_line_segment,
            line_arc_intersection, line_segment_intersection, perpendicular_distance_to_segment,
            project_point_onto_arc, project_point_onto_segment,
        },
    };
}

#[cfg(feature = "cli")]
use clap::ValueEnum;
use serde::Deserialize;
use serde::Serialize;

use crate::exec::WarningLevel;
#[allow(unused_imports)]
use crate::log::log;
#[allow(unused_imports)]
use crate::log::logln;

lazy_static::lazy_static! {

    pub static ref IMPORT_FILE_EXTENSIONS: Vec<String> = {
        let mut import_file_extensions = vec!["stp".to_string(), "glb".to_string(), "fbxb".to_string()];
        #[cfg(feature = "cli")]
        let named_extensions = kittycad::types::FileImportFormat::value_variants()
            .iter()
            .map(|x| format!("{x}"))
            .collect::<Vec<String>>();
        #[cfg(not(feature = "cli"))]
        let named_extensions = vec![]; // We don't really need this outside of the CLI.
        // Add all the default import formats.
        import_file_extensions.extend_from_slice(&named_extensions);
        import_file_extensions
    };

    pub static ref RELEVANT_FILE_EXTENSIONS: Vec<String> = {
        let mut relevant_extensions = IMPORT_FILE_EXTENSIONS.clone();
        relevant_extensions.push("kcl".to_string());
        relevant_extensions.push("md".to_string());
        relevant_extensions
    };
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Program {
    #[serde(flatten)]
    pub ast: parsing::ast::types::Node<parsing::ast::types::Program>,
    // The ui doesn't need to know about this.
    // It's purely used for saving the contents of the original file, so we can use it for errors.
    // Because in the case of the root file, we don't want to read the file from disk again.
    #[serde(skip)]
    pub original_file_contents: String,
}

#[cfg(any(test, feature = "lsp-test-util"))]
pub use lsp::test_util::copilot_lsp_server;
#[cfg(any(test, feature = "lsp-test-util"))]
pub use lsp::test_util::kcl_lsp_server;

impl Program {
    pub fn parse(input: &str) -> Result<(Option<Program>, Vec<CompilationIssue>), KclError> {
        let module_id = ModuleId::default();
        let (ast, errs) = parsing::parse_str(input, module_id).0?;

        Ok((
            ast.map(|ast| Program {
                ast,
                original_file_contents: input.to_string(),
            }),
            errs,
        ))
    }

    pub fn parse_no_errs(input: &str) -> Result<Program, KclError> {
        let module_id = ModuleId::default();
        let ast = parsing::parse_str(input, module_id).parse_errs_as_err()?;

        Ok(Program {
            ast,
            original_file_contents: input.to_string(),
        })
    }

    pub fn compute_digest(&mut self) -> parsing::ast::digest::Digest {
        self.ast.compute_digest()
    }

    /// Get the meta settings for the kcl file from the annotations.
    pub fn meta_settings(&self) -> Result<Option<crate::MetaSettings>, KclError> {
        self.ast.meta_settings()
    }

    /// Change the meta settings for the kcl file.
    pub fn change_default_units(
        &self,
        length_units: Option<kittycad_modeling_cmds::units::UnitLength>,
    ) -> Result<Self, KclError> {
        Ok(Self {
            ast: self.ast.change_default_units(length_units)?,
            original_file_contents: self.original_file_contents.clone(),
        })
    }

    pub fn change_experimental_features(&self, warning_level: Option<WarningLevel>) -> Result<Self, KclError> {
        Ok(Self {
            ast: self.ast.change_experimental_features(warning_level)?,
            original_file_contents: self.original_file_contents.clone(),
        })
    }

    pub fn is_empty_or_only_settings(&self) -> bool {
        self.ast.is_empty_or_only_settings()
    }

    pub fn lint_all(&self) -> Result<Vec<lint::Discovered>, anyhow::Error> {
        self.ast.lint_all()
    }

    pub fn lint<'a>(&'a self, rule: impl lint::Rule<'a>) -> Result<Vec<lint::Discovered>, anyhow::Error> {
        self.ast.lint(rule)
    }

    #[cfg(feature = "artifact-graph")]
    pub fn node_path_from_range(&self, cached_body_items: usize, range: SourceRange) -> Option<NodePath> {
        let module_infos = indexmap::IndexMap::new();
        let programs = crate::execution::ProgramLookup::new(self.ast.clone(), module_infos);
        NodePath::from_range(&programs, cached_body_items, range)
    }

    /// Fill node paths and consume the input so that the program without paths
    /// isn't accidentally used. Filling node paths happens automatically during
    /// parsing. Calling this is only needed after the caller invalidates the
    /// node paths such as by mutating an AST or by making a round-trip through
    /// serialization.
    #[cfg(feature = "artifact-graph")]
    pub fn fill_node_paths(mut self) -> Program {
        parsing::ast::types::fill_node_paths(&mut self.ast);
        self
    }

    pub fn recast(&self) -> String {
        // Use the default options until we integrate into the UI the ability to change them.
        self.ast.recast_top(&Default::default(), 0)
    }

    pub fn recast_with_options(&self, options: &FormatOptions) -> String {
        self.ast.recast_top(options, 0)
    }

    /// Create an empty program.
    pub fn empty() -> Self {
        Self {
            ast: parsing::ast::types::Node::no_src(parsing::ast::types::Program::default()),
            original_file_contents: String::new(),
        }
    }
}

#[inline]
fn try_f64_to_usize(f: f64) -> Option<usize> {
    let i = f as usize;
    if i as f64 == f { Some(i) } else { None }
}

#[inline]
fn try_f64_to_u32(f: f64) -> Option<u32> {
    let i = f as u32;
    if i as f64 == f { Some(i) } else { None }
}

#[inline]
fn try_f64_to_u64(f: f64) -> Option<u64> {
    let i = f as u64;
    if i as f64 == f { Some(i) } else { None }
}

#[inline]
fn try_f64_to_i64(f: f64) -> Option<i64> {
    let i = f as i64;
    if i as f64 == f { Some(i) } else { None }
}

/// Get the version of the KCL library.
pub fn version() -> &'static str {
    env!("CARGO_PKG_VERSION")
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn convert_int() {
        assert_eq!(try_f64_to_usize(0.0), Some(0));
        assert_eq!(try_f64_to_usize(42.0), Some(42));
        assert_eq!(try_f64_to_usize(0.00000000001), None);
        assert_eq!(try_f64_to_usize(-1.0), None);
        assert_eq!(try_f64_to_usize(f64::NAN), None);
        assert_eq!(try_f64_to_usize(f64::INFINITY), None);
        assert_eq!(try_f64_to_usize((0.1 + 0.2) * 10.0), None);

        assert_eq!(try_f64_to_u32(0.0), Some(0));
        assert_eq!(try_f64_to_u32(42.0), Some(42));
        assert_eq!(try_f64_to_u32(0.00000000001), None);
        assert_eq!(try_f64_to_u32(-1.0), None);
        assert_eq!(try_f64_to_u32(f64::NAN), None);
        assert_eq!(try_f64_to_u32(f64::INFINITY), None);
        assert_eq!(try_f64_to_u32((0.1 + 0.2) * 10.0), None);

        assert_eq!(try_f64_to_u64(0.0), Some(0));
        assert_eq!(try_f64_to_u64(42.0), Some(42));
        assert_eq!(try_f64_to_u64(0.00000000001), None);
        assert_eq!(try_f64_to_u64(-1.0), None);
        assert_eq!(try_f64_to_u64(f64::NAN), None);
        assert_eq!(try_f64_to_u64(f64::INFINITY), None);
        assert_eq!(try_f64_to_u64((0.1 + 0.2) * 10.0), None);

        assert_eq!(try_f64_to_i64(0.0), Some(0));
        assert_eq!(try_f64_to_i64(42.0), Some(42));
        assert_eq!(try_f64_to_i64(0.00000000001), None);
        assert_eq!(try_f64_to_i64(-1.0), Some(-1));
        assert_eq!(try_f64_to_i64(f64::NAN), None);
        assert_eq!(try_f64_to_i64(f64::INFINITY), None);
        assert_eq!(try_f64_to_i64((0.1 + 0.2) * 10.0), None);
    }
}