kcl_lib/execution/
mod.rs

1//! The executor for the AST.
2
3use std::sync::Arc;
4
5use anyhow::Result;
6#[cfg(feature = "artifact-graph")]
7pub use artifact::{Artifact, ArtifactCommand, ArtifactGraph, CodeRef, StartSketchOnFace, StartSketchOnPlane};
8use cache::GlobalState;
9pub use cache::{bust_cache, clear_mem_cache};
10#[cfg(feature = "artifact-graph")]
11pub use cad_op::Group;
12pub use cad_op::Operation;
13pub use geometry::*;
14pub use id_generator::IdGenerator;
15pub(crate) use import::PreImportedGeometry;
16use indexmap::IndexMap;
17pub use kcl_value::{KclObjectFields, KclValue};
18use kcmc::{
19    ImageFormat, ModelingCmd, each_cmd as mcmd,
20    ok_response::{OkModelingCmdResponse, output::TakeSnapshot},
21    websocket::{ModelingSessionData, OkWebSocketResponseData},
22};
23use kittycad_modeling_cmds::{self as kcmc, id::ModelingCmdId};
24pub use memory::EnvironmentRef;
25pub(crate) use modeling::ModelingCmdMeta;
26use serde::{Deserialize, Serialize};
27pub(crate) use state::ModuleArtifactState;
28pub use state::{ExecState, MetaSettings};
29use uuid::Uuid;
30
31use crate::{
32    CompilationError, ExecError, KclErrorWithOutputs, SourceRange,
33    engine::{EngineManager, GridScaleBehavior},
34    errors::{KclError, KclErrorDetails},
35    execution::{
36        cache::{CacheInformation, CacheResult},
37        import_graph::{Universe, UniverseMap},
38        typed_path::TypedPath,
39    },
40    fs::FileManager,
41    modules::{ModuleExecutionOutcome, ModuleId, ModulePath, ModuleRepr},
42    parsing::ast::types::{Expr, ImportPath, NodeRef},
43};
44
45pub(crate) mod annotations;
46#[cfg(feature = "artifact-graph")]
47mod artifact;
48pub(crate) mod cache;
49mod cad_op;
50mod exec_ast;
51pub mod fn_call;
52mod geometry;
53mod id_generator;
54mod import;
55mod import_graph;
56pub(crate) mod kcl_value;
57mod memory;
58mod modeling;
59mod state;
60pub mod typed_path;
61pub(crate) mod types;
62
63pub(crate) enum StatementKind<'a> {
64    Declaration { name: &'a str },
65    Expression,
66}
67
68/// Outcome of executing a program.  This is used in TS.
69#[derive(Debug, Clone, Serialize, ts_rs::TS, PartialEq)]
70#[ts(export)]
71#[serde(rename_all = "camelCase")]
72pub struct ExecOutcome {
73    /// Variables in the top-level of the root module. Note that functions will have an invalid env ref.
74    pub variables: IndexMap<String, KclValue>,
75    /// Operations that have been performed in execution order, for display in
76    /// the Feature Tree.
77    #[cfg(feature = "artifact-graph")]
78    pub operations: Vec<Operation>,
79    /// Output artifact graph.
80    #[cfg(feature = "artifact-graph")]
81    pub artifact_graph: ArtifactGraph,
82    /// Non-fatal errors and warnings.
83    pub errors: Vec<CompilationError>,
84    /// File Names in module Id array index order
85    pub filenames: IndexMap<ModuleId, ModulePath>,
86    /// The default planes.
87    pub default_planes: Option<DefaultPlanes>,
88}
89
90#[derive(Debug, Default, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS)]
91#[ts(export)]
92#[serde(rename_all = "camelCase")]
93pub struct DefaultPlanes {
94    pub xy: uuid::Uuid,
95    pub xz: uuid::Uuid,
96    pub yz: uuid::Uuid,
97    pub neg_xy: uuid::Uuid,
98    pub neg_xz: uuid::Uuid,
99    pub neg_yz: uuid::Uuid,
100}
101
102#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ts_rs::TS)]
103#[ts(export)]
104#[serde(tag = "type", rename_all = "camelCase")]
105pub struct TagIdentifier {
106    pub value: String,
107    // Multi-version representation of info about the tag. Kept ordered. The usize is the epoch at which the info
108    // was written.
109    #[serde(skip)]
110    pub info: Vec<(usize, TagEngineInfo)>,
111    #[serde(skip)]
112    pub meta: Vec<Metadata>,
113}
114
115impl TagIdentifier {
116    /// Get the tag info for this tag at a specified epoch.
117    pub fn get_info(&self, at_epoch: usize) -> Option<&TagEngineInfo> {
118        for (e, info) in self.info.iter().rev() {
119            if *e <= at_epoch {
120                return Some(info);
121            }
122        }
123
124        None
125    }
126
127    /// Get the most recent tag info for this tag.
128    pub fn get_cur_info(&self) -> Option<&TagEngineInfo> {
129        self.info.last().map(|i| &i.1)
130    }
131
132    /// Add info from a different instance of this tag.
133    pub fn merge_info(&mut self, other: &TagIdentifier) {
134        assert_eq!(&self.value, &other.value);
135        for (oe, ot) in &other.info {
136            if let Some((e, t)) = self.info.last_mut() {
137                // If there is newer info, then skip this iteration.
138                if *e > *oe {
139                    continue;
140                }
141                // If we're in the same epoch, then overwrite.
142                if e == oe {
143                    *t = ot.clone();
144                    continue;
145                }
146            }
147            self.info.push((*oe, ot.clone()));
148        }
149    }
150}
151
152impl Eq for TagIdentifier {}
153
154impl std::fmt::Display for TagIdentifier {
155    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156        write!(f, "{}", self.value)
157    }
158}
159
160impl std::str::FromStr for TagIdentifier {
161    type Err = KclError;
162
163    fn from_str(s: &str) -> Result<Self, Self::Err> {
164        Ok(Self {
165            value: s.to_string(),
166            info: Vec::new(),
167            meta: Default::default(),
168        })
169    }
170}
171
172impl Ord for TagIdentifier {
173    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
174        self.value.cmp(&other.value)
175    }
176}
177
178impl PartialOrd for TagIdentifier {
179    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
180        Some(self.cmp(other))
181    }
182}
183
184impl std::hash::Hash for TagIdentifier {
185    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
186        self.value.hash(state);
187    }
188}
189
190/// Engine information for a tag.
191#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
192#[ts(export)]
193#[serde(tag = "type", rename_all = "camelCase")]
194pub struct TagEngineInfo {
195    /// The id of the tagged object.
196    pub id: uuid::Uuid,
197    /// The sketch the tag is on.
198    pub sketch: uuid::Uuid,
199    /// The path the tag is on.
200    pub path: Option<Path>,
201    /// The surface information for the tag.
202    pub surface: Option<ExtrudeSurface>,
203}
204
205#[derive(Debug, Copy, Clone, Deserialize, Serialize, PartialEq)]
206pub enum BodyType {
207    Root,
208    Block,
209}
210
211/// Metadata.
212#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, Eq, Copy)]
213#[ts(export)]
214#[serde(rename_all = "camelCase")]
215pub struct Metadata {
216    /// The source range.
217    pub source_range: SourceRange,
218}
219
220impl From<Metadata> for Vec<SourceRange> {
221    fn from(meta: Metadata) -> Self {
222        vec![meta.source_range]
223    }
224}
225
226impl From<SourceRange> for Metadata {
227    fn from(source_range: SourceRange) -> Self {
228        Self { source_range }
229    }
230}
231
232impl<T> From<NodeRef<'_, T>> for Metadata {
233    fn from(node: NodeRef<'_, T>) -> Self {
234        Self {
235            source_range: SourceRange::new(node.start, node.end, node.module_id),
236        }
237    }
238}
239
240impl From<&Expr> for Metadata {
241    fn from(expr: &Expr) -> Self {
242        Self {
243            source_range: SourceRange::from(expr),
244        }
245    }
246}
247
248/// The type of ExecutorContext being used
249#[derive(PartialEq, Debug, Default, Clone)]
250pub enum ContextType {
251    /// Live engine connection
252    #[default]
253    Live,
254
255    /// Completely mocked connection
256    /// Mock mode is only for the Design Studio when they just want to mock engine calls and not
257    /// actually make them.
258    Mock,
259
260    /// Handled by some other interpreter/conversion system
261    MockCustomForwarded,
262}
263
264/// The executor context.
265/// Cloning will return another handle to the same engine connection/session,
266/// as this uses `Arc` under the hood.
267#[derive(Debug, Clone)]
268pub struct ExecutorContext {
269    pub engine: Arc<Box<dyn EngineManager>>,
270    pub fs: Arc<FileManager>,
271    pub settings: ExecutorSettings,
272    pub context_type: ContextType,
273}
274
275/// The executor settings.
276#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS)]
277#[ts(export)]
278pub struct ExecutorSettings {
279    /// Highlight edges of 3D objects?
280    pub highlight_edges: bool,
281    /// Whether or not Screen Space Ambient Occlusion (SSAO) is enabled.
282    pub enable_ssao: bool,
283    /// Show grid?
284    pub show_grid: bool,
285    /// Should engine store this for replay?
286    /// If so, under what name?
287    pub replay: Option<String>,
288    /// The directory of the current project.  This is used for resolving import
289    /// paths.  If None is given, the current working directory is used.
290    pub project_directory: Option<TypedPath>,
291    /// This is the path to the current file being executed.
292    /// We use this for preventing cyclic imports.
293    pub current_file: Option<TypedPath>,
294    /// Whether or not to automatically scale the grid when user zooms.
295    pub fixed_size_grid: bool,
296}
297
298impl Default for ExecutorSettings {
299    fn default() -> Self {
300        Self {
301            highlight_edges: true,
302            enable_ssao: false,
303            show_grid: false,
304            replay: None,
305            project_directory: None,
306            current_file: None,
307            fixed_size_grid: true,
308        }
309    }
310}
311
312impl From<crate::settings::types::Configuration> for ExecutorSettings {
313    fn from(config: crate::settings::types::Configuration) -> Self {
314        Self::from(config.settings)
315    }
316}
317
318impl From<crate::settings::types::Settings> for ExecutorSettings {
319    fn from(settings: crate::settings::types::Settings) -> Self {
320        Self {
321            highlight_edges: settings.modeling.highlight_edges.into(),
322            enable_ssao: settings.modeling.enable_ssao.into(),
323            show_grid: settings.modeling.show_scale_grid,
324            replay: None,
325            project_directory: None,
326            current_file: None,
327            fixed_size_grid: settings.modeling.fixed_size_grid,
328        }
329    }
330}
331
332impl From<crate::settings::types::project::ProjectConfiguration> for ExecutorSettings {
333    fn from(config: crate::settings::types::project::ProjectConfiguration) -> Self {
334        Self::from(config.settings.modeling)
335    }
336}
337
338impl From<crate::settings::types::ModelingSettings> for ExecutorSettings {
339    fn from(modeling: crate::settings::types::ModelingSettings) -> Self {
340        Self {
341            highlight_edges: modeling.highlight_edges.into(),
342            enable_ssao: modeling.enable_ssao.into(),
343            show_grid: modeling.show_scale_grid,
344            replay: None,
345            project_directory: None,
346            current_file: None,
347            fixed_size_grid: true,
348        }
349    }
350}
351
352impl From<crate::settings::types::project::ProjectModelingSettings> for ExecutorSettings {
353    fn from(modeling: crate::settings::types::project::ProjectModelingSettings) -> Self {
354        Self {
355            highlight_edges: modeling.highlight_edges.into(),
356            enable_ssao: modeling.enable_ssao.into(),
357            show_grid: Default::default(),
358            replay: None,
359            project_directory: None,
360            current_file: None,
361            fixed_size_grid: true,
362        }
363    }
364}
365
366impl ExecutorSettings {
367    /// Add the current file path to the executor settings.
368    pub fn with_current_file(&mut self, current_file: TypedPath) {
369        // We want the parent directory of the file.
370        if current_file.extension() == Some("kcl") {
371            self.current_file = Some(current_file.clone());
372            // Get the parent directory.
373            if let Some(parent) = current_file.parent() {
374                self.project_directory = Some(parent);
375            } else {
376                self.project_directory = Some(TypedPath::from(""));
377            }
378        } else {
379            self.project_directory = Some(current_file);
380        }
381    }
382}
383
384impl ExecutorContext {
385    /// Create a new default executor context.
386    #[cfg(not(target_arch = "wasm32"))]
387    pub async fn new(client: &kittycad::Client, settings: ExecutorSettings) -> Result<Self> {
388        let pool = std::env::var("ZOO_ENGINE_POOL").ok();
389        let (ws, _headers) = client
390            .modeling()
391            .commands_ws(
392                None,
393                None,
394                pool,
395                if settings.enable_ssao {
396                    Some(kittycad::types::PostEffectType::Ssao)
397                } else {
398                    None
399                },
400                settings.replay.clone(),
401                if settings.show_grid { Some(true) } else { None },
402                None,
403                None,
404                None,
405                Some(false),
406            )
407            .await?;
408
409        let engine: Arc<Box<dyn EngineManager>> =
410            Arc::new(Box::new(crate::engine::conn::EngineConnection::new(ws).await?));
411
412        Ok(Self {
413            engine,
414            fs: Arc::new(FileManager::new()),
415            settings,
416            context_type: ContextType::Live,
417        })
418    }
419
420    #[cfg(target_arch = "wasm32")]
421    pub fn new(engine: Arc<Box<dyn EngineManager>>, fs: Arc<FileManager>, settings: ExecutorSettings) -> Self {
422        ExecutorContext {
423            engine,
424            fs,
425            settings,
426            context_type: ContextType::Live,
427        }
428    }
429
430    #[cfg(not(target_arch = "wasm32"))]
431    pub async fn new_mock(settings: Option<ExecutorSettings>) -> Self {
432        ExecutorContext {
433            engine: Arc::new(Box::new(crate::engine::conn_mock::EngineConnection::new().unwrap())),
434            fs: Arc::new(FileManager::new()),
435            settings: settings.unwrap_or_default(),
436            context_type: ContextType::Mock,
437        }
438    }
439
440    #[cfg(target_arch = "wasm32")]
441    pub fn new_mock(engine: Arc<Box<dyn EngineManager>>, fs: Arc<FileManager>, settings: ExecutorSettings) -> Self {
442        ExecutorContext {
443            engine,
444            fs,
445            settings,
446            context_type: ContextType::Mock,
447        }
448    }
449
450    #[cfg(not(target_arch = "wasm32"))]
451    pub fn new_forwarded_mock(engine: Arc<Box<dyn EngineManager>>) -> Self {
452        ExecutorContext {
453            engine,
454            fs: Arc::new(FileManager::new()),
455            settings: Default::default(),
456            context_type: ContextType::MockCustomForwarded,
457        }
458    }
459
460    /// Create a new default executor context.
461    /// With a kittycad client.
462    /// This allows for passing in `ZOO_API_TOKEN` and `ZOO_HOST` as environment
463    /// variables.
464    /// But also allows for passing in a token and engine address directly.
465    #[cfg(not(target_arch = "wasm32"))]
466    pub async fn new_with_client(
467        settings: ExecutorSettings,
468        token: Option<String>,
469        engine_addr: Option<String>,
470    ) -> Result<Self> {
471        // Create the client.
472        let client = crate::engine::new_zoo_client(token, engine_addr)?;
473
474        let ctx = Self::new(&client, settings).await?;
475        Ok(ctx)
476    }
477
478    /// Create a new default executor context.
479    /// With the default kittycad client.
480    /// This allows for passing in `ZOO_API_TOKEN` and `ZOO_HOST` as environment
481    /// variables.
482    #[cfg(not(target_arch = "wasm32"))]
483    pub async fn new_with_default_client() -> Result<Self> {
484        // Create the client.
485        let ctx = Self::new_with_client(Default::default(), None, None).await?;
486        Ok(ctx)
487    }
488
489    /// For executing unit tests.
490    #[cfg(not(target_arch = "wasm32"))]
491    pub async fn new_for_unit_test(engine_addr: Option<String>) -> Result<Self> {
492        let ctx = ExecutorContext::new_with_client(
493            ExecutorSettings {
494                highlight_edges: true,
495                enable_ssao: false,
496                show_grid: false,
497                replay: None,
498                project_directory: None,
499                current_file: None,
500                fixed_size_grid: false,
501            },
502            None,
503            engine_addr,
504        )
505        .await?;
506        Ok(ctx)
507    }
508
509    pub fn is_mock(&self) -> bool {
510        self.context_type == ContextType::Mock || self.context_type == ContextType::MockCustomForwarded
511    }
512
513    /// Returns true if we should not send engine commands for any reason.
514    pub async fn no_engine_commands(&self) -> bool {
515        self.is_mock()
516    }
517
518    pub async fn send_clear_scene(
519        &self,
520        exec_state: &mut ExecState,
521        source_range: crate::execution::SourceRange,
522    ) -> Result<(), KclError> {
523        // Ensure artifacts are cleared so that we don't accumulate them across
524        // runs.
525        exec_state.mod_local.artifacts.clear();
526        exec_state.global.root_module_artifacts.clear();
527        exec_state.global.artifacts.clear();
528
529        self.engine
530            .clear_scene(&mut exec_state.mod_local.id_generator, source_range)
531            .await
532    }
533
534    pub async fn bust_cache_and_reset_scene(&self) -> Result<ExecOutcome, KclErrorWithOutputs> {
535        cache::bust_cache().await;
536
537        // Execute an empty program to clear and reset the scene.
538        // We specifically want to be returned the objects after the scene is reset.
539        // Like the default planes so it is easier to just execute an empty program
540        // after the cache is busted.
541        let outcome = self.run_with_caching(crate::Program::empty()).await?;
542
543        Ok(outcome)
544    }
545
546    async fn prepare_mem(&self, exec_state: &mut ExecState) -> Result<(), KclErrorWithOutputs> {
547        self.eval_prelude(exec_state, SourceRange::synthetic())
548            .await
549            .map_err(KclErrorWithOutputs::no_outputs)?;
550        exec_state.mut_stack().push_new_root_env(true);
551        Ok(())
552    }
553
554    pub async fn run_mock(
555        &self,
556        program: &crate::Program,
557        use_prev_memory: bool,
558    ) -> Result<ExecOutcome, KclErrorWithOutputs> {
559        assert!(
560            self.is_mock(),
561            "To use mock execution, instantiate via ExecutorContext::new_mock, not ::new"
562        );
563
564        let mut exec_state = ExecState::new(self);
565        if use_prev_memory {
566            match cache::read_old_memory().await {
567                Some(mem) => {
568                    *exec_state.mut_stack() = mem.0;
569                    exec_state.global.module_infos = mem.1;
570                }
571                None => self.prepare_mem(&mut exec_state).await?,
572            }
573        } else {
574            self.prepare_mem(&mut exec_state).await?
575        };
576
577        // Push a scope so that old variables can be overwritten (since we might be re-executing some
578        // part of the scene).
579        exec_state.mut_stack().push_new_env_for_scope();
580
581        let result = self.inner_run(program, &mut exec_state, true).await?;
582
583        // Restore any temporary variables, then save any newly created variables back to
584        // memory in case another run wants to use them. Note this is just saved to the preserved
585        // memory, not to the exec_state which is not cached for mock execution.
586
587        let mut mem = exec_state.stack().clone();
588        let module_infos = exec_state.global.module_infos.clone();
589        let outcome = exec_state.into_exec_outcome(result.0, self).await;
590
591        mem.squash_env(result.0);
592        cache::write_old_memory((mem, module_infos)).await;
593
594        Ok(outcome)
595    }
596
597    pub async fn run_with_caching(&self, program: crate::Program) -> Result<ExecOutcome, KclErrorWithOutputs> {
598        assert!(!self.is_mock());
599        let grid_scale = if self.settings.fixed_size_grid {
600            GridScaleBehavior::Fixed(program.meta_settings().ok().flatten().map(|s| s.default_length_units))
601        } else {
602            GridScaleBehavior::ScaleWithZoom
603        };
604
605        let original_program = program.clone();
606
607        let (_program, exec_state, result) = match cache::read_old_ast().await {
608            Some(mut cached_state) => {
609                let old = CacheInformation {
610                    ast: &cached_state.main.ast,
611                    settings: &cached_state.settings,
612                };
613                let new = CacheInformation {
614                    ast: &program.ast,
615                    settings: &self.settings,
616                };
617
618                // Get the program that actually changed from the old and new information.
619                let (clear_scene, program, import_check_info) = match cache::get_changed_program(old, new).await {
620                    CacheResult::ReExecute {
621                        clear_scene,
622                        reapply_settings,
623                        program: changed_program,
624                    } => {
625                        if reapply_settings
626                            && self
627                                .engine
628                                .reapply_settings(
629                                    &self.settings,
630                                    Default::default(),
631                                    &mut cached_state.main.exec_state.id_generator,
632                                    grid_scale,
633                                )
634                                .await
635                                .is_err()
636                        {
637                            (true, program, None)
638                        } else {
639                            (
640                                clear_scene,
641                                crate::Program {
642                                    ast: changed_program,
643                                    original_file_contents: program.original_file_contents,
644                                },
645                                None,
646                            )
647                        }
648                    }
649                    CacheResult::CheckImportsOnly {
650                        reapply_settings,
651                        ast: changed_program,
652                    } => {
653                        if reapply_settings
654                            && self
655                                .engine
656                                .reapply_settings(
657                                    &self.settings,
658                                    Default::default(),
659                                    &mut cached_state.main.exec_state.id_generator,
660                                    grid_scale,
661                                )
662                                .await
663                                .is_err()
664                        {
665                            (true, program, None)
666                        } else {
667                            // We need to check our imports to see if they changed.
668                            let mut new_exec_state = ExecState::new(self);
669                            let (new_universe, new_universe_map) =
670                                self.get_universe(&program, &mut new_exec_state).await?;
671
672                            let clear_scene = new_universe.values().any(|value| {
673                                let id = value.1;
674                                match (
675                                    cached_state.exec_state.get_source(id),
676                                    new_exec_state.global.get_source(id),
677                                ) {
678                                    (Some(s0), Some(s1)) => s0.source != s1.source,
679                                    _ => false,
680                                }
681                            });
682
683                            if !clear_scene {
684                                // Return early we don't need to clear the scene.
685                                return Ok(cached_state.into_exec_outcome(self).await);
686                            }
687
688                            (
689                                true,
690                                crate::Program {
691                                    ast: changed_program,
692                                    original_file_contents: program.original_file_contents,
693                                },
694                                Some((new_universe, new_universe_map, new_exec_state)),
695                            )
696                        }
697                    }
698                    CacheResult::NoAction(true) => {
699                        if self
700                            .engine
701                            .reapply_settings(
702                                &self.settings,
703                                Default::default(),
704                                &mut cached_state.main.exec_state.id_generator,
705                                grid_scale,
706                            )
707                            .await
708                            .is_ok()
709                        {
710                            // We need to update the old ast state with the new settings!!
711                            cache::write_old_ast(GlobalState::with_settings(
712                                cached_state.clone(),
713                                self.settings.clone(),
714                            ))
715                            .await;
716
717                            return Ok(cached_state.into_exec_outcome(self).await);
718                        }
719                        (true, program, None)
720                    }
721                    CacheResult::NoAction(false) => {
722                        return Ok(cached_state.into_exec_outcome(self).await);
723                    }
724                };
725
726                let (exec_state, result) = match import_check_info {
727                    Some((new_universe, new_universe_map, mut new_exec_state)) => {
728                        // Clear the scene if the imports changed.
729                        self.send_clear_scene(&mut new_exec_state, Default::default())
730                            .await
731                            .map_err(KclErrorWithOutputs::no_outputs)?;
732
733                        let result = self
734                            .run_concurrent(
735                                &program,
736                                &mut new_exec_state,
737                                Some((new_universe, new_universe_map)),
738                                false,
739                            )
740                            .await;
741
742                        (new_exec_state, result)
743                    }
744                    None if clear_scene => {
745                        // Pop the execution state, since we are starting fresh.
746                        let mut exec_state = cached_state.reconstitute_exec_state();
747                        exec_state.reset(self);
748
749                        self.send_clear_scene(&mut exec_state, Default::default())
750                            .await
751                            .map_err(KclErrorWithOutputs::no_outputs)?;
752
753                        let result = self.run_concurrent(&program, &mut exec_state, None, false).await;
754
755                        (exec_state, result)
756                    }
757                    None => {
758                        let mut exec_state = cached_state.reconstitute_exec_state();
759                        exec_state.mut_stack().restore_env(cached_state.main.result_env);
760
761                        let result = self.run_concurrent(&program, &mut exec_state, None, true).await;
762
763                        (exec_state, result)
764                    }
765                };
766
767                (program, exec_state, result)
768            }
769            None => {
770                let mut exec_state = ExecState::new(self);
771                self.send_clear_scene(&mut exec_state, Default::default())
772                    .await
773                    .map_err(KclErrorWithOutputs::no_outputs)?;
774
775                let result = self.run_concurrent(&program, &mut exec_state, None, false).await;
776
777                (program, exec_state, result)
778            }
779        };
780
781        if result.is_err() {
782            cache::bust_cache().await;
783        }
784
785        // Throw the error.
786        let result = result?;
787
788        // Save this as the last successful execution to the cache.
789        // Gotcha: `CacheResult::ReExecute.program` may be diff-based, do not save that AST
790        // the last-successful AST. Instead, save in the full AST passed in.
791        cache::write_old_ast(GlobalState::new(
792            exec_state.clone(),
793            self.settings.clone(),
794            original_program.ast,
795            result.0,
796        ))
797        .await;
798
799        let outcome = exec_state.into_exec_outcome(result.0, self).await;
800        Ok(outcome)
801    }
802
803    /// Perform the execution of a program.
804    ///
805    /// To access non-fatal errors and warnings, extract them from the `ExecState`.
806    pub async fn run(
807        &self,
808        program: &crate::Program,
809        exec_state: &mut ExecState,
810    ) -> Result<(EnvironmentRef, Option<ModelingSessionData>), KclErrorWithOutputs> {
811        self.run_concurrent(program, exec_state, None, false).await
812    }
813
814    /// Perform the execution of a program using a concurrent
815    /// execution model.
816    ///
817    /// To access non-fatal errors and warnings, extract them from the `ExecState`.
818    pub async fn run_concurrent(
819        &self,
820        program: &crate::Program,
821        exec_state: &mut ExecState,
822        universe_info: Option<(Universe, UniverseMap)>,
823        preserve_mem: bool,
824    ) -> Result<(EnvironmentRef, Option<ModelingSessionData>), KclErrorWithOutputs> {
825        // Reuse our cached universe if we have one.
826
827        let (universe, universe_map) = if let Some((universe, universe_map)) = universe_info {
828            (universe, universe_map)
829        } else {
830            self.get_universe(program, exec_state).await?
831        };
832
833        let default_planes = self.engine.get_default_planes().read().await.clone();
834
835        // Run the prelude to set up the engine.
836        self.eval_prelude(exec_state, SourceRange::synthetic())
837            .await
838            .map_err(KclErrorWithOutputs::no_outputs)?;
839
840        for modules in import_graph::import_graph(&universe, self)
841            .map_err(|err| exec_state.error_with_outputs(err, None, default_planes.clone()))?
842            .into_iter()
843        {
844            #[cfg(not(target_arch = "wasm32"))]
845            let mut set = tokio::task::JoinSet::new();
846
847            #[allow(clippy::type_complexity)]
848            let (results_tx, mut results_rx): (
849                tokio::sync::mpsc::Sender<(ModuleId, ModulePath, Result<ModuleRepr, KclError>)>,
850                tokio::sync::mpsc::Receiver<_>,
851            ) = tokio::sync::mpsc::channel(1);
852
853            for module in modules {
854                let Some((import_stmt, module_id, module_path, repr)) = universe.get(&module) else {
855                    return Err(KclErrorWithOutputs::no_outputs(KclError::new_internal(
856                        KclErrorDetails::new(format!("Module {module} not found in universe"), Default::default()),
857                    )));
858                };
859                let module_id = *module_id;
860                let module_path = module_path.clone();
861                let source_range = SourceRange::from(import_stmt);
862                // Clone before mutating.
863                let module_exec_state = exec_state.clone();
864
865                self.add_import_module_ops(
866                    exec_state,
867                    program,
868                    module_id,
869                    &module_path,
870                    source_range,
871                    &universe_map,
872                );
873
874                let repr = repr.clone();
875                let exec_ctxt = self.clone();
876                let results_tx = results_tx.clone();
877
878                let exec_module = async |exec_ctxt: &ExecutorContext,
879                                         repr: &ModuleRepr,
880                                         module_id: ModuleId,
881                                         module_path: &ModulePath,
882                                         exec_state: &mut ExecState,
883                                         source_range: SourceRange|
884                       -> Result<ModuleRepr, KclError> {
885                    match repr {
886                        ModuleRepr::Kcl(program, _) => {
887                            let result = exec_ctxt
888                                .exec_module_from_ast(program, module_id, module_path, exec_state, source_range, false)
889                                .await;
890
891                            result.map(|val| ModuleRepr::Kcl(program.clone(), Some(val)))
892                        }
893                        ModuleRepr::Foreign(geom, _) => {
894                            let result = crate::execution::import::send_to_engine(geom.clone(), exec_state, exec_ctxt)
895                                .await
896                                .map(|geom| Some(KclValue::ImportedGeometry(geom)));
897
898                            result.map(|val| {
899                                ModuleRepr::Foreign(geom.clone(), Some((val, exec_state.mod_local.artifacts.clone())))
900                            })
901                        }
902                        ModuleRepr::Dummy | ModuleRepr::Root => Err(KclError::new_internal(KclErrorDetails::new(
903                            format!("Module {module_path} not found in universe"),
904                            vec![source_range],
905                        ))),
906                    }
907                };
908
909                #[cfg(target_arch = "wasm32")]
910                {
911                    wasm_bindgen_futures::spawn_local(async move {
912                        let mut exec_state = module_exec_state;
913                        let exec_ctxt = exec_ctxt;
914
915                        let result = exec_module(
916                            &exec_ctxt,
917                            &repr,
918                            module_id,
919                            &module_path,
920                            &mut exec_state,
921                            source_range,
922                        )
923                        .await;
924
925                        results_tx
926                            .send((module_id, module_path, result))
927                            .await
928                            .unwrap_or_default();
929                    });
930                }
931                #[cfg(not(target_arch = "wasm32"))]
932                {
933                    set.spawn(async move {
934                        let mut exec_state = module_exec_state;
935                        let exec_ctxt = exec_ctxt;
936
937                        let result = exec_module(
938                            &exec_ctxt,
939                            &repr,
940                            module_id,
941                            &module_path,
942                            &mut exec_state,
943                            source_range,
944                        )
945                        .await;
946
947                        results_tx
948                            .send((module_id, module_path, result))
949                            .await
950                            .unwrap_or_default();
951                    });
952                }
953            }
954
955            drop(results_tx);
956
957            while let Some((module_id, _, result)) = results_rx.recv().await {
958                match result {
959                    Ok(new_repr) => {
960                        let mut repr = exec_state.global.module_infos[&module_id].take_repr();
961
962                        match &mut repr {
963                            ModuleRepr::Kcl(_, cache) => {
964                                let ModuleRepr::Kcl(_, session_data) = new_repr else {
965                                    unreachable!();
966                                };
967                                *cache = session_data;
968                            }
969                            ModuleRepr::Foreign(_, cache) => {
970                                let ModuleRepr::Foreign(_, session_data) = new_repr else {
971                                    unreachable!();
972                                };
973                                *cache = session_data;
974                            }
975                            ModuleRepr::Dummy | ModuleRepr::Root => unreachable!(),
976                        }
977
978                        exec_state.global.module_infos[&module_id].restore_repr(repr);
979                    }
980                    Err(e) => {
981                        return Err(exec_state.error_with_outputs(e, None, default_planes));
982                    }
983                }
984            }
985        }
986
987        // Since we haven't technically started executing the root module yet,
988        // the operations corresponding to the imports will be missing unless we
989        // track them here.
990        exec_state
991            .global
992            .root_module_artifacts
993            .extend(std::mem::take(&mut exec_state.mod_local.artifacts));
994
995        self.inner_run(program, exec_state, preserve_mem).await
996    }
997
998    /// Get the universe & universe map of the program.
999    /// And see if any of the imports changed.
1000    async fn get_universe(
1001        &self,
1002        program: &crate::Program,
1003        exec_state: &mut ExecState,
1004    ) -> Result<(Universe, UniverseMap), KclErrorWithOutputs> {
1005        exec_state.add_root_module_contents(program);
1006
1007        let mut universe = std::collections::HashMap::new();
1008
1009        let default_planes = self.engine.get_default_planes().read().await.clone();
1010
1011        let root_imports = import_graph::import_universe(
1012            self,
1013            &ModulePath::Main,
1014            &ModuleRepr::Kcl(program.ast.clone(), None),
1015            &mut universe,
1016            exec_state,
1017        )
1018        .await
1019        .map_err(|err| exec_state.error_with_outputs(err, None, default_planes))?;
1020
1021        Ok((universe, root_imports))
1022    }
1023
1024    #[cfg(not(feature = "artifact-graph"))]
1025    fn add_import_module_ops(
1026        &self,
1027        _exec_state: &mut ExecState,
1028        _program: &crate::Program,
1029        _module_id: ModuleId,
1030        _module_path: &ModulePath,
1031        _source_range: SourceRange,
1032        _universe_map: &UniverseMap,
1033    ) {
1034    }
1035
1036    #[cfg(feature = "artifact-graph")]
1037    fn add_import_module_ops(
1038        &self,
1039        exec_state: &mut ExecState,
1040        program: &crate::Program,
1041        module_id: ModuleId,
1042        module_path: &ModulePath,
1043        source_range: SourceRange,
1044        universe_map: &UniverseMap,
1045    ) {
1046        match module_path {
1047            ModulePath::Main => {
1048                // This should never happen.
1049            }
1050            ModulePath::Local {
1051                value,
1052                original_import_path,
1053            } => {
1054                // We only want to display the top-level module imports in
1055                // the Feature Tree, not transitive imports.
1056                if universe_map.contains_key(value) {
1057                    use crate::NodePath;
1058
1059                    let node_path = if source_range.is_top_level_module() {
1060                        let cached_body_items = exec_state.global.artifacts.cached_body_items();
1061                        NodePath::from_range(&program.ast, cached_body_items, source_range).unwrap_or_default()
1062                    } else {
1063                        // The frontend doesn't care about paths in
1064                        // files other than the top-level module.
1065                        NodePath::placeholder()
1066                    };
1067
1068                    let name = match original_import_path {
1069                        Some(value) => value.to_string_lossy(),
1070                        None => value.file_name().unwrap_or_default(),
1071                    };
1072                    exec_state.push_op(Operation::GroupBegin {
1073                        group: Group::ModuleInstance { name, module_id },
1074                        node_path,
1075                        source_range,
1076                    });
1077                    // Due to concurrent execution, we cannot easily
1078                    // group operations by module. So we leave the
1079                    // group empty and close it immediately.
1080                    exec_state.push_op(Operation::GroupEnd);
1081                }
1082            }
1083            ModulePath::Std { .. } => {
1084                // We don't want to display stdlib in the Feature Tree.
1085            }
1086        }
1087    }
1088
1089    /// Perform the execution of a program.  Accept all possible parameters and
1090    /// output everything.
1091    async fn inner_run(
1092        &self,
1093        program: &crate::Program,
1094        exec_state: &mut ExecState,
1095        preserve_mem: bool,
1096    ) -> Result<(EnvironmentRef, Option<ModelingSessionData>), KclErrorWithOutputs> {
1097        let _stats = crate::log::LogPerfStats::new("Interpretation");
1098
1099        // Re-apply the settings, in case the cache was busted.
1100        let grid_scale = if self.settings.fixed_size_grid {
1101            GridScaleBehavior::Fixed(program.meta_settings().ok().flatten().map(|s| s.default_length_units))
1102        } else {
1103            GridScaleBehavior::ScaleWithZoom
1104        };
1105        self.engine
1106            .reapply_settings(
1107                &self.settings,
1108                Default::default(),
1109                exec_state.id_generator(),
1110                grid_scale,
1111            )
1112            .await
1113            .map_err(KclErrorWithOutputs::no_outputs)?;
1114
1115        let default_planes = self.engine.get_default_planes().read().await.clone();
1116        let result = self
1117            .execute_and_build_graph(&program.ast, exec_state, preserve_mem)
1118            .await;
1119
1120        crate::log::log(format!(
1121            "Post interpretation KCL memory stats: {:#?}",
1122            exec_state.stack().memory.stats
1123        ));
1124        crate::log::log(format!("Engine stats: {:?}", self.engine.stats()));
1125
1126        let env_ref = result.map_err(|(err, env_ref)| exec_state.error_with_outputs(err, env_ref, default_planes))?;
1127
1128        if !self.is_mock() {
1129            let mut mem = exec_state.stack().deep_clone();
1130            mem.restore_env(env_ref);
1131            cache::write_old_memory((mem, exec_state.global.module_infos.clone())).await;
1132        }
1133        let session_data = self.engine.get_session_data().await;
1134
1135        Ok((env_ref, session_data))
1136    }
1137
1138    /// Execute an AST's program and build auxiliary outputs like the artifact
1139    /// graph.
1140    async fn execute_and_build_graph(
1141        &self,
1142        program: NodeRef<'_, crate::parsing::ast::types::Program>,
1143        exec_state: &mut ExecState,
1144        preserve_mem: bool,
1145    ) -> Result<EnvironmentRef, (KclError, Option<EnvironmentRef>)> {
1146        // Don't early return!  We need to build other outputs regardless of
1147        // whether execution failed.
1148
1149        // Because of execution caching, we may start with operations from a
1150        // previous run.
1151        #[cfg(feature = "artifact-graph")]
1152        let start_op = exec_state.global.root_module_artifacts.operations.len();
1153
1154        self.eval_prelude(exec_state, SourceRange::from(program).start_as_range())
1155            .await
1156            .map_err(|e| (e, None))?;
1157
1158        let exec_result = self
1159            .exec_module_body(
1160                program,
1161                exec_state,
1162                preserve_mem,
1163                ModuleId::default(),
1164                &ModulePath::Main,
1165            )
1166            .await
1167            .map(
1168                |ModuleExecutionOutcome {
1169                     environment: env_ref,
1170                     artifacts: module_artifacts,
1171                     ..
1172                 }| {
1173                    // We need to extend because it may already have operations from
1174                    // imports.
1175                    exec_state.global.root_module_artifacts.extend(module_artifacts);
1176                    env_ref
1177                },
1178            )
1179            .map_err(|(err, env_ref, module_artifacts)| {
1180                if let Some(module_artifacts) = module_artifacts {
1181                    // We need to extend because it may already have operations
1182                    // from imports.
1183                    exec_state.global.root_module_artifacts.extend(module_artifacts);
1184                }
1185                (err, env_ref)
1186            });
1187
1188        #[cfg(feature = "artifact-graph")]
1189        {
1190            // Fill in NodePath for operations.
1191            let cached_body_items = exec_state.global.artifacts.cached_body_items();
1192            for op in exec_state
1193                .global
1194                .root_module_artifacts
1195                .operations
1196                .iter_mut()
1197                .skip(start_op)
1198            {
1199                op.fill_node_paths(program, cached_body_items);
1200            }
1201            for module in exec_state.global.module_infos.values_mut() {
1202                if let ModuleRepr::Kcl(_, Some(outcome)) = &mut module.repr {
1203                    for op in &mut outcome.artifacts.operations {
1204                        op.fill_node_paths(program, cached_body_items);
1205                    }
1206                }
1207            }
1208        }
1209
1210        // Ensure all the async commands completed.
1211        self.engine.ensure_async_commands_completed().await.map_err(|e| {
1212            match &exec_result {
1213                Ok(env_ref) => (e, Some(*env_ref)),
1214                // Prefer the execution error.
1215                Err((exec_err, env_ref)) => (exec_err.clone(), *env_ref),
1216            }
1217        })?;
1218
1219        // If we errored out and early-returned, there might be commands which haven't been executed
1220        // and should be dropped.
1221        self.engine.clear_queues().await;
1222
1223        match exec_state.build_artifact_graph(&self.engine, program).await {
1224            Ok(_) => exec_result,
1225            Err(err) => exec_result.and_then(|env_ref| Err((err, Some(env_ref)))),
1226        }
1227    }
1228
1229    /// 'Import' std::prelude as the outermost scope.
1230    ///
1231    /// SAFETY: the current thread must have sole access to the memory referenced in exec_state.
1232    async fn eval_prelude(&self, exec_state: &mut ExecState, source_range: SourceRange) -> Result<(), KclError> {
1233        if exec_state.stack().memory.requires_std() {
1234            #[cfg(feature = "artifact-graph")]
1235            let initial_ops = exec_state.mod_local.artifacts.operations.len();
1236
1237            let path = vec!["std".to_owned(), "prelude".to_owned()];
1238            let resolved_path = ModulePath::from_std_import_path(&path)?;
1239            let id = self
1240                .open_module(&ImportPath::Std { path }, &[], &resolved_path, exec_state, source_range)
1241                .await?;
1242            let (module_memory, _) = self.exec_module_for_items(id, exec_state, source_range).await?;
1243
1244            exec_state.mut_stack().memory.set_std(module_memory);
1245
1246            // Operations generated by the prelude are not useful, so clear them
1247            // out.
1248            //
1249            // TODO: Should we also clear them out of each module so that they
1250            // don't appear in test output?
1251            #[cfg(feature = "artifact-graph")]
1252            exec_state.mod_local.artifacts.operations.truncate(initial_ops);
1253        }
1254
1255        Ok(())
1256    }
1257
1258    /// Get a snapshot of the current scene.
1259    pub async fn prepare_snapshot(&self) -> std::result::Result<TakeSnapshot, ExecError> {
1260        // Zoom to fit.
1261        self.engine
1262            .send_modeling_cmd(
1263                uuid::Uuid::new_v4(),
1264                crate::execution::SourceRange::default(),
1265                &ModelingCmd::from(mcmd::ZoomToFit {
1266                    object_ids: Default::default(),
1267                    animated: false,
1268                    padding: 0.1,
1269                }),
1270            )
1271            .await
1272            .map_err(KclErrorWithOutputs::no_outputs)?;
1273
1274        // Send a snapshot request to the engine.
1275        let resp = self
1276            .engine
1277            .send_modeling_cmd(
1278                uuid::Uuid::new_v4(),
1279                crate::execution::SourceRange::default(),
1280                &ModelingCmd::from(mcmd::TakeSnapshot {
1281                    format: ImageFormat::Png,
1282                }),
1283            )
1284            .await
1285            .map_err(KclErrorWithOutputs::no_outputs)?;
1286
1287        let OkWebSocketResponseData::Modeling {
1288            modeling_response: OkModelingCmdResponse::TakeSnapshot(contents),
1289        } = resp
1290        else {
1291            return Err(ExecError::BadPng(format!(
1292                "Instead of a TakeSnapshot response, the engine returned {resp:?}"
1293            )));
1294        };
1295        Ok(contents)
1296    }
1297
1298    /// Export the current scene as a CAD file.
1299    pub async fn export(
1300        &self,
1301        format: kittycad_modeling_cmds::format::OutputFormat3d,
1302    ) -> Result<Vec<kittycad_modeling_cmds::websocket::RawFile>, KclError> {
1303        let resp = self
1304            .engine
1305            .send_modeling_cmd(
1306                uuid::Uuid::new_v4(),
1307                crate::SourceRange::default(),
1308                &kittycad_modeling_cmds::ModelingCmd::Export(kittycad_modeling_cmds::Export {
1309                    entity_ids: vec![],
1310                    format,
1311                }),
1312            )
1313            .await?;
1314
1315        let kittycad_modeling_cmds::websocket::OkWebSocketResponseData::Export { files } = resp else {
1316            return Err(KclError::new_internal(crate::errors::KclErrorDetails::new(
1317                format!("Expected Export response, got {resp:?}",),
1318                vec![SourceRange::default()],
1319            )));
1320        };
1321
1322        Ok(files)
1323    }
1324
1325    /// Export the current scene as a STEP file.
1326    pub async fn export_step(
1327        &self,
1328        deterministic_time: bool,
1329    ) -> Result<Vec<kittycad_modeling_cmds::websocket::RawFile>, KclError> {
1330        let files = self
1331            .export(kittycad_modeling_cmds::format::OutputFormat3d::Step(
1332                kittycad_modeling_cmds::format::step::export::Options {
1333                    coords: *kittycad_modeling_cmds::coord::KITTYCAD,
1334                    created: if deterministic_time {
1335                        Some("2021-01-01T00:00:00Z".parse().map_err(|e| {
1336                            KclError::new_internal(crate::errors::KclErrorDetails::new(
1337                                format!("Failed to parse date: {e}"),
1338                                vec![SourceRange::default()],
1339                            ))
1340                        })?)
1341                    } else {
1342                        None
1343                    },
1344                },
1345            ))
1346            .await?;
1347
1348        Ok(files)
1349    }
1350
1351    pub async fn close(&self) {
1352        self.engine.close().await;
1353    }
1354}
1355
1356#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, Ord, PartialOrd, Hash, ts_rs::TS)]
1357pub struct ArtifactId(Uuid);
1358
1359impl ArtifactId {
1360    pub fn new(uuid: Uuid) -> Self {
1361        Self(uuid)
1362    }
1363}
1364
1365impl From<Uuid> for ArtifactId {
1366    fn from(uuid: Uuid) -> Self {
1367        Self::new(uuid)
1368    }
1369}
1370
1371impl From<&Uuid> for ArtifactId {
1372    fn from(uuid: &Uuid) -> Self {
1373        Self::new(*uuid)
1374    }
1375}
1376
1377impl From<ArtifactId> for Uuid {
1378    fn from(id: ArtifactId) -> Self {
1379        id.0
1380    }
1381}
1382
1383impl From<&ArtifactId> for Uuid {
1384    fn from(id: &ArtifactId) -> Self {
1385        id.0
1386    }
1387}
1388
1389impl From<ModelingCmdId> for ArtifactId {
1390    fn from(id: ModelingCmdId) -> Self {
1391        Self::new(*id.as_ref())
1392    }
1393}
1394
1395impl From<&ModelingCmdId> for ArtifactId {
1396    fn from(id: &ModelingCmdId) -> Self {
1397        Self::new(*id.as_ref())
1398    }
1399}
1400
1401#[cfg(test)]
1402pub(crate) async fn parse_execute(code: &str) -> Result<ExecTestResults, KclError> {
1403    parse_execute_with_project_dir(code, None).await
1404}
1405
1406#[cfg(test)]
1407pub(crate) async fn parse_execute_with_project_dir(
1408    code: &str,
1409    project_directory: Option<TypedPath>,
1410) -> Result<ExecTestResults, KclError> {
1411    let program = crate::Program::parse_no_errs(code)?;
1412
1413    let exec_ctxt = ExecutorContext {
1414        engine: Arc::new(Box::new(crate::engine::conn_mock::EngineConnection::new().map_err(
1415            |err| {
1416                KclError::new_internal(crate::errors::KclErrorDetails::new(
1417                    format!("Failed to create mock engine connection: {err}"),
1418                    vec![SourceRange::default()],
1419                ))
1420            },
1421        )?)),
1422        fs: Arc::new(crate::fs::FileManager::new()),
1423        settings: ExecutorSettings {
1424            project_directory,
1425            ..Default::default()
1426        },
1427        context_type: ContextType::Mock,
1428    };
1429    let mut exec_state = ExecState::new(&exec_ctxt);
1430    let result = exec_ctxt.run(&program, &mut exec_state).await?;
1431
1432    Ok(ExecTestResults {
1433        program,
1434        mem_env: result.0,
1435        exec_ctxt,
1436        exec_state,
1437    })
1438}
1439
1440#[cfg(test)]
1441#[derive(Debug)]
1442pub(crate) struct ExecTestResults {
1443    program: crate::Program,
1444    mem_env: EnvironmentRef,
1445    exec_ctxt: ExecutorContext,
1446    exec_state: ExecState,
1447}
1448
1449#[cfg(test)]
1450mod tests {
1451    use pretty_assertions::assert_eq;
1452
1453    use super::*;
1454    use crate::{
1455        ModuleId,
1456        errors::{KclErrorDetails, Severity},
1457        exec::NumericType,
1458        execution::{memory::Stack, types::RuntimeType},
1459    };
1460
1461    /// Convenience function to get a JSON value from memory and unwrap.
1462    #[track_caller]
1463    fn mem_get_json(memory: &Stack, env: EnvironmentRef, name: &str) -> KclValue {
1464        memory.memory.get_from_unchecked(name, env).unwrap().to_owned()
1465    }
1466
1467    #[tokio::test(flavor = "multi_thread")]
1468    async fn test_execute_warn() {
1469        let text = "@blah";
1470        let result = parse_execute(text).await.unwrap();
1471        let errs = result.exec_state.errors();
1472        assert_eq!(errs.len(), 1);
1473        assert_eq!(errs[0].severity, crate::errors::Severity::Warning);
1474        assert!(
1475            errs[0].message.contains("Unknown annotation"),
1476            "unexpected warning message: {}",
1477            errs[0].message
1478        );
1479    }
1480
1481    #[tokio::test(flavor = "multi_thread")]
1482    async fn test_execute_fn_definitions() {
1483        let ast = r#"fn def(@x) {
1484  return x
1485}
1486fn ghi(@x) {
1487  return x
1488}
1489fn jkl(@x) {
1490  return x
1491}
1492fn hmm(@x) {
1493  return x
1494}
1495
1496yo = 5 + 6
1497
1498abc = 3
1499identifierGuy = 5
1500part001 = startSketchOn(XY)
1501|> startProfile(at = [-1.2, 4.83])
1502|> line(end = [2.8, 0])
1503|> angledLine(angle = 100 + 100, length = 3.01)
1504|> angledLine(angle = abc, length = 3.02)
1505|> angledLine(angle = def(yo), length = 3.03)
1506|> angledLine(angle = ghi(2), length = 3.04)
1507|> angledLine(angle = jkl(yo) + 2, length = 3.05)
1508|> close()
1509yo2 = hmm([identifierGuy + 5])"#;
1510
1511        parse_execute(ast).await.unwrap();
1512    }
1513
1514    #[tokio::test(flavor = "multi_thread")]
1515    async fn test_execute_with_pipe_substitutions_unary() {
1516        let ast = r#"myVar = 3
1517part001 = startSketchOn(XY)
1518  |> startProfile(at = [0, 0])
1519  |> line(end = [3, 4], tag = $seg01)
1520  |> line(end = [
1521  min([segLen(seg01), myVar]),
1522  -legLen(hypotenuse = segLen(seg01), leg = myVar)
1523])
1524"#;
1525
1526        parse_execute(ast).await.unwrap();
1527    }
1528
1529    #[tokio::test(flavor = "multi_thread")]
1530    async fn test_execute_with_pipe_substitutions() {
1531        let ast = r#"myVar = 3
1532part001 = startSketchOn(XY)
1533  |> startProfile(at = [0, 0])
1534  |> line(end = [3, 4], tag = $seg01)
1535  |> line(end = [
1536  min([segLen(seg01), myVar]),
1537  legLen(hypotenuse = segLen(seg01), leg = myVar)
1538])
1539"#;
1540
1541        parse_execute(ast).await.unwrap();
1542    }
1543
1544    #[tokio::test(flavor = "multi_thread")]
1545    async fn test_execute_with_inline_comment() {
1546        let ast = r#"baseThick = 1
1547armAngle = 60
1548
1549baseThickHalf = baseThick / 2
1550halfArmAngle = armAngle / 2
1551
1552arrExpShouldNotBeIncluded = [1, 2, 3]
1553objExpShouldNotBeIncluded = { a = 1, b = 2, c = 3 }
1554
1555part001 = startSketchOn(XY)
1556  |> startProfile(at = [0, 0])
1557  |> yLine(endAbsolute = 1)
1558  |> xLine(length = 3.84) // selection-range-7ish-before-this
1559
1560variableBelowShouldNotBeIncluded = 3
1561"#;
1562
1563        parse_execute(ast).await.unwrap();
1564    }
1565
1566    #[tokio::test(flavor = "multi_thread")]
1567    async fn test_execute_with_function_literal_in_pipe() {
1568        let ast = r#"w = 20
1569l = 8
1570h = 10
1571
1572fn thing() {
1573  return -8
1574}
1575
1576firstExtrude = startSketchOn(XY)
1577  |> startProfile(at = [0,0])
1578  |> line(end = [0, l])
1579  |> line(end = [w, 0])
1580  |> line(end = [0, thing()])
1581  |> close()
1582  |> extrude(length = h)"#;
1583
1584        parse_execute(ast).await.unwrap();
1585    }
1586
1587    #[tokio::test(flavor = "multi_thread")]
1588    async fn test_execute_with_function_unary_in_pipe() {
1589        let ast = r#"w = 20
1590l = 8
1591h = 10
1592
1593fn thing(@x) {
1594  return -x
1595}
1596
1597firstExtrude = startSketchOn(XY)
1598  |> startProfile(at = [0,0])
1599  |> line(end = [0, l])
1600  |> line(end = [w, 0])
1601  |> line(end = [0, thing(8)])
1602  |> close()
1603  |> extrude(length = h)"#;
1604
1605        parse_execute(ast).await.unwrap();
1606    }
1607
1608    #[tokio::test(flavor = "multi_thread")]
1609    async fn test_execute_with_function_array_in_pipe() {
1610        let ast = r#"w = 20
1611l = 8
1612h = 10
1613
1614fn thing(@x) {
1615  return [0, -x]
1616}
1617
1618firstExtrude = startSketchOn(XY)
1619  |> startProfile(at = [0,0])
1620  |> line(end = [0, l])
1621  |> line(end = [w, 0])
1622  |> line(end = thing(8))
1623  |> close()
1624  |> extrude(length = h)"#;
1625
1626        parse_execute(ast).await.unwrap();
1627    }
1628
1629    #[tokio::test(flavor = "multi_thread")]
1630    async fn test_execute_with_function_call_in_pipe() {
1631        let ast = r#"w = 20
1632l = 8
1633h = 10
1634
1635fn other_thing(@y) {
1636  return -y
1637}
1638
1639fn thing(@x) {
1640  return other_thing(x)
1641}
1642
1643firstExtrude = startSketchOn(XY)
1644  |> startProfile(at = [0,0])
1645  |> line(end = [0, l])
1646  |> line(end = [w, 0])
1647  |> line(end = [0, thing(8)])
1648  |> close()
1649  |> extrude(length = h)"#;
1650
1651        parse_execute(ast).await.unwrap();
1652    }
1653
1654    #[tokio::test(flavor = "multi_thread")]
1655    async fn test_execute_with_function_sketch() {
1656        let ast = r#"fn box(h, l, w) {
1657 myBox = startSketchOn(XY)
1658    |> startProfile(at = [0,0])
1659    |> line(end = [0, l])
1660    |> line(end = [w, 0])
1661    |> line(end = [0, -l])
1662    |> close()
1663    |> extrude(length = h)
1664
1665  return myBox
1666}
1667
1668fnBox = box(h = 3, l = 6, w = 10)"#;
1669
1670        parse_execute(ast).await.unwrap();
1671    }
1672
1673    #[tokio::test(flavor = "multi_thread")]
1674    async fn test_get_member_of_object_with_function_period() {
1675        let ast = r#"fn box(@obj) {
1676 myBox = startSketchOn(XY)
1677    |> startProfile(at = obj.start)
1678    |> line(end = [0, obj.l])
1679    |> line(end = [obj.w, 0])
1680    |> line(end = [0, -obj.l])
1681    |> close()
1682    |> extrude(length = obj.h)
1683
1684  return myBox
1685}
1686
1687thisBox = box({start = [0,0], l = 6, w = 10, h = 3})
1688"#;
1689        parse_execute(ast).await.unwrap();
1690    }
1691
1692    #[tokio::test(flavor = "multi_thread")]
1693    #[ignore] // https://github.com/KittyCAD/modeling-app/issues/3338
1694    async fn test_object_member_starting_pipeline() {
1695        let ast = r#"
1696fn test2() {
1697  return {
1698    thing: startSketchOn(XY)
1699      |> startProfile(at = [0, 0])
1700      |> line(end = [0, 1])
1701      |> line(end = [1, 0])
1702      |> line(end = [0, -1])
1703      |> close()
1704  }
1705}
1706
1707x2 = test2()
1708
1709x2.thing
1710  |> extrude(length = 10)
1711"#;
1712        parse_execute(ast).await.unwrap();
1713    }
1714
1715    #[tokio::test(flavor = "multi_thread")]
1716    #[ignore] // ignore til we get loops
1717    async fn test_execute_with_function_sketch_loop_objects() {
1718        let ast = r#"fn box(obj) {
1719let myBox = startSketchOn(XY)
1720    |> startProfile(at = obj.start)
1721    |> line(end = [0, obj.l])
1722    |> line(end = [obj.w, 0])
1723    |> line(end = [0, -obj.l])
1724    |> close()
1725    |> extrude(length = obj.h)
1726
1727  return myBox
1728}
1729
1730for var in [{start: [0,0], l: 6, w: 10, h: 3}, {start: [-10,-10], l: 3, w: 5, h: 1.5}] {
1731  thisBox = box(var)
1732}"#;
1733
1734        parse_execute(ast).await.unwrap();
1735    }
1736
1737    #[tokio::test(flavor = "multi_thread")]
1738    #[ignore] // ignore til we get loops
1739    async fn test_execute_with_function_sketch_loop_array() {
1740        let ast = r#"fn box(h, l, w, start) {
1741 myBox = startSketchOn(XY)
1742    |> startProfile(at = [0,0])
1743    |> line(end = [0, l])
1744    |> line(end = [w, 0])
1745    |> line(end = [0, -l])
1746    |> close()
1747    |> extrude(length = h)
1748
1749  return myBox
1750}
1751
1752
1753for var in [[3, 6, 10, [0,0]], [1.5, 3, 5, [-10,-10]]] {
1754  const thisBox = box(var[0], var[1], var[2], var[3])
1755}"#;
1756
1757        parse_execute(ast).await.unwrap();
1758    }
1759
1760    #[tokio::test(flavor = "multi_thread")]
1761    async fn test_get_member_of_array_with_function() {
1762        let ast = r#"fn box(@arr) {
1763 myBox =startSketchOn(XY)
1764    |> startProfile(at = arr[0])
1765    |> line(end = [0, arr[1]])
1766    |> line(end = [arr[2], 0])
1767    |> line(end = [0, -arr[1]])
1768    |> close()
1769    |> extrude(length = arr[3])
1770
1771  return myBox
1772}
1773
1774thisBox = box([[0,0], 6, 10, 3])
1775
1776"#;
1777        parse_execute(ast).await.unwrap();
1778    }
1779
1780    #[tokio::test(flavor = "multi_thread")]
1781    async fn test_function_cannot_access_future_definitions() {
1782        let ast = r#"
1783fn returnX() {
1784  // x shouldn't be defined yet.
1785  return x
1786}
1787
1788x = 5
1789
1790answer = returnX()"#;
1791
1792        let result = parse_execute(ast).await;
1793        let err = result.unwrap_err();
1794        assert_eq!(err.message(), "`x` is not defined");
1795    }
1796
1797    #[tokio::test(flavor = "multi_thread")]
1798    async fn test_override_prelude() {
1799        let text = "PI = 3.0";
1800        let result = parse_execute(text).await.unwrap();
1801        let errs = result.exec_state.errors();
1802        assert!(errs.is_empty());
1803    }
1804
1805    #[tokio::test(flavor = "multi_thread")]
1806    async fn type_aliases() {
1807        let text = r#"@settings(experimentalFeatures = allow)
1808type MyTy = [number; 2]
1809fn foo(@x: MyTy) {
1810    return x[0]
1811}
1812
1813foo([0, 1])
1814
1815type Other = MyTy | Helix
1816"#;
1817        let result = parse_execute(text).await.unwrap();
1818        let errs = result.exec_state.errors();
1819        assert!(errs.is_empty());
1820    }
1821
1822    #[tokio::test(flavor = "multi_thread")]
1823    async fn test_cannot_shebang_in_fn() {
1824        let ast = r#"
1825fn foo() {
1826  #!hello
1827  return true
1828}
1829
1830foo
1831"#;
1832
1833        let result = parse_execute(ast).await;
1834        let err = result.unwrap_err();
1835        assert_eq!(
1836            err,
1837            KclError::new_syntax(KclErrorDetails::new(
1838                "Unexpected token: #".to_owned(),
1839                vec![SourceRange::new(14, 15, ModuleId::default())],
1840            )),
1841        );
1842    }
1843
1844    #[tokio::test(flavor = "multi_thread")]
1845    async fn test_pattern_transform_function_cannot_access_future_definitions() {
1846        let ast = r#"
1847fn transform(@replicaId) {
1848  // x shouldn't be defined yet.
1849  scale = x
1850  return {
1851    translate = [0, 0, replicaId * 10],
1852    scale = [scale, 1, 0],
1853  }
1854}
1855
1856fn layer() {
1857  return startSketchOn(XY)
1858    |> circle( center= [0, 0], radius= 1, tag = $tag1)
1859    |> extrude(length = 10)
1860}
1861
1862x = 5
1863
1864// The 10 layers are replicas of each other, with a transform applied to each.
1865shape = layer() |> patternTransform(instances = 10, transform = transform)
1866"#;
1867
1868        let result = parse_execute(ast).await;
1869        let err = result.unwrap_err();
1870        assert_eq!(err.message(), "`x` is not defined",);
1871    }
1872
1873    // ADAM: Move some of these into simulation tests.
1874
1875    #[tokio::test(flavor = "multi_thread")]
1876    async fn test_math_execute_with_functions() {
1877        let ast = r#"myVar = 2 + min([100, -1 + legLen(hypotenuse = 5, leg = 3)])"#;
1878        let result = parse_execute(ast).await.unwrap();
1879        assert_eq!(
1880            5.0,
1881            mem_get_json(result.exec_state.stack(), result.mem_env, "myVar")
1882                .as_f64()
1883                .unwrap()
1884        );
1885    }
1886
1887    #[tokio::test(flavor = "multi_thread")]
1888    async fn test_math_execute() {
1889        let ast = r#"myVar = 1 + 2 * (3 - 4) / -5 + 6"#;
1890        let result = parse_execute(ast).await.unwrap();
1891        assert_eq!(
1892            7.4,
1893            mem_get_json(result.exec_state.stack(), result.mem_env, "myVar")
1894                .as_f64()
1895                .unwrap()
1896        );
1897    }
1898
1899    #[tokio::test(flavor = "multi_thread")]
1900    async fn test_math_execute_start_negative() {
1901        let ast = r#"myVar = -5 + 6"#;
1902        let result = parse_execute(ast).await.unwrap();
1903        assert_eq!(
1904            1.0,
1905            mem_get_json(result.exec_state.stack(), result.mem_env, "myVar")
1906                .as_f64()
1907                .unwrap()
1908        );
1909    }
1910
1911    #[tokio::test(flavor = "multi_thread")]
1912    async fn test_math_execute_with_pi() {
1913        let ast = r#"myVar = PI * 2"#;
1914        let result = parse_execute(ast).await.unwrap();
1915        assert_eq!(
1916            std::f64::consts::TAU,
1917            mem_get_json(result.exec_state.stack(), result.mem_env, "myVar")
1918                .as_f64()
1919                .unwrap()
1920        );
1921    }
1922
1923    #[tokio::test(flavor = "multi_thread")]
1924    async fn test_math_define_decimal_without_leading_zero() {
1925        let ast = r#"thing = .4 + 7"#;
1926        let result = parse_execute(ast).await.unwrap();
1927        assert_eq!(
1928            7.4,
1929            mem_get_json(result.exec_state.stack(), result.mem_env, "thing")
1930                .as_f64()
1931                .unwrap()
1932        );
1933    }
1934
1935    #[tokio::test(flavor = "multi_thread")]
1936    async fn pass_std_to_std() {
1937        let ast = r#"sketch001 = startSketchOn(XY)
1938profile001 = circle(sketch001, center = [0, 0], radius = 2)
1939extrude001 = extrude(profile001, length = 5)
1940extrudes = patternLinear3d(
1941  extrude001,
1942  instances = 3,
1943  distance = 5,
1944  axis = [1, 1, 0],
1945)
1946clone001 = map(extrudes, f = clone)
1947"#;
1948        parse_execute(ast).await.unwrap();
1949    }
1950
1951    #[tokio::test(flavor = "multi_thread")]
1952    async fn test_array_reduce_nested_array() {
1953        let code = r#"
1954fn id(@el, accum)  { return accum }
1955
1956answer = reduce([], initial=[[[0,0]]], f=id)
1957"#;
1958        let result = parse_execute(code).await.unwrap();
1959        assert_eq!(
1960            mem_get_json(result.exec_state.stack(), result.mem_env, "answer"),
1961            KclValue::HomArray {
1962                value: vec![KclValue::HomArray {
1963                    value: vec![KclValue::HomArray {
1964                        value: vec![
1965                            KclValue::Number {
1966                                value: 0.0,
1967                                ty: NumericType::default(),
1968                                meta: vec![SourceRange::new(69, 70, Default::default()).into()],
1969                            },
1970                            KclValue::Number {
1971                                value: 0.0,
1972                                ty: NumericType::default(),
1973                                meta: vec![SourceRange::new(71, 72, Default::default()).into()],
1974                            }
1975                        ],
1976                        ty: RuntimeType::any(),
1977                    }],
1978                    ty: RuntimeType::any(),
1979                }],
1980                ty: RuntimeType::any(),
1981            }
1982        );
1983    }
1984
1985    #[tokio::test(flavor = "multi_thread")]
1986    async fn test_zero_param_fn() {
1987        let ast = r#"sigmaAllow = 35000 // psi
1988leg1 = 5 // inches
1989leg2 = 8 // inches
1990fn thickness() { return 0.56 }
1991
1992bracket = startSketchOn(XY)
1993  |> startProfile(at = [0,0])
1994  |> line(end = [0, leg1])
1995  |> line(end = [leg2, 0])
1996  |> line(end = [0, -thickness()])
1997  |> line(end = [-leg2 + thickness(), 0])
1998"#;
1999        parse_execute(ast).await.unwrap();
2000    }
2001
2002    #[tokio::test(flavor = "multi_thread")]
2003    async fn test_unary_operator_not_succeeds() {
2004        let ast = r#"
2005fn returnTrue() { return !false }
2006t = true
2007f = false
2008notTrue = !t
2009notFalse = !f
2010c = !!true
2011d = !returnTrue()
2012
2013assertIs(!false, error = "expected to pass")
2014
2015fn check(x) {
2016  assertIs(!x, error = "expected argument to be false")
2017  return true
2018}
2019check(x = false)
2020"#;
2021        let result = parse_execute(ast).await.unwrap();
2022        assert_eq!(
2023            false,
2024            mem_get_json(result.exec_state.stack(), result.mem_env, "notTrue")
2025                .as_bool()
2026                .unwrap()
2027        );
2028        assert_eq!(
2029            true,
2030            mem_get_json(result.exec_state.stack(), result.mem_env, "notFalse")
2031                .as_bool()
2032                .unwrap()
2033        );
2034        assert_eq!(
2035            true,
2036            mem_get_json(result.exec_state.stack(), result.mem_env, "c")
2037                .as_bool()
2038                .unwrap()
2039        );
2040        assert_eq!(
2041            false,
2042            mem_get_json(result.exec_state.stack(), result.mem_env, "d")
2043                .as_bool()
2044                .unwrap()
2045        );
2046    }
2047
2048    #[tokio::test(flavor = "multi_thread")]
2049    async fn test_unary_operator_not_on_non_bool_fails() {
2050        let code1 = r#"
2051// Yup, this is null.
2052myNull = 0 / 0
2053notNull = !myNull
2054"#;
2055        assert_eq!(
2056            parse_execute(code1).await.unwrap_err().message(),
2057            "Cannot apply unary operator ! to non-boolean value: a number",
2058        );
2059
2060        let code2 = "notZero = !0";
2061        assert_eq!(
2062            parse_execute(code2).await.unwrap_err().message(),
2063            "Cannot apply unary operator ! to non-boolean value: a number",
2064        );
2065
2066        let code3 = r#"
2067notEmptyString = !""
2068"#;
2069        assert_eq!(
2070            parse_execute(code3).await.unwrap_err().message(),
2071            "Cannot apply unary operator ! to non-boolean value: a string",
2072        );
2073
2074        let code4 = r#"
2075obj = { a = 1 }
2076notMember = !obj.a
2077"#;
2078        assert_eq!(
2079            parse_execute(code4).await.unwrap_err().message(),
2080            "Cannot apply unary operator ! to non-boolean value: a number",
2081        );
2082
2083        let code5 = "
2084a = []
2085notArray = !a";
2086        assert_eq!(
2087            parse_execute(code5).await.unwrap_err().message(),
2088            "Cannot apply unary operator ! to non-boolean value: an empty array",
2089        );
2090
2091        let code6 = "
2092x = {}
2093notObject = !x";
2094        assert_eq!(
2095            parse_execute(code6).await.unwrap_err().message(),
2096            "Cannot apply unary operator ! to non-boolean value: an object",
2097        );
2098
2099        let code7 = "
2100fn x() { return 1 }
2101notFunction = !x";
2102        let fn_err = parse_execute(code7).await.unwrap_err();
2103        // These are currently printed out as JSON objects, so we don't want to
2104        // check the full error.
2105        assert!(
2106            fn_err
2107                .message()
2108                .starts_with("Cannot apply unary operator ! to non-boolean value: "),
2109            "Actual error: {fn_err:?}"
2110        );
2111
2112        let code8 = "
2113myTagDeclarator = $myTag
2114notTagDeclarator = !myTagDeclarator";
2115        let tag_declarator_err = parse_execute(code8).await.unwrap_err();
2116        // These are currently printed out as JSON objects, so we don't want to
2117        // check the full error.
2118        assert!(
2119            tag_declarator_err
2120                .message()
2121                .starts_with("Cannot apply unary operator ! to non-boolean value: a tag declarator"),
2122            "Actual error: {tag_declarator_err:?}"
2123        );
2124
2125        let code9 = "
2126myTagDeclarator = $myTag
2127notTagIdentifier = !myTag";
2128        let tag_identifier_err = parse_execute(code9).await.unwrap_err();
2129        // These are currently printed out as JSON objects, so we don't want to
2130        // check the full error.
2131        assert!(
2132            tag_identifier_err
2133                .message()
2134                .starts_with("Cannot apply unary operator ! to non-boolean value: a tag identifier"),
2135            "Actual error: {tag_identifier_err:?}"
2136        );
2137
2138        let code10 = "notPipe = !(1 |> 2)";
2139        assert_eq!(
2140            // TODO: We don't currently parse this, but we should.  It should be
2141            // a runtime error instead.
2142            parse_execute(code10).await.unwrap_err(),
2143            KclError::new_syntax(KclErrorDetails::new(
2144                "Unexpected token: !".to_owned(),
2145                vec![SourceRange::new(10, 11, ModuleId::default())],
2146            ))
2147        );
2148
2149        let code11 = "
2150fn identity(x) { return x }
2151notPipeSub = 1 |> identity(!%))";
2152        assert_eq!(
2153            // TODO: We don't currently parse this, but we should.  It should be
2154            // a runtime error instead.
2155            parse_execute(code11).await.unwrap_err(),
2156            KclError::new_syntax(KclErrorDetails::new(
2157                "There was an unexpected `!`. Try removing it.".to_owned(),
2158                vec![SourceRange::new(56, 57, ModuleId::default())],
2159            ))
2160        );
2161
2162        // TODO: Add these tests when we support these types.
2163        // let notNan = !NaN
2164        // let notInfinity = !Infinity
2165    }
2166
2167    #[tokio::test(flavor = "multi_thread")]
2168    async fn test_start_sketch_on_invalid_kwargs() {
2169        let current_dir = std::env::current_dir().unwrap();
2170        let mut path = current_dir.join("tests/inputs/startSketchOn_0.kcl");
2171        let mut code = std::fs::read_to_string(&path).unwrap();
2172        assert_eq!(
2173            parse_execute(&code).await.unwrap_err().message(),
2174            "You cannot give both `face` and `normalToFace` params, you have to choose one or the other.".to_owned(),
2175        );
2176
2177        path = current_dir.join("tests/inputs/startSketchOn_1.kcl");
2178        code = std::fs::read_to_string(&path).unwrap();
2179
2180        assert_eq!(
2181            parse_execute(&code).await.unwrap_err().message(),
2182            "`alignAxis` is required if `normalToFace` is specified.".to_owned(),
2183        );
2184
2185        path = current_dir.join("tests/inputs/startSketchOn_2.kcl");
2186        code = std::fs::read_to_string(&path).unwrap();
2187
2188        assert_eq!(
2189            parse_execute(&code).await.unwrap_err().message(),
2190            "`normalToFace` is required if `alignAxis` is specified.".to_owned(),
2191        );
2192
2193        path = current_dir.join("tests/inputs/startSketchOn_3.kcl");
2194        code = std::fs::read_to_string(&path).unwrap();
2195
2196        assert_eq!(
2197            parse_execute(&code).await.unwrap_err().message(),
2198            "`normalToFace` is required if `alignAxis` is specified.".to_owned(),
2199        );
2200
2201        path = current_dir.join("tests/inputs/startSketchOn_4.kcl");
2202        code = std::fs::read_to_string(&path).unwrap();
2203
2204        assert_eq!(
2205            parse_execute(&code).await.unwrap_err().message(),
2206            "`normalToFace` is required if `normalOffset` is specified.".to_owned(),
2207        );
2208    }
2209
2210    #[tokio::test(flavor = "multi_thread")]
2211    async fn test_math_negative_variable_in_binary_expression() {
2212        let ast = r#"sigmaAllow = 35000 // psi
2213width = 1 // inch
2214
2215p = 150 // lbs
2216distance = 6 // inches
2217FOS = 2
2218
2219leg1 = 5 // inches
2220leg2 = 8 // inches
2221
2222thickness_squared = distance * p * FOS * 6 / sigmaAllow
2223thickness = 0.56 // inches. App does not support square root function yet
2224
2225bracket = startSketchOn(XY)
2226  |> startProfile(at = [0,0])
2227  |> line(end = [0, leg1])
2228  |> line(end = [leg2, 0])
2229  |> line(end = [0, -thickness])
2230  |> line(end = [-leg2 + thickness, 0])
2231"#;
2232        parse_execute(ast).await.unwrap();
2233    }
2234
2235    #[tokio::test(flavor = "multi_thread")]
2236    async fn test_execute_function_no_return() {
2237        let ast = r#"fn test(@origin) {
2238  origin
2239}
2240
2241test([0, 0])
2242"#;
2243        let result = parse_execute(ast).await;
2244        assert!(result.is_err());
2245        assert!(result.unwrap_err().to_string().contains("undefined"));
2246    }
2247
2248    #[tokio::test(flavor = "multi_thread")]
2249    async fn test_math_doubly_nested_parens() {
2250        let ast = r#"sigmaAllow = 35000 // psi
2251width = 4 // inch
2252p = 150 // Force on shelf - lbs
2253distance = 6 // inches
2254FOS = 2
2255leg1 = 5 // inches
2256leg2 = 8 // inches
2257thickness_squared = (distance * p * FOS * 6 / (sigmaAllow - width))
2258thickness = 0.32 // inches. App does not support square root function yet
2259bracket = startSketchOn(XY)
2260  |> startProfile(at = [0,0])
2261    |> line(end = [0, leg1])
2262  |> line(end = [leg2, 0])
2263  |> line(end = [0, -thickness])
2264  |> line(end = [-1 * leg2 + thickness, 0])
2265  |> line(end = [0, -1 * leg1 + thickness])
2266  |> close()
2267  |> extrude(length = width)
2268"#;
2269        parse_execute(ast).await.unwrap();
2270    }
2271
2272    #[tokio::test(flavor = "multi_thread")]
2273    async fn test_math_nested_parens_one_less() {
2274        let ast = r#" sigmaAllow = 35000 // psi
2275width = 4 // inch
2276p = 150 // Force on shelf - lbs
2277distance = 6 // inches
2278FOS = 2
2279leg1 = 5 // inches
2280leg2 = 8 // inches
2281thickness_squared = distance * p * FOS * 6 / (sigmaAllow - width)
2282thickness = 0.32 // inches. App does not support square root function yet
2283bracket = startSketchOn(XY)
2284  |> startProfile(at = [0,0])
2285    |> line(end = [0, leg1])
2286  |> line(end = [leg2, 0])
2287  |> line(end = [0, -thickness])
2288  |> line(end = [-1 * leg2 + thickness, 0])
2289  |> line(end = [0, -1 * leg1 + thickness])
2290  |> close()
2291  |> extrude(length = width)
2292"#;
2293        parse_execute(ast).await.unwrap();
2294    }
2295
2296    #[tokio::test(flavor = "multi_thread")]
2297    async fn test_fn_as_operand() {
2298        let ast = r#"fn f() { return 1 }
2299x = f()
2300y = x + 1
2301z = f() + 1
2302w = f() + f()
2303"#;
2304        parse_execute(ast).await.unwrap();
2305    }
2306
2307    #[tokio::test(flavor = "multi_thread")]
2308    async fn kcl_test_ids_stable_between_executions() {
2309        let code = r#"sketch001 = startSketchOn(XZ)
2310|> startProfile(at = [61.74, 206.13])
2311|> xLine(length = 305.11, tag = $seg01)
2312|> yLine(length = -291.85)
2313|> xLine(length = -segLen(seg01))
2314|> line(endAbsolute = [profileStartX(%), profileStartY(%)])
2315|> close()
2316|> extrude(length = 40.14)
2317|> shell(
2318    thickness = 3.14,
2319    faces = [seg01]
2320)
2321"#;
2322
2323        let ctx = crate::test_server::new_context(true, None).await.unwrap();
2324        let old_program = crate::Program::parse_no_errs(code).unwrap();
2325
2326        // Execute the program.
2327        if let Err(err) = ctx.run_with_caching(old_program).await {
2328            let report = err.into_miette_report_with_outputs(code).unwrap();
2329            let report = miette::Report::new(report);
2330            panic!("Error executing program: {report:?}");
2331        }
2332
2333        // Get the id_generator from the first execution.
2334        let id_generator = cache::read_old_ast().await.unwrap().main.exec_state.id_generator;
2335
2336        let code = r#"sketch001 = startSketchOn(XZ)
2337|> startProfile(at = [62.74, 206.13])
2338|> xLine(length = 305.11, tag = $seg01)
2339|> yLine(length = -291.85)
2340|> xLine(length = -segLen(seg01))
2341|> line(endAbsolute = [profileStartX(%), profileStartY(%)])
2342|> close()
2343|> extrude(length = 40.14)
2344|> shell(
2345    faces = [seg01],
2346    thickness = 3.14,
2347)
2348"#;
2349
2350        // Execute a slightly different program again.
2351        let program = crate::Program::parse_no_errs(code).unwrap();
2352        // Execute the program.
2353        ctx.run_with_caching(program).await.unwrap();
2354
2355        let new_id_generator = cache::read_old_ast().await.unwrap().main.exec_state.id_generator;
2356
2357        assert_eq!(id_generator, new_id_generator);
2358    }
2359
2360    #[tokio::test(flavor = "multi_thread")]
2361    async fn kcl_test_changing_a_setting_updates_the_cached_state() {
2362        let code = r#"sketch001 = startSketchOn(XZ)
2363|> startProfile(at = [61.74, 206.13])
2364|> xLine(length = 305.11, tag = $seg01)
2365|> yLine(length = -291.85)
2366|> xLine(length = -segLen(seg01))
2367|> line(endAbsolute = [profileStartX(%), profileStartY(%)])
2368|> close()
2369|> extrude(length = 40.14)
2370|> shell(
2371    thickness = 3.14,
2372    faces = [seg01]
2373)
2374"#;
2375
2376        let mut ctx = crate::test_server::new_context(true, None).await.unwrap();
2377        let old_program = crate::Program::parse_no_errs(code).unwrap();
2378
2379        // Execute the program.
2380        ctx.run_with_caching(old_program.clone()).await.unwrap();
2381
2382        let settings_state = cache::read_old_ast().await.unwrap().settings;
2383
2384        // Ensure the settings are as expected.
2385        assert_eq!(settings_state, ctx.settings);
2386
2387        // Change a setting.
2388        ctx.settings.highlight_edges = !ctx.settings.highlight_edges;
2389
2390        // Execute the program.
2391        ctx.run_with_caching(old_program.clone()).await.unwrap();
2392
2393        let settings_state = cache::read_old_ast().await.unwrap().settings;
2394
2395        // Ensure the settings are as expected.
2396        assert_eq!(settings_state, ctx.settings);
2397
2398        // Change a setting.
2399        ctx.settings.highlight_edges = !ctx.settings.highlight_edges;
2400
2401        // Execute the program.
2402        ctx.run_with_caching(old_program).await.unwrap();
2403
2404        let settings_state = cache::read_old_ast().await.unwrap().settings;
2405
2406        // Ensure the settings are as expected.
2407        assert_eq!(settings_state, ctx.settings);
2408
2409        ctx.close().await;
2410    }
2411
2412    #[tokio::test(flavor = "multi_thread")]
2413    async fn mock_after_not_mock() {
2414        let ctx = ExecutorContext::new_with_default_client().await.unwrap();
2415        let program = crate::Program::parse_no_errs("x = 2").unwrap();
2416        let result = ctx.run_with_caching(program).await.unwrap();
2417        assert_eq!(result.variables.get("x").unwrap().as_f64().unwrap(), 2.0);
2418
2419        let ctx2 = ExecutorContext::new_mock(None).await;
2420        let program2 = crate::Program::parse_no_errs("z = x + 1").unwrap();
2421        let result = ctx2.run_mock(&program2, true).await.unwrap();
2422        assert_eq!(result.variables.get("z").unwrap().as_f64().unwrap(), 3.0);
2423
2424        ctx.close().await;
2425        ctx2.close().await;
2426    }
2427
2428    #[cfg(feature = "artifact-graph")]
2429    #[tokio::test(flavor = "multi_thread")]
2430    async fn mock_has_stable_ids() {
2431        let ctx = ExecutorContext::new_mock(None).await;
2432        let code = "sk = startSketchOn(XY)
2433        |> startProfile(at = [0, 0])";
2434        let program = crate::Program::parse_no_errs(code).unwrap();
2435        let result = ctx.run_mock(&program, false).await.unwrap();
2436        let ids = result.artifact_graph.iter().map(|(k, _)| *k).collect::<Vec<_>>();
2437        assert!(!ids.is_empty(), "IDs should not be empty");
2438
2439        let ctx2 = ExecutorContext::new_mock(None).await;
2440        let program2 = crate::Program::parse_no_errs(code).unwrap();
2441        let result = ctx2.run_mock(&program2, false).await.unwrap();
2442        let ids2 = result.artifact_graph.iter().map(|(k, _)| *k).collect::<Vec<_>>();
2443
2444        assert_eq!(ids, ids2, "Generated IDs should match");
2445    }
2446
2447    #[cfg(feature = "artifact-graph")]
2448    #[tokio::test(flavor = "multi_thread")]
2449    async fn sim_sketch_mode_real_mock_real() {
2450        let ctx = ExecutorContext::new_with_default_client().await.unwrap();
2451        let code = r#"sketch001 = startSketchOn(XY)
2452profile001 = startProfile(sketch001, at = [0, 0])
2453  |> line(end = [10, 0])
2454  |> line(end = [0, 10])
2455  |> line(end = [-10, 0])
2456  |> line(end = [0, -10])
2457  |> close()
2458"#;
2459        let program = crate::Program::parse_no_errs(code).unwrap();
2460        let result = ctx.run_with_caching(program).await.unwrap();
2461        assert_eq!(result.operations.len(), 1);
2462
2463        let mock_ctx = ExecutorContext::new_mock(None).await;
2464        let mock_program = crate::Program::parse_no_errs(code).unwrap();
2465        let mock_result = mock_ctx.run_mock(&mock_program, true).await.unwrap();
2466        assert_eq!(mock_result.operations.len(), 1);
2467
2468        let code2 = code.to_owned()
2469            + r#"
2470extrude001 = extrude(profile001, length = 10)
2471"#;
2472        let program2 = crate::Program::parse_no_errs(&code2).unwrap();
2473        let result = ctx.run_with_caching(program2).await.unwrap();
2474        assert_eq!(result.operations.len(), 2);
2475
2476        ctx.close().await;
2477        mock_ctx.close().await;
2478    }
2479
2480    #[tokio::test(flavor = "multi_thread")]
2481    async fn read_tag_version() {
2482        let ast = r#"fn bar(@t) {
2483  return startSketchOn(XY)
2484    |> startProfile(at = [0,0])
2485    |> angledLine(
2486        angle = -60,
2487        length = segLen(t),
2488    )
2489    |> line(end = [0, 0])
2490    |> close()
2491}
2492
2493sketch = startSketchOn(XY)
2494  |> startProfile(at = [0,0])
2495  |> line(end = [0, 10])
2496  |> line(end = [10, 0], tag = $tag0)
2497  |> line(end = [0, 0])
2498
2499fn foo() {
2500  // tag0 tags an edge
2501  return bar(tag0)
2502}
2503
2504solid = sketch |> extrude(length = 10)
2505// tag0 tags a face
2506sketch2 = startSketchOn(solid, face = tag0)
2507  |> startProfile(at = [0,0])
2508  |> line(end = [0, 1])
2509  |> line(end = [1, 0])
2510  |> line(end = [0, 0])
2511
2512foo() |> extrude(length = 1)
2513"#;
2514        parse_execute(ast).await.unwrap();
2515    }
2516
2517    #[tokio::test(flavor = "multi_thread")]
2518    async fn experimental() {
2519        let code = r#"
2520startSketchOn(XY)
2521  |> startProfile(at = [0, 0], tag = $start)
2522  |> elliptic(center = [0, 0], angleStart = segAng(start), angleEnd = 160deg, majorRadius = 2, minorRadius = 3)
2523"#;
2524        let result = parse_execute(code).await.unwrap();
2525        let errors = result.exec_state.errors();
2526        assert_eq!(errors.len(), 1);
2527        assert_eq!(errors[0].severity, Severity::Error);
2528        let msg = &errors[0].message;
2529        assert!(msg.contains("experimental"), "found {msg}");
2530
2531        let code = r#"@settings(experimentalFeatures = allow)
2532startSketchOn(XY)
2533  |> startProfile(at = [0, 0], tag = $start)
2534  |> elliptic(center = [0, 0], angleStart = segAng(start), angleEnd = 160deg, majorRadius = 2, minorRadius = 3)
2535"#;
2536        let result = parse_execute(code).await.unwrap();
2537        let errors = result.exec_state.errors();
2538        assert!(errors.is_empty());
2539
2540        let code = r#"@settings(experimentalFeatures = warn)
2541startSketchOn(XY)
2542  |> startProfile(at = [0, 0], tag = $start)
2543  |> elliptic(center = [0, 0], angleStart = segAng(start), angleEnd = 160deg, majorRadius = 2, minorRadius = 3)
2544"#;
2545        let result = parse_execute(code).await.unwrap();
2546        let errors = result.exec_state.errors();
2547        assert_eq!(errors.len(), 1);
2548        assert_eq!(errors[0].severity, Severity::Warning);
2549        let msg = &errors[0].message;
2550        assert!(msg.contains("experimental"), "found {msg}");
2551
2552        let code = r#"@settings(experimentalFeatures = deny)
2553startSketchOn(XY)
2554  |> startProfile(at = [0, 0], tag = $start)
2555  |> elliptic(center = [0, 0], angleStart = segAng(start), angleEnd = 160deg, majorRadius = 2, minorRadius = 3)
2556"#;
2557        let result = parse_execute(code).await.unwrap();
2558        let errors = result.exec_state.errors();
2559        assert_eq!(errors.len(), 1);
2560        assert_eq!(errors[0].severity, Severity::Error);
2561        let msg = &errors[0].message;
2562        assert!(msg.contains("experimental"), "found {msg}");
2563
2564        let code = r#"@settings(experimentalFeatures = foo)
2565startSketchOn(XY)
2566  |> startProfile(at = [0, 0], tag = $start)
2567  |> elliptic(center = [0, 0], angleStart = segAng(start), angleEnd = 160deg, majorRadius = 2, minorRadius = 3)
2568"#;
2569        parse_execute(code).await.unwrap_err();
2570    }
2571}