1use 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::{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
63enum StatementKind<'a> {
64 Declaration { name: &'a str },
65 Expression,
66}
67
68#[derive(Debug, Clone, Serialize, ts_rs::TS, PartialEq)]
70#[ts(export)]
71#[serde(rename_all = "camelCase")]
72pub struct ExecOutcome {
73 pub variables: IndexMap<String, KclValue>,
75 #[cfg(feature = "artifact-graph")]
78 pub operations: Vec<Operation>,
79 #[cfg(feature = "artifact-graph")]
81 pub artifact_graph: ArtifactGraph,
82 pub errors: Vec<CompilationError>,
84 pub filenames: IndexMap<ModuleId, ModulePath>,
86 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 #[serde(skip)]
110 pub info: Vec<(usize, TagEngineInfo)>,
111 #[serde(skip)]
112 pub meta: Vec<Metadata>,
113}
114
115impl TagIdentifier {
116 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 pub fn get_cur_info(&self) -> Option<&TagEngineInfo> {
129 self.info.last().map(|i| &i.1)
130 }
131
132 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 *e > *oe {
139 continue;
140 }
141 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#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
192#[ts(export)]
193#[serde(tag = "type", rename_all = "camelCase")]
194pub struct TagEngineInfo {
195 pub id: uuid::Uuid,
197 pub sketch: uuid::Uuid,
199 pub path: Option<Path>,
201 pub surface: Option<ExtrudeSurface>,
203}
204
205#[derive(Debug, Copy, Clone, Deserialize, Serialize, PartialEq)]
206pub enum BodyType {
207 Root,
208 Block,
209}
210
211#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, Eq, Copy)]
213#[ts(export)]
214#[serde(rename_all = "camelCase")]
215pub struct Metadata {
216 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#[derive(PartialEq, Debug, Default, Clone)]
250pub enum ContextType {
251 #[default]
253 Live,
254
255 Mock,
259
260 MockCustomForwarded,
262}
263
264#[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#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS)]
277#[ts(export)]
278pub struct ExecutorSettings {
279 pub highlight_edges: bool,
281 pub enable_ssao: bool,
283 pub show_grid: bool,
285 pub replay: Option<String>,
288 pub project_directory: Option<TypedPath>,
291 pub current_file: Option<TypedPath>,
294 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 pub fn with_current_file(&mut self, current_file: TypedPath) {
369 if current_file.extension() == Some("kcl") {
371 self.current_file = Some(current_file.clone());
372 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.clone());
380 }
381 }
382}
383
384impl ExecutorContext {
385 #[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 #[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 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 #[cfg(not(target_arch = "wasm32"))]
483 pub async fn new_with_default_client() -> Result<Self> {
484 let ctx = Self::new_with_client(Default::default(), None, None).await?;
486 Ok(ctx)
487 }
488
489 #[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 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 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 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 exec_state.mut_stack().push_new_env_for_scope();
580
581 let result = self.inner_run(program, &mut exec_state, true).await?;
582
583 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 (program, exec_state, result) = match cache::read_old_ast().await {
606 Some(mut cached_state) => {
607 let old = CacheInformation {
608 ast: &cached_state.main.ast,
609 settings: &cached_state.settings,
610 };
611 let new = CacheInformation {
612 ast: &program.ast,
613 settings: &self.settings,
614 };
615
616 let (clear_scene, program, import_check_info) = match cache::get_changed_program(old, new).await {
618 CacheResult::ReExecute {
619 clear_scene,
620 reapply_settings,
621 program: changed_program,
622 } => {
623 if reapply_settings
624 && self
625 .engine
626 .reapply_settings(
627 &self.settings,
628 Default::default(),
629 &mut cached_state.main.exec_state.id_generator,
630 grid_scale,
631 )
632 .await
633 .is_err()
634 {
635 (true, program, None)
636 } else {
637 (
638 clear_scene,
639 crate::Program {
640 ast: changed_program,
641 original_file_contents: program.original_file_contents,
642 },
643 None,
644 )
645 }
646 }
647 CacheResult::CheckImportsOnly {
648 reapply_settings,
649 ast: changed_program,
650 } => {
651 if reapply_settings
652 && self
653 .engine
654 .reapply_settings(
655 &self.settings,
656 Default::default(),
657 &mut cached_state.main.exec_state.id_generator,
658 grid_scale,
659 )
660 .await
661 .is_err()
662 {
663 (true, program, None)
664 } else {
665 let mut new_exec_state = ExecState::new(self);
667 let (new_universe, new_universe_map) =
668 self.get_universe(&program, &mut new_exec_state).await?;
669
670 let clear_scene = new_universe.values().any(|value| {
671 let id = value.1;
672 match (
673 cached_state.exec_state.get_source(id),
674 new_exec_state.global.get_source(id),
675 ) {
676 (Some(s0), Some(s1)) => s0.source != s1.source,
677 _ => false,
678 }
679 });
680
681 if !clear_scene {
682 return Ok(cached_state.into_exec_outcome(self).await);
684 }
685
686 (
687 true,
688 crate::Program {
689 ast: changed_program,
690 original_file_contents: program.original_file_contents,
691 },
692 Some((new_universe, new_universe_map, new_exec_state)),
693 )
694 }
695 }
696 CacheResult::NoAction(true) => {
697 if self
698 .engine
699 .reapply_settings(
700 &self.settings,
701 Default::default(),
702 &mut cached_state.main.exec_state.id_generator,
703 grid_scale,
704 )
705 .await
706 .is_ok()
707 {
708 cache::write_old_ast(GlobalState::with_settings(
710 cached_state.clone(),
711 self.settings.clone(),
712 ))
713 .await;
714
715 return Ok(cached_state.into_exec_outcome(self).await);
716 }
717 (true, program, None)
718 }
719 CacheResult::NoAction(false) => {
720 return Ok(cached_state.into_exec_outcome(self).await);
721 }
722 };
723
724 let (exec_state, result) = match import_check_info {
725 Some((new_universe, new_universe_map, mut new_exec_state)) => {
726 self.send_clear_scene(&mut new_exec_state, Default::default())
728 .await
729 .map_err(KclErrorWithOutputs::no_outputs)?;
730
731 let result = self
732 .run_concurrent(
733 &program,
734 &mut new_exec_state,
735 Some((new_universe, new_universe_map)),
736 false,
737 )
738 .await;
739
740 (new_exec_state, result)
741 }
742 None if clear_scene => {
743 let mut exec_state = cached_state.reconstitute_exec_state();
745 exec_state.reset(self);
746
747 self.send_clear_scene(&mut exec_state, Default::default())
748 .await
749 .map_err(KclErrorWithOutputs::no_outputs)?;
750
751 let result = self.run_concurrent(&program, &mut exec_state, None, false).await;
752
753 (exec_state, result)
754 }
755 None => {
756 let mut exec_state = cached_state.reconstitute_exec_state();
757 exec_state.mut_stack().restore_env(cached_state.main.result_env);
758
759 let result = self.run_concurrent(&program, &mut exec_state, None, true).await;
760
761 (exec_state, result)
762 }
763 };
764
765 (program, exec_state, result)
766 }
767 None => {
768 let mut exec_state = ExecState::new(self);
769 self.send_clear_scene(&mut exec_state, Default::default())
770 .await
771 .map_err(KclErrorWithOutputs::no_outputs)?;
772
773 let result = self.run_concurrent(&program, &mut exec_state, None, false).await;
774
775 (program, exec_state, result)
776 }
777 };
778
779 if result.is_err() {
780 cache::bust_cache().await;
781 }
782
783 let result = result?;
785
786 cache::write_old_ast(GlobalState::new(
788 exec_state.clone(),
789 self.settings.clone(),
790 program.ast,
791 result.0,
792 ))
793 .await;
794
795 let outcome = exec_state.into_exec_outcome(result.0, self).await;
796 Ok(outcome)
797 }
798
799 pub async fn run(
803 &self,
804 program: &crate::Program,
805 exec_state: &mut ExecState,
806 ) -> Result<(EnvironmentRef, Option<ModelingSessionData>), KclErrorWithOutputs> {
807 self.run_concurrent(program, exec_state, None, false).await
808 }
809
810 pub async fn run_concurrent(
815 &self,
816 program: &crate::Program,
817 exec_state: &mut ExecState,
818 universe_info: Option<(Universe, UniverseMap)>,
819 preserve_mem: bool,
820 ) -> Result<(EnvironmentRef, Option<ModelingSessionData>), KclErrorWithOutputs> {
821 let (universe, universe_map) = if let Some((universe, universe_map)) = universe_info {
824 (universe, universe_map)
825 } else {
826 self.get_universe(program, exec_state).await?
827 };
828
829 let default_planes = self.engine.get_default_planes().read().await.clone();
830
831 self.eval_prelude(exec_state, SourceRange::synthetic())
833 .await
834 .map_err(KclErrorWithOutputs::no_outputs)?;
835
836 for modules in import_graph::import_graph(&universe, self)
837 .map_err(|err| exec_state.error_with_outputs(err, None, default_planes.clone()))?
838 .into_iter()
839 {
840 #[cfg(not(target_arch = "wasm32"))]
841 let mut set = tokio::task::JoinSet::new();
842
843 #[allow(clippy::type_complexity)]
844 let (results_tx, mut results_rx): (
845 tokio::sync::mpsc::Sender<(ModuleId, ModulePath, Result<ModuleRepr, KclError>)>,
846 tokio::sync::mpsc::Receiver<_>,
847 ) = tokio::sync::mpsc::channel(1);
848
849 for module in modules {
850 let Some((import_stmt, module_id, module_path, repr)) = universe.get(&module) else {
851 return Err(KclErrorWithOutputs::no_outputs(KclError::new_internal(
852 KclErrorDetails::new(format!("Module {module} not found in universe"), Default::default()),
853 )));
854 };
855 let module_id = *module_id;
856 let module_path = module_path.clone();
857 let source_range = SourceRange::from(import_stmt);
858 let module_exec_state = exec_state.clone();
860
861 self.add_import_module_ops(
862 exec_state,
863 program,
864 module_id,
865 &module_path,
866 source_range,
867 &universe_map,
868 );
869
870 let repr = repr.clone();
871 let exec_ctxt = self.clone();
872 let results_tx = results_tx.clone();
873
874 let exec_module = async |exec_ctxt: &ExecutorContext,
875 repr: &ModuleRepr,
876 module_id: ModuleId,
877 module_path: &ModulePath,
878 exec_state: &mut ExecState,
879 source_range: SourceRange|
880 -> Result<ModuleRepr, KclError> {
881 match repr {
882 ModuleRepr::Kcl(program, _) => {
883 let result = exec_ctxt
884 .exec_module_from_ast(program, module_id, module_path, exec_state, source_range, false)
885 .await;
886
887 result.map(|val| ModuleRepr::Kcl(program.clone(), Some(val)))
888 }
889 ModuleRepr::Foreign(geom, _) => {
890 let result = crate::execution::import::send_to_engine(geom.clone(), exec_state, exec_ctxt)
891 .await
892 .map(|geom| Some(KclValue::ImportedGeometry(geom)));
893
894 result.map(|val| {
895 ModuleRepr::Foreign(geom.clone(), Some((val, exec_state.mod_local.artifacts.clone())))
896 })
897 }
898 ModuleRepr::Dummy | ModuleRepr::Root => Err(KclError::new_internal(KclErrorDetails::new(
899 format!("Module {module_path} not found in universe"),
900 vec![source_range],
901 ))),
902 }
903 };
904
905 #[cfg(target_arch = "wasm32")]
906 {
907 wasm_bindgen_futures::spawn_local(async move {
908 let mut exec_state = module_exec_state;
909 let exec_ctxt = exec_ctxt;
910
911 let result = exec_module(
912 &exec_ctxt,
913 &repr,
914 module_id,
915 &module_path,
916 &mut exec_state,
917 source_range,
918 )
919 .await;
920
921 results_tx
922 .send((module_id, module_path, result))
923 .await
924 .unwrap_or_default();
925 });
926 }
927 #[cfg(not(target_arch = "wasm32"))]
928 {
929 set.spawn(async move {
930 let mut exec_state = module_exec_state;
931 let exec_ctxt = exec_ctxt;
932
933 let result = exec_module(
934 &exec_ctxt,
935 &repr,
936 module_id,
937 &module_path,
938 &mut exec_state,
939 source_range,
940 )
941 .await;
942
943 results_tx
944 .send((module_id, module_path, result))
945 .await
946 .unwrap_or_default();
947 });
948 }
949 }
950
951 drop(results_tx);
952
953 while let Some((module_id, _, result)) = results_rx.recv().await {
954 match result {
955 Ok(new_repr) => {
956 let mut repr = exec_state.global.module_infos[&module_id].take_repr();
957
958 match &mut repr {
959 ModuleRepr::Kcl(_, cache) => {
960 let ModuleRepr::Kcl(_, session_data) = new_repr else {
961 unreachable!();
962 };
963 *cache = session_data;
964 }
965 ModuleRepr::Foreign(_, cache) => {
966 let ModuleRepr::Foreign(_, session_data) = new_repr else {
967 unreachable!();
968 };
969 *cache = session_data;
970 }
971 ModuleRepr::Dummy | ModuleRepr::Root => unreachable!(),
972 }
973
974 exec_state.global.module_infos[&module_id].restore_repr(repr);
975 }
976 Err(e) => {
977 return Err(exec_state.error_with_outputs(e, None, default_planes));
978 }
979 }
980 }
981 }
982
983 exec_state
987 .global
988 .root_module_artifacts
989 .extend(std::mem::take(&mut exec_state.mod_local.artifacts));
990
991 self.inner_run(program, exec_state, preserve_mem).await
992 }
993
994 async fn get_universe(
997 &self,
998 program: &crate::Program,
999 exec_state: &mut ExecState,
1000 ) -> Result<(Universe, UniverseMap), KclErrorWithOutputs> {
1001 exec_state.add_root_module_contents(program);
1002
1003 let mut universe = std::collections::HashMap::new();
1004
1005 let default_planes = self.engine.get_default_planes().read().await.clone();
1006
1007 let root_imports = import_graph::import_universe(
1008 self,
1009 &ModulePath::Main,
1010 &ModuleRepr::Kcl(program.ast.clone(), None),
1011 &mut universe,
1012 exec_state,
1013 )
1014 .await
1015 .map_err(|err| exec_state.error_with_outputs(err, None, default_planes))?;
1016
1017 Ok((universe, root_imports))
1018 }
1019
1020 #[cfg(not(feature = "artifact-graph"))]
1021 fn add_import_module_ops(
1022 &self,
1023 _exec_state: &mut ExecState,
1024 _program: &crate::Program,
1025 _module_id: ModuleId,
1026 _module_path: &ModulePath,
1027 _source_range: SourceRange,
1028 _universe_map: &UniverseMap,
1029 ) {
1030 }
1031
1032 #[cfg(feature = "artifact-graph")]
1033 fn add_import_module_ops(
1034 &self,
1035 exec_state: &mut ExecState,
1036 program: &crate::Program,
1037 module_id: ModuleId,
1038 module_path: &ModulePath,
1039 source_range: SourceRange,
1040 universe_map: &UniverseMap,
1041 ) {
1042 match module_path {
1043 ModulePath::Main => {
1044 }
1046 ModulePath::Local { value, .. } => {
1047 if universe_map.contains_key(value) {
1050 use crate::NodePath;
1051
1052 let node_path = if source_range.is_top_level_module() {
1053 let cached_body_items = exec_state.global.artifacts.cached_body_items();
1054 NodePath::from_range(&program.ast, cached_body_items, source_range).unwrap_or_default()
1055 } else {
1056 NodePath::placeholder()
1059 };
1060
1061 exec_state.push_op(Operation::GroupBegin {
1062 group: Group::ModuleInstance {
1063 name: value.file_name().unwrap_or_default(),
1064 module_id,
1065 },
1066 node_path,
1067 source_range,
1068 });
1069 exec_state.push_op(Operation::GroupEnd);
1073 }
1074 }
1075 ModulePath::Std { .. } => {
1076 }
1078 }
1079 }
1080
1081 async fn inner_run(
1084 &self,
1085 program: &crate::Program,
1086 exec_state: &mut ExecState,
1087 preserve_mem: bool,
1088 ) -> Result<(EnvironmentRef, Option<ModelingSessionData>), KclErrorWithOutputs> {
1089 let _stats = crate::log::LogPerfStats::new("Interpretation");
1090
1091 let grid_scale = if self.settings.fixed_size_grid {
1093 GridScaleBehavior::Fixed(program.meta_settings().ok().flatten().map(|s| s.default_length_units))
1094 } else {
1095 GridScaleBehavior::ScaleWithZoom
1096 };
1097 self.engine
1098 .reapply_settings(
1099 &self.settings,
1100 Default::default(),
1101 exec_state.id_generator(),
1102 grid_scale,
1103 )
1104 .await
1105 .map_err(KclErrorWithOutputs::no_outputs)?;
1106
1107 let default_planes = self.engine.get_default_planes().read().await.clone();
1108 let result = self
1109 .execute_and_build_graph(&program.ast, exec_state, preserve_mem)
1110 .await;
1111
1112 crate::log::log(format!(
1113 "Post interpretation KCL memory stats: {:#?}",
1114 exec_state.stack().memory.stats
1115 ));
1116 crate::log::log(format!("Engine stats: {:?}", self.engine.stats()));
1117
1118 let env_ref = result.map_err(|(err, env_ref)| exec_state.error_with_outputs(err, env_ref, default_planes))?;
1119
1120 if !self.is_mock() {
1121 let mut mem = exec_state.stack().deep_clone();
1122 mem.restore_env(env_ref);
1123 cache::write_old_memory((mem, exec_state.global.module_infos.clone())).await;
1124 }
1125 let session_data = self.engine.get_session_data().await;
1126
1127 Ok((env_ref, session_data))
1128 }
1129
1130 async fn execute_and_build_graph(
1133 &self,
1134 program: NodeRef<'_, crate::parsing::ast::types::Program>,
1135 exec_state: &mut ExecState,
1136 preserve_mem: bool,
1137 ) -> Result<EnvironmentRef, (KclError, Option<EnvironmentRef>)> {
1138 #[cfg(feature = "artifact-graph")]
1144 let start_op = exec_state.global.root_module_artifacts.operations.len();
1145
1146 self.eval_prelude(exec_state, SourceRange::from(program).start_as_range())
1147 .await
1148 .map_err(|e| (e, None))?;
1149
1150 let exec_result = self
1151 .exec_module_body(
1152 program,
1153 exec_state,
1154 preserve_mem,
1155 ModuleId::default(),
1156 &ModulePath::Main,
1157 )
1158 .await
1159 .map(|(_, env_ref, _, module_artifacts)| {
1160 exec_state.global.root_module_artifacts.extend(module_artifacts);
1163 env_ref
1164 })
1165 .map_err(|(err, env_ref, module_artifacts)| {
1166 if let Some(module_artifacts) = module_artifacts {
1167 exec_state.global.root_module_artifacts.extend(module_artifacts);
1170 }
1171 (err, env_ref)
1172 });
1173
1174 #[cfg(feature = "artifact-graph")]
1175 {
1176 let cached_body_items = exec_state.global.artifacts.cached_body_items();
1178 for op in exec_state
1179 .global
1180 .root_module_artifacts
1181 .operations
1182 .iter_mut()
1183 .skip(start_op)
1184 {
1185 op.fill_node_paths(program, cached_body_items);
1186 }
1187 for module in exec_state.global.module_infos.values_mut() {
1188 if let ModuleRepr::Kcl(_, Some((_, _, _, module_artifacts))) = &mut module.repr {
1189 for op in &mut module_artifacts.operations {
1190 op.fill_node_paths(program, cached_body_items);
1191 }
1192 }
1193 }
1194 }
1195
1196 self.engine.ensure_async_commands_completed().await.map_err(|e| {
1198 match &exec_result {
1199 Ok(env_ref) => (e, Some(*env_ref)),
1200 Err((exec_err, env_ref)) => (exec_err.clone(), *env_ref),
1202 }
1203 })?;
1204
1205 self.engine.clear_queues().await;
1208
1209 match exec_state.build_artifact_graph(&self.engine, program).await {
1210 Ok(_) => exec_result,
1211 Err(err) => exec_result.and_then(|env_ref| Err((err, Some(env_ref)))),
1212 }
1213 }
1214
1215 async fn eval_prelude(&self, exec_state: &mut ExecState, source_range: SourceRange) -> Result<(), KclError> {
1219 if exec_state.stack().memory.requires_std() {
1220 #[cfg(feature = "artifact-graph")]
1221 let initial_ops = exec_state.mod_local.artifacts.operations.len();
1222
1223 let path = vec!["std".to_owned(), "prelude".to_owned()];
1224 let resolved_path = ModulePath::from_std_import_path(&path)?;
1225 let id = self
1226 .open_module(&ImportPath::Std { path }, &[], &resolved_path, exec_state, source_range)
1227 .await?;
1228 let (module_memory, _) = self.exec_module_for_items(id, exec_state, source_range).await?;
1229
1230 exec_state.mut_stack().memory.set_std(module_memory);
1231
1232 #[cfg(feature = "artifact-graph")]
1238 exec_state.mod_local.artifacts.operations.truncate(initial_ops);
1239 }
1240
1241 Ok(())
1242 }
1243
1244 pub async fn prepare_snapshot(&self) -> std::result::Result<TakeSnapshot, ExecError> {
1246 self.engine
1248 .send_modeling_cmd(
1249 uuid::Uuid::new_v4(),
1250 crate::execution::SourceRange::default(),
1251 &ModelingCmd::from(mcmd::ZoomToFit {
1252 object_ids: Default::default(),
1253 animated: false,
1254 padding: 0.1,
1255 }),
1256 )
1257 .await
1258 .map_err(KclErrorWithOutputs::no_outputs)?;
1259
1260 let resp = self
1262 .engine
1263 .send_modeling_cmd(
1264 uuid::Uuid::new_v4(),
1265 crate::execution::SourceRange::default(),
1266 &ModelingCmd::from(mcmd::TakeSnapshot {
1267 format: ImageFormat::Png,
1268 }),
1269 )
1270 .await
1271 .map_err(KclErrorWithOutputs::no_outputs)?;
1272
1273 let OkWebSocketResponseData::Modeling {
1274 modeling_response: OkModelingCmdResponse::TakeSnapshot(contents),
1275 } = resp
1276 else {
1277 return Err(ExecError::BadPng(format!(
1278 "Instead of a TakeSnapshot response, the engine returned {resp:?}"
1279 )));
1280 };
1281 Ok(contents)
1282 }
1283
1284 pub async fn export(
1286 &self,
1287 format: kittycad_modeling_cmds::format::OutputFormat3d,
1288 ) -> Result<Vec<kittycad_modeling_cmds::websocket::RawFile>, KclError> {
1289 let resp = self
1290 .engine
1291 .send_modeling_cmd(
1292 uuid::Uuid::new_v4(),
1293 crate::SourceRange::default(),
1294 &kittycad_modeling_cmds::ModelingCmd::Export(kittycad_modeling_cmds::Export {
1295 entity_ids: vec![],
1296 format,
1297 }),
1298 )
1299 .await?;
1300
1301 let kittycad_modeling_cmds::websocket::OkWebSocketResponseData::Export { files } = resp else {
1302 return Err(KclError::new_internal(crate::errors::KclErrorDetails::new(
1303 format!("Expected Export response, got {resp:?}",),
1304 vec![SourceRange::default()],
1305 )));
1306 };
1307
1308 Ok(files)
1309 }
1310
1311 pub async fn export_step(
1313 &self,
1314 deterministic_time: bool,
1315 ) -> Result<Vec<kittycad_modeling_cmds::websocket::RawFile>, KclError> {
1316 let files = self
1317 .export(kittycad_modeling_cmds::format::OutputFormat3d::Step(
1318 kittycad_modeling_cmds::format::step::export::Options {
1319 coords: *kittycad_modeling_cmds::coord::KITTYCAD,
1320 created: if deterministic_time {
1321 Some("2021-01-01T00:00:00Z".parse().map_err(|e| {
1322 KclError::new_internal(crate::errors::KclErrorDetails::new(
1323 format!("Failed to parse date: {e}"),
1324 vec![SourceRange::default()],
1325 ))
1326 })?)
1327 } else {
1328 None
1329 },
1330 },
1331 ))
1332 .await?;
1333
1334 Ok(files)
1335 }
1336
1337 pub async fn close(&self) {
1338 self.engine.close().await;
1339 }
1340}
1341
1342#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, Ord, PartialOrd, Hash, ts_rs::TS)]
1343pub struct ArtifactId(Uuid);
1344
1345impl ArtifactId {
1346 pub fn new(uuid: Uuid) -> Self {
1347 Self(uuid)
1348 }
1349}
1350
1351impl From<Uuid> for ArtifactId {
1352 fn from(uuid: Uuid) -> Self {
1353 Self::new(uuid)
1354 }
1355}
1356
1357impl From<&Uuid> for ArtifactId {
1358 fn from(uuid: &Uuid) -> Self {
1359 Self::new(*uuid)
1360 }
1361}
1362
1363impl From<ArtifactId> for Uuid {
1364 fn from(id: ArtifactId) -> Self {
1365 id.0
1366 }
1367}
1368
1369impl From<&ArtifactId> for Uuid {
1370 fn from(id: &ArtifactId) -> Self {
1371 id.0
1372 }
1373}
1374
1375impl From<ModelingCmdId> for ArtifactId {
1376 fn from(id: ModelingCmdId) -> Self {
1377 Self::new(*id.as_ref())
1378 }
1379}
1380
1381impl From<&ModelingCmdId> for ArtifactId {
1382 fn from(id: &ModelingCmdId) -> Self {
1383 Self::new(*id.as_ref())
1384 }
1385}
1386
1387#[cfg(test)]
1388pub(crate) async fn parse_execute(code: &str) -> Result<ExecTestResults, KclError> {
1389 parse_execute_with_project_dir(code, None).await
1390}
1391
1392#[cfg(test)]
1393pub(crate) async fn parse_execute_with_project_dir(
1394 code: &str,
1395 project_directory: Option<TypedPath>,
1396) -> Result<ExecTestResults, KclError> {
1397 let program = crate::Program::parse_no_errs(code)?;
1398
1399 let exec_ctxt = ExecutorContext {
1400 engine: Arc::new(Box::new(crate::engine::conn_mock::EngineConnection::new().map_err(
1401 |err| {
1402 KclError::new_internal(crate::errors::KclErrorDetails::new(
1403 format!("Failed to create mock engine connection: {err}"),
1404 vec![SourceRange::default()],
1405 ))
1406 },
1407 )?)),
1408 fs: Arc::new(crate::fs::FileManager::new()),
1409 settings: ExecutorSettings {
1410 project_directory,
1411 ..Default::default()
1412 },
1413 context_type: ContextType::Mock,
1414 };
1415 let mut exec_state = ExecState::new(&exec_ctxt);
1416 let result = exec_ctxt.run(&program, &mut exec_state).await?;
1417
1418 Ok(ExecTestResults {
1419 program,
1420 mem_env: result.0,
1421 exec_ctxt,
1422 exec_state,
1423 })
1424}
1425
1426#[cfg(test)]
1427#[derive(Debug)]
1428pub(crate) struct ExecTestResults {
1429 program: crate::Program,
1430 mem_env: EnvironmentRef,
1431 exec_ctxt: ExecutorContext,
1432 exec_state: ExecState,
1433}
1434
1435#[cfg(test)]
1436mod tests {
1437 use pretty_assertions::assert_eq;
1438
1439 use super::*;
1440 use crate::{
1441 ModuleId,
1442 errors::{KclErrorDetails, Severity},
1443 exec::NumericType,
1444 execution::{memory::Stack, types::RuntimeType},
1445 };
1446
1447 #[track_caller]
1449 fn mem_get_json(memory: &Stack, env: EnvironmentRef, name: &str) -> KclValue {
1450 memory.memory.get_from_unchecked(name, env).unwrap().to_owned()
1451 }
1452
1453 #[tokio::test(flavor = "multi_thread")]
1454 async fn test_execute_warn() {
1455 let text = "@blah";
1456 let result = parse_execute(text).await.unwrap();
1457 let errs = result.exec_state.errors();
1458 assert_eq!(errs.len(), 1);
1459 assert_eq!(errs[0].severity, crate::errors::Severity::Warning);
1460 assert!(
1461 errs[0].message.contains("Unknown annotation"),
1462 "unexpected warning message: {}",
1463 errs[0].message
1464 );
1465 }
1466
1467 #[tokio::test(flavor = "multi_thread")]
1468 async fn test_execute_fn_definitions() {
1469 let ast = r#"fn def(@x) {
1470 return x
1471}
1472fn ghi(@x) {
1473 return x
1474}
1475fn jkl(@x) {
1476 return x
1477}
1478fn hmm(@x) {
1479 return x
1480}
1481
1482yo = 5 + 6
1483
1484abc = 3
1485identifierGuy = 5
1486part001 = startSketchOn(XY)
1487|> startProfile(at = [-1.2, 4.83])
1488|> line(end = [2.8, 0])
1489|> angledLine(angle = 100 + 100, length = 3.01)
1490|> angledLine(angle = abc, length = 3.02)
1491|> angledLine(angle = def(yo), length = 3.03)
1492|> angledLine(angle = ghi(2), length = 3.04)
1493|> angledLine(angle = jkl(yo) + 2, length = 3.05)
1494|> close()
1495yo2 = hmm([identifierGuy + 5])"#;
1496
1497 parse_execute(ast).await.unwrap();
1498 }
1499
1500 #[tokio::test(flavor = "multi_thread")]
1501 async fn test_execute_with_pipe_substitutions_unary() {
1502 let ast = r#"myVar = 3
1503part001 = startSketchOn(XY)
1504 |> startProfile(at = [0, 0])
1505 |> line(end = [3, 4], tag = $seg01)
1506 |> line(end = [
1507 min([segLen(seg01), myVar]),
1508 -legLen(hypotenuse = segLen(seg01), leg = myVar)
1509])
1510"#;
1511
1512 parse_execute(ast).await.unwrap();
1513 }
1514
1515 #[tokio::test(flavor = "multi_thread")]
1516 async fn test_execute_with_pipe_substitutions() {
1517 let ast = r#"myVar = 3
1518part001 = startSketchOn(XY)
1519 |> startProfile(at = [0, 0])
1520 |> line(end = [3, 4], tag = $seg01)
1521 |> line(end = [
1522 min([segLen(seg01), myVar]),
1523 legLen(hypotenuse = segLen(seg01), leg = myVar)
1524])
1525"#;
1526
1527 parse_execute(ast).await.unwrap();
1528 }
1529
1530 #[tokio::test(flavor = "multi_thread")]
1531 async fn test_execute_with_inline_comment() {
1532 let ast = r#"baseThick = 1
1533armAngle = 60
1534
1535baseThickHalf = baseThick / 2
1536halfArmAngle = armAngle / 2
1537
1538arrExpShouldNotBeIncluded = [1, 2, 3]
1539objExpShouldNotBeIncluded = { a = 1, b = 2, c = 3 }
1540
1541part001 = startSketchOn(XY)
1542 |> startProfile(at = [0, 0])
1543 |> yLine(endAbsolute = 1)
1544 |> xLine(length = 3.84) // selection-range-7ish-before-this
1545
1546variableBelowShouldNotBeIncluded = 3
1547"#;
1548
1549 parse_execute(ast).await.unwrap();
1550 }
1551
1552 #[tokio::test(flavor = "multi_thread")]
1553 async fn test_execute_with_function_literal_in_pipe() {
1554 let ast = r#"w = 20
1555l = 8
1556h = 10
1557
1558fn thing() {
1559 return -8
1560}
1561
1562firstExtrude = startSketchOn(XY)
1563 |> startProfile(at = [0,0])
1564 |> line(end = [0, l])
1565 |> line(end = [w, 0])
1566 |> line(end = [0, thing()])
1567 |> close()
1568 |> extrude(length = h)"#;
1569
1570 parse_execute(ast).await.unwrap();
1571 }
1572
1573 #[tokio::test(flavor = "multi_thread")]
1574 async fn test_execute_with_function_unary_in_pipe() {
1575 let ast = r#"w = 20
1576l = 8
1577h = 10
1578
1579fn thing(@x) {
1580 return -x
1581}
1582
1583firstExtrude = startSketchOn(XY)
1584 |> startProfile(at = [0,0])
1585 |> line(end = [0, l])
1586 |> line(end = [w, 0])
1587 |> line(end = [0, thing(8)])
1588 |> close()
1589 |> extrude(length = h)"#;
1590
1591 parse_execute(ast).await.unwrap();
1592 }
1593
1594 #[tokio::test(flavor = "multi_thread")]
1595 async fn test_execute_with_function_array_in_pipe() {
1596 let ast = r#"w = 20
1597l = 8
1598h = 10
1599
1600fn thing(@x) {
1601 return [0, -x]
1602}
1603
1604firstExtrude = startSketchOn(XY)
1605 |> startProfile(at = [0,0])
1606 |> line(end = [0, l])
1607 |> line(end = [w, 0])
1608 |> line(end = thing(8))
1609 |> close()
1610 |> extrude(length = h)"#;
1611
1612 parse_execute(ast).await.unwrap();
1613 }
1614
1615 #[tokio::test(flavor = "multi_thread")]
1616 async fn test_execute_with_function_call_in_pipe() {
1617 let ast = r#"w = 20
1618l = 8
1619h = 10
1620
1621fn other_thing(@y) {
1622 return -y
1623}
1624
1625fn thing(@x) {
1626 return other_thing(x)
1627}
1628
1629firstExtrude = startSketchOn(XY)
1630 |> startProfile(at = [0,0])
1631 |> line(end = [0, l])
1632 |> line(end = [w, 0])
1633 |> line(end = [0, thing(8)])
1634 |> close()
1635 |> extrude(length = h)"#;
1636
1637 parse_execute(ast).await.unwrap();
1638 }
1639
1640 #[tokio::test(flavor = "multi_thread")]
1641 async fn test_execute_with_function_sketch() {
1642 let ast = r#"fn box(h, l, w) {
1643 myBox = startSketchOn(XY)
1644 |> startProfile(at = [0,0])
1645 |> line(end = [0, l])
1646 |> line(end = [w, 0])
1647 |> line(end = [0, -l])
1648 |> close()
1649 |> extrude(length = h)
1650
1651 return myBox
1652}
1653
1654fnBox = box(h = 3, l = 6, w = 10)"#;
1655
1656 parse_execute(ast).await.unwrap();
1657 }
1658
1659 #[tokio::test(flavor = "multi_thread")]
1660 async fn test_get_member_of_object_with_function_period() {
1661 let ast = r#"fn box(@obj) {
1662 myBox = startSketchOn(XY)
1663 |> startProfile(at = obj.start)
1664 |> line(end = [0, obj.l])
1665 |> line(end = [obj.w, 0])
1666 |> line(end = [0, -obj.l])
1667 |> close()
1668 |> extrude(length = obj.h)
1669
1670 return myBox
1671}
1672
1673thisBox = box({start = [0,0], l = 6, w = 10, h = 3})
1674"#;
1675 parse_execute(ast).await.unwrap();
1676 }
1677
1678 #[tokio::test(flavor = "multi_thread")]
1679 #[ignore] async fn test_object_member_starting_pipeline() {
1681 let ast = r#"
1682fn test2() {
1683 return {
1684 thing: startSketchOn(XY)
1685 |> startProfile(at = [0, 0])
1686 |> line(end = [0, 1])
1687 |> line(end = [1, 0])
1688 |> line(end = [0, -1])
1689 |> close()
1690 }
1691}
1692
1693x2 = test2()
1694
1695x2.thing
1696 |> extrude(length = 10)
1697"#;
1698 parse_execute(ast).await.unwrap();
1699 }
1700
1701 #[tokio::test(flavor = "multi_thread")]
1702 #[ignore] async fn test_execute_with_function_sketch_loop_objects() {
1704 let ast = r#"fn box(obj) {
1705let myBox = startSketchOn(XY)
1706 |> startProfile(at = obj.start)
1707 |> line(end = [0, obj.l])
1708 |> line(end = [obj.w, 0])
1709 |> line(end = [0, -obj.l])
1710 |> close()
1711 |> extrude(length = obj.h)
1712
1713 return myBox
1714}
1715
1716for var in [{start: [0,0], l: 6, w: 10, h: 3}, {start: [-10,-10], l: 3, w: 5, h: 1.5}] {
1717 thisBox = box(var)
1718}"#;
1719
1720 parse_execute(ast).await.unwrap();
1721 }
1722
1723 #[tokio::test(flavor = "multi_thread")]
1724 #[ignore] async fn test_execute_with_function_sketch_loop_array() {
1726 let ast = r#"fn box(h, l, w, start) {
1727 myBox = startSketchOn(XY)
1728 |> startProfile(at = [0,0])
1729 |> line(end = [0, l])
1730 |> line(end = [w, 0])
1731 |> line(end = [0, -l])
1732 |> close()
1733 |> extrude(length = h)
1734
1735 return myBox
1736}
1737
1738
1739for var in [[3, 6, 10, [0,0]], [1.5, 3, 5, [-10,-10]]] {
1740 const thisBox = box(var[0], var[1], var[2], var[3])
1741}"#;
1742
1743 parse_execute(ast).await.unwrap();
1744 }
1745
1746 #[tokio::test(flavor = "multi_thread")]
1747 async fn test_get_member_of_array_with_function() {
1748 let ast = r#"fn box(@arr) {
1749 myBox =startSketchOn(XY)
1750 |> startProfile(at = arr[0])
1751 |> line(end = [0, arr[1]])
1752 |> line(end = [arr[2], 0])
1753 |> line(end = [0, -arr[1]])
1754 |> close()
1755 |> extrude(length = arr[3])
1756
1757 return myBox
1758}
1759
1760thisBox = box([[0,0], 6, 10, 3])
1761
1762"#;
1763 parse_execute(ast).await.unwrap();
1764 }
1765
1766 #[tokio::test(flavor = "multi_thread")]
1767 async fn test_function_cannot_access_future_definitions() {
1768 let ast = r#"
1769fn returnX() {
1770 // x shouldn't be defined yet.
1771 return x
1772}
1773
1774x = 5
1775
1776answer = returnX()"#;
1777
1778 let result = parse_execute(ast).await;
1779 let err = result.unwrap_err();
1780 assert_eq!(err.message(), "`x` is not defined");
1781 }
1782
1783 #[tokio::test(flavor = "multi_thread")]
1784 async fn test_override_prelude() {
1785 let text = "PI = 3.0";
1786 let result = parse_execute(text).await.unwrap();
1787 let errs = result.exec_state.errors();
1788 assert!(errs.is_empty());
1789 }
1790
1791 #[tokio::test(flavor = "multi_thread")]
1792 async fn type_aliases() {
1793 let text = r#"@settings(experimentalFeatures = allow)
1794type MyTy = [number; 2]
1795fn foo(@x: MyTy) {
1796 return x[0]
1797}
1798
1799foo([0, 1])
1800
1801type Other = MyTy | Helix
1802"#;
1803 let result = parse_execute(text).await.unwrap();
1804 let errs = result.exec_state.errors();
1805 assert!(errs.is_empty());
1806 }
1807
1808 #[tokio::test(flavor = "multi_thread")]
1809 async fn test_cannot_shebang_in_fn() {
1810 let ast = r#"
1811fn foo() {
1812 #!hello
1813 return true
1814}
1815
1816foo
1817"#;
1818
1819 let result = parse_execute(ast).await;
1820 let err = result.unwrap_err();
1821 assert_eq!(
1822 err,
1823 KclError::new_syntax(KclErrorDetails::new(
1824 "Unexpected token: #".to_owned(),
1825 vec![SourceRange::new(14, 15, ModuleId::default())],
1826 )),
1827 );
1828 }
1829
1830 #[tokio::test(flavor = "multi_thread")]
1831 async fn test_pattern_transform_function_cannot_access_future_definitions() {
1832 let ast = r#"
1833fn transform(@replicaId) {
1834 // x shouldn't be defined yet.
1835 scale = x
1836 return {
1837 translate = [0, 0, replicaId * 10],
1838 scale = [scale, 1, 0],
1839 }
1840}
1841
1842fn layer() {
1843 return startSketchOn(XY)
1844 |> circle( center= [0, 0], radius= 1, tag = $tag1)
1845 |> extrude(length = 10)
1846}
1847
1848x = 5
1849
1850// The 10 layers are replicas of each other, with a transform applied to each.
1851shape = layer() |> patternTransform(instances = 10, transform = transform)
1852"#;
1853
1854 let result = parse_execute(ast).await;
1855 let err = result.unwrap_err();
1856 assert_eq!(err.message(), "`x` is not defined",);
1857 }
1858
1859 #[tokio::test(flavor = "multi_thread")]
1862 async fn test_math_execute_with_functions() {
1863 let ast = r#"myVar = 2 + min([100, -1 + legLen(hypotenuse = 5, leg = 3)])"#;
1864 let result = parse_execute(ast).await.unwrap();
1865 assert_eq!(
1866 5.0,
1867 mem_get_json(result.exec_state.stack(), result.mem_env, "myVar")
1868 .as_f64()
1869 .unwrap()
1870 );
1871 }
1872
1873 #[tokio::test(flavor = "multi_thread")]
1874 async fn test_math_execute() {
1875 let ast = r#"myVar = 1 + 2 * (3 - 4) / -5 + 6"#;
1876 let result = parse_execute(ast).await.unwrap();
1877 assert_eq!(
1878 7.4,
1879 mem_get_json(result.exec_state.stack(), result.mem_env, "myVar")
1880 .as_f64()
1881 .unwrap()
1882 );
1883 }
1884
1885 #[tokio::test(flavor = "multi_thread")]
1886 async fn test_math_execute_start_negative() {
1887 let ast = r#"myVar = -5 + 6"#;
1888 let result = parse_execute(ast).await.unwrap();
1889 assert_eq!(
1890 1.0,
1891 mem_get_json(result.exec_state.stack(), result.mem_env, "myVar")
1892 .as_f64()
1893 .unwrap()
1894 );
1895 }
1896
1897 #[tokio::test(flavor = "multi_thread")]
1898 async fn test_math_execute_with_pi() {
1899 let ast = r#"myVar = PI * 2"#;
1900 let result = parse_execute(ast).await.unwrap();
1901 assert_eq!(
1902 std::f64::consts::TAU,
1903 mem_get_json(result.exec_state.stack(), result.mem_env, "myVar")
1904 .as_f64()
1905 .unwrap()
1906 );
1907 }
1908
1909 #[tokio::test(flavor = "multi_thread")]
1910 async fn test_math_define_decimal_without_leading_zero() {
1911 let ast = r#"thing = .4 + 7"#;
1912 let result = parse_execute(ast).await.unwrap();
1913 assert_eq!(
1914 7.4,
1915 mem_get_json(result.exec_state.stack(), result.mem_env, "thing")
1916 .as_f64()
1917 .unwrap()
1918 );
1919 }
1920
1921 #[tokio::test(flavor = "multi_thread")]
1922 async fn pass_std_to_std() {
1923 let ast = r#"sketch001 = startSketchOn(XY)
1924profile001 = circle(sketch001, center = [0, 0], radius = 2)
1925extrude001 = extrude(profile001, length = 5)
1926extrudes = patternLinear3d(
1927 extrude001,
1928 instances = 3,
1929 distance = 5,
1930 axis = [1, 1, 0],
1931)
1932clone001 = map(extrudes, f = clone)
1933"#;
1934 parse_execute(ast).await.unwrap();
1935 }
1936
1937 #[tokio::test(flavor = "multi_thread")]
1938 async fn test_array_reduce_nested_array() {
1939 let code = r#"
1940fn id(@el, accum) { return accum }
1941
1942answer = reduce([], initial=[[[0,0]]], f=id)
1943"#;
1944 let result = parse_execute(code).await.unwrap();
1945 assert_eq!(
1946 mem_get_json(result.exec_state.stack(), result.mem_env, "answer"),
1947 KclValue::HomArray {
1948 value: vec![KclValue::HomArray {
1949 value: vec![KclValue::HomArray {
1950 value: vec![
1951 KclValue::Number {
1952 value: 0.0,
1953 ty: NumericType::default(),
1954 meta: vec![SourceRange::new(69, 70, Default::default()).into()],
1955 },
1956 KclValue::Number {
1957 value: 0.0,
1958 ty: NumericType::default(),
1959 meta: vec![SourceRange::new(71, 72, Default::default()).into()],
1960 }
1961 ],
1962 ty: RuntimeType::any(),
1963 }],
1964 ty: RuntimeType::any(),
1965 }],
1966 ty: RuntimeType::any(),
1967 }
1968 );
1969 }
1970
1971 #[tokio::test(flavor = "multi_thread")]
1972 async fn test_zero_param_fn() {
1973 let ast = r#"sigmaAllow = 35000 // psi
1974leg1 = 5 // inches
1975leg2 = 8 // inches
1976fn thickness() { return 0.56 }
1977
1978bracket = startSketchOn(XY)
1979 |> startProfile(at = [0,0])
1980 |> line(end = [0, leg1])
1981 |> line(end = [leg2, 0])
1982 |> line(end = [0, -thickness()])
1983 |> line(end = [-leg2 + thickness(), 0])
1984"#;
1985 parse_execute(ast).await.unwrap();
1986 }
1987
1988 #[tokio::test(flavor = "multi_thread")]
1989 async fn test_unary_operator_not_succeeds() {
1990 let ast = r#"
1991fn returnTrue() { return !false }
1992t = true
1993f = false
1994notTrue = !t
1995notFalse = !f
1996c = !!true
1997d = !returnTrue()
1998
1999assertIs(!false, error = "expected to pass")
2000
2001fn check(x) {
2002 assertIs(!x, error = "expected argument to be false")
2003 return true
2004}
2005check(x = false)
2006"#;
2007 let result = parse_execute(ast).await.unwrap();
2008 assert_eq!(
2009 false,
2010 mem_get_json(result.exec_state.stack(), result.mem_env, "notTrue")
2011 .as_bool()
2012 .unwrap()
2013 );
2014 assert_eq!(
2015 true,
2016 mem_get_json(result.exec_state.stack(), result.mem_env, "notFalse")
2017 .as_bool()
2018 .unwrap()
2019 );
2020 assert_eq!(
2021 true,
2022 mem_get_json(result.exec_state.stack(), result.mem_env, "c")
2023 .as_bool()
2024 .unwrap()
2025 );
2026 assert_eq!(
2027 false,
2028 mem_get_json(result.exec_state.stack(), result.mem_env, "d")
2029 .as_bool()
2030 .unwrap()
2031 );
2032 }
2033
2034 #[tokio::test(flavor = "multi_thread")]
2035 async fn test_unary_operator_not_on_non_bool_fails() {
2036 let code1 = r#"
2037// Yup, this is null.
2038myNull = 0 / 0
2039notNull = !myNull
2040"#;
2041 assert_eq!(
2042 parse_execute(code1).await.unwrap_err().message(),
2043 "Cannot apply unary operator ! to non-boolean value: a number",
2044 );
2045
2046 let code2 = "notZero = !0";
2047 assert_eq!(
2048 parse_execute(code2).await.unwrap_err().message(),
2049 "Cannot apply unary operator ! to non-boolean value: a number",
2050 );
2051
2052 let code3 = r#"
2053notEmptyString = !""
2054"#;
2055 assert_eq!(
2056 parse_execute(code3).await.unwrap_err().message(),
2057 "Cannot apply unary operator ! to non-boolean value: a string",
2058 );
2059
2060 let code4 = r#"
2061obj = { a = 1 }
2062notMember = !obj.a
2063"#;
2064 assert_eq!(
2065 parse_execute(code4).await.unwrap_err().message(),
2066 "Cannot apply unary operator ! to non-boolean value: a number",
2067 );
2068
2069 let code5 = "
2070a = []
2071notArray = !a";
2072 assert_eq!(
2073 parse_execute(code5).await.unwrap_err().message(),
2074 "Cannot apply unary operator ! to non-boolean value: an empty array",
2075 );
2076
2077 let code6 = "
2078x = {}
2079notObject = !x";
2080 assert_eq!(
2081 parse_execute(code6).await.unwrap_err().message(),
2082 "Cannot apply unary operator ! to non-boolean value: an object",
2083 );
2084
2085 let code7 = "
2086fn x() { return 1 }
2087notFunction = !x";
2088 let fn_err = parse_execute(code7).await.unwrap_err();
2089 assert!(
2092 fn_err
2093 .message()
2094 .starts_with("Cannot apply unary operator ! to non-boolean value: "),
2095 "Actual error: {fn_err:?}"
2096 );
2097
2098 let code8 = "
2099myTagDeclarator = $myTag
2100notTagDeclarator = !myTagDeclarator";
2101 let tag_declarator_err = parse_execute(code8).await.unwrap_err();
2102 assert!(
2105 tag_declarator_err
2106 .message()
2107 .starts_with("Cannot apply unary operator ! to non-boolean value: a tag declarator"),
2108 "Actual error: {tag_declarator_err:?}"
2109 );
2110
2111 let code9 = "
2112myTagDeclarator = $myTag
2113notTagIdentifier = !myTag";
2114 let tag_identifier_err = parse_execute(code9).await.unwrap_err();
2115 assert!(
2118 tag_identifier_err
2119 .message()
2120 .starts_with("Cannot apply unary operator ! to non-boolean value: a tag identifier"),
2121 "Actual error: {tag_identifier_err:?}"
2122 );
2123
2124 let code10 = "notPipe = !(1 |> 2)";
2125 assert_eq!(
2126 parse_execute(code10).await.unwrap_err(),
2129 KclError::new_syntax(KclErrorDetails::new(
2130 "Unexpected token: !".to_owned(),
2131 vec![SourceRange::new(10, 11, ModuleId::default())],
2132 ))
2133 );
2134
2135 let code11 = "
2136fn identity(x) { return x }
2137notPipeSub = 1 |> identity(!%))";
2138 assert_eq!(
2139 parse_execute(code11).await.unwrap_err(),
2142 KclError::new_syntax(KclErrorDetails::new(
2143 "There was an unexpected `!`. Try removing it.".to_owned(),
2144 vec![SourceRange::new(56, 57, ModuleId::default())],
2145 ))
2146 );
2147
2148 }
2152
2153 #[tokio::test(flavor = "multi_thread")]
2154 async fn test_start_sketch_on_invalid_kwargs() {
2155 let current_dir = std::env::current_dir().unwrap();
2156 let mut path = current_dir.join("tests/inputs/startSketchOn_0.kcl");
2157 let mut code = std::fs::read_to_string(&path).unwrap();
2158 assert_eq!(
2159 parse_execute(&code).await.unwrap_err().message(),
2160 "You cannot give both `face` and `normalToFace` params, you have to choose one or the other.".to_owned(),
2161 );
2162
2163 path = current_dir.join("tests/inputs/startSketchOn_1.kcl");
2164 code = std::fs::read_to_string(&path).unwrap();
2165
2166 assert_eq!(
2167 parse_execute(&code).await.unwrap_err().message(),
2168 "`alignAxis` is required if `normalToFace` is specified.".to_owned(),
2169 );
2170
2171 path = current_dir.join("tests/inputs/startSketchOn_2.kcl");
2172 code = std::fs::read_to_string(&path).unwrap();
2173
2174 assert_eq!(
2175 parse_execute(&code).await.unwrap_err().message(),
2176 "`normalToFace` is required if `alignAxis` is specified.".to_owned(),
2177 );
2178
2179 path = current_dir.join("tests/inputs/startSketchOn_3.kcl");
2180 code = std::fs::read_to_string(&path).unwrap();
2181
2182 assert_eq!(
2183 parse_execute(&code).await.unwrap_err().message(),
2184 "`normalToFace` is required if `alignAxis` is specified.".to_owned(),
2185 );
2186
2187 path = current_dir.join("tests/inputs/startSketchOn_4.kcl");
2188 code = std::fs::read_to_string(&path).unwrap();
2189
2190 assert_eq!(
2191 parse_execute(&code).await.unwrap_err().message(),
2192 "`normalToFace` is required if `normalOffset` is specified.".to_owned(),
2193 );
2194 }
2195
2196 #[tokio::test(flavor = "multi_thread")]
2197 async fn test_math_negative_variable_in_binary_expression() {
2198 let ast = r#"sigmaAllow = 35000 // psi
2199width = 1 // inch
2200
2201p = 150 // lbs
2202distance = 6 // inches
2203FOS = 2
2204
2205leg1 = 5 // inches
2206leg2 = 8 // inches
2207
2208thickness_squared = distance * p * FOS * 6 / sigmaAllow
2209thickness = 0.56 // inches. App does not support square root function yet
2210
2211bracket = startSketchOn(XY)
2212 |> startProfile(at = [0,0])
2213 |> line(end = [0, leg1])
2214 |> line(end = [leg2, 0])
2215 |> line(end = [0, -thickness])
2216 |> line(end = [-leg2 + thickness, 0])
2217"#;
2218 parse_execute(ast).await.unwrap();
2219 }
2220
2221 #[tokio::test(flavor = "multi_thread")]
2222 async fn test_execute_function_no_return() {
2223 let ast = r#"fn test(@origin) {
2224 origin
2225}
2226
2227test([0, 0])
2228"#;
2229 let result = parse_execute(ast).await;
2230 assert!(result.is_err());
2231 assert!(result.unwrap_err().to_string().contains("undefined"));
2232 }
2233
2234 #[tokio::test(flavor = "multi_thread")]
2235 async fn test_math_doubly_nested_parens() {
2236 let ast = r#"sigmaAllow = 35000 // psi
2237width = 4 // inch
2238p = 150 // Force on shelf - lbs
2239distance = 6 // inches
2240FOS = 2
2241leg1 = 5 // inches
2242leg2 = 8 // inches
2243thickness_squared = (distance * p * FOS * 6 / (sigmaAllow - width))
2244thickness = 0.32 // inches. App does not support square root function yet
2245bracket = startSketchOn(XY)
2246 |> startProfile(at = [0,0])
2247 |> line(end = [0, leg1])
2248 |> line(end = [leg2, 0])
2249 |> line(end = [0, -thickness])
2250 |> line(end = [-1 * leg2 + thickness, 0])
2251 |> line(end = [0, -1 * leg1 + thickness])
2252 |> close()
2253 |> extrude(length = width)
2254"#;
2255 parse_execute(ast).await.unwrap();
2256 }
2257
2258 #[tokio::test(flavor = "multi_thread")]
2259 async fn test_math_nested_parens_one_less() {
2260 let ast = r#" sigmaAllow = 35000 // psi
2261width = 4 // inch
2262p = 150 // Force on shelf - lbs
2263distance = 6 // inches
2264FOS = 2
2265leg1 = 5 // inches
2266leg2 = 8 // inches
2267thickness_squared = distance * p * FOS * 6 / (sigmaAllow - width)
2268thickness = 0.32 // inches. App does not support square root function yet
2269bracket = startSketchOn(XY)
2270 |> startProfile(at = [0,0])
2271 |> line(end = [0, leg1])
2272 |> line(end = [leg2, 0])
2273 |> line(end = [0, -thickness])
2274 |> line(end = [-1 * leg2 + thickness, 0])
2275 |> line(end = [0, -1 * leg1 + thickness])
2276 |> close()
2277 |> extrude(length = width)
2278"#;
2279 parse_execute(ast).await.unwrap();
2280 }
2281
2282 #[tokio::test(flavor = "multi_thread")]
2283 async fn test_fn_as_operand() {
2284 let ast = r#"fn f() { return 1 }
2285x = f()
2286y = x + 1
2287z = f() + 1
2288w = f() + f()
2289"#;
2290 parse_execute(ast).await.unwrap();
2291 }
2292
2293 #[tokio::test(flavor = "multi_thread")]
2294 async fn kcl_test_ids_stable_between_executions() {
2295 let code = r#"sketch001 = startSketchOn(XZ)
2296|> startProfile(at = [61.74, 206.13])
2297|> xLine(length = 305.11, tag = $seg01)
2298|> yLine(length = -291.85)
2299|> xLine(length = -segLen(seg01))
2300|> line(endAbsolute = [profileStartX(%), profileStartY(%)])
2301|> close()
2302|> extrude(length = 40.14)
2303|> shell(
2304 thickness = 3.14,
2305 faces = [seg01]
2306)
2307"#;
2308
2309 let ctx = crate::test_server::new_context(true, None).await.unwrap();
2310 let old_program = crate::Program::parse_no_errs(code).unwrap();
2311
2312 if let Err(err) = ctx.run_with_caching(old_program).await {
2314 let report = err.into_miette_report_with_outputs(code).unwrap();
2315 let report = miette::Report::new(report);
2316 panic!("Error executing program: {report:?}");
2317 }
2318
2319 let id_generator = cache::read_old_ast().await.unwrap().main.exec_state.id_generator;
2321
2322 let code = r#"sketch001 = startSketchOn(XZ)
2323|> startProfile(at = [62.74, 206.13])
2324|> xLine(length = 305.11, tag = $seg01)
2325|> yLine(length = -291.85)
2326|> xLine(length = -segLen(seg01))
2327|> line(endAbsolute = [profileStartX(%), profileStartY(%)])
2328|> close()
2329|> extrude(length = 40.14)
2330|> shell(
2331 faces = [seg01],
2332 thickness = 3.14,
2333)
2334"#;
2335
2336 let program = crate::Program::parse_no_errs(code).unwrap();
2338 ctx.run_with_caching(program).await.unwrap();
2340
2341 let new_id_generator = cache::read_old_ast().await.unwrap().main.exec_state.id_generator;
2342
2343 assert_eq!(id_generator, new_id_generator);
2344 }
2345
2346 #[tokio::test(flavor = "multi_thread")]
2347 async fn kcl_test_changing_a_setting_updates_the_cached_state() {
2348 let code = r#"sketch001 = startSketchOn(XZ)
2349|> startProfile(at = [61.74, 206.13])
2350|> xLine(length = 305.11, tag = $seg01)
2351|> yLine(length = -291.85)
2352|> xLine(length = -segLen(seg01))
2353|> line(endAbsolute = [profileStartX(%), profileStartY(%)])
2354|> close()
2355|> extrude(length = 40.14)
2356|> shell(
2357 thickness = 3.14,
2358 faces = [seg01]
2359)
2360"#;
2361
2362 let mut ctx = crate::test_server::new_context(true, None).await.unwrap();
2363 let old_program = crate::Program::parse_no_errs(code).unwrap();
2364
2365 ctx.run_with_caching(old_program.clone()).await.unwrap();
2367
2368 let settings_state = cache::read_old_ast().await.unwrap().settings;
2369
2370 assert_eq!(settings_state, ctx.settings);
2372
2373 ctx.settings.highlight_edges = !ctx.settings.highlight_edges;
2375
2376 ctx.run_with_caching(old_program.clone()).await.unwrap();
2378
2379 let settings_state = cache::read_old_ast().await.unwrap().settings;
2380
2381 assert_eq!(settings_state, ctx.settings);
2383
2384 ctx.settings.highlight_edges = !ctx.settings.highlight_edges;
2386
2387 ctx.run_with_caching(old_program).await.unwrap();
2389
2390 let settings_state = cache::read_old_ast().await.unwrap().settings;
2391
2392 assert_eq!(settings_state, ctx.settings);
2394
2395 ctx.close().await;
2396 }
2397
2398 #[tokio::test(flavor = "multi_thread")]
2399 async fn mock_after_not_mock() {
2400 let ctx = ExecutorContext::new_with_default_client().await.unwrap();
2401 let program = crate::Program::parse_no_errs("x = 2").unwrap();
2402 let result = ctx.run_with_caching(program).await.unwrap();
2403 assert_eq!(result.variables.get("x").unwrap().as_f64().unwrap(), 2.0);
2404
2405 let ctx2 = ExecutorContext::new_mock(None).await;
2406 let program2 = crate::Program::parse_no_errs("z = x + 1").unwrap();
2407 let result = ctx2.run_mock(&program2, true).await.unwrap();
2408 assert_eq!(result.variables.get("z").unwrap().as_f64().unwrap(), 3.0);
2409
2410 ctx.close().await;
2411 ctx2.close().await;
2412 }
2413
2414 #[cfg(feature = "artifact-graph")]
2415 #[tokio::test(flavor = "multi_thread")]
2416 async fn mock_has_stable_ids() {
2417 let ctx = ExecutorContext::new_mock(None).await;
2418 let code = "sk = startSketchOn(XY)
2419 |> startProfile(at = [0, 0])";
2420 let program = crate::Program::parse_no_errs(code).unwrap();
2421 let result = ctx.run_mock(&program, false).await.unwrap();
2422 let ids = result.artifact_graph.iter().map(|(k, _)| *k).collect::<Vec<_>>();
2423 assert!(!ids.is_empty(), "IDs should not be empty");
2424
2425 let ctx2 = ExecutorContext::new_mock(None).await;
2426 let program2 = crate::Program::parse_no_errs(code).unwrap();
2427 let result = ctx2.run_mock(&program2, false).await.unwrap();
2428 let ids2 = result.artifact_graph.iter().map(|(k, _)| *k).collect::<Vec<_>>();
2429
2430 assert_eq!(ids, ids2, "Generated IDs should match");
2431 }
2432
2433 #[cfg(feature = "artifact-graph")]
2434 #[tokio::test(flavor = "multi_thread")]
2435 async fn sim_sketch_mode_real_mock_real() {
2436 let ctx = ExecutorContext::new_with_default_client().await.unwrap();
2437 let code = r#"sketch001 = startSketchOn(XY)
2438profile001 = startProfile(sketch001, at = [0, 0])
2439 |> line(end = [10, 0])
2440 |> line(end = [0, 10])
2441 |> line(end = [-10, 0])
2442 |> line(end = [0, -10])
2443 |> close()
2444"#;
2445 let program = crate::Program::parse_no_errs(code).unwrap();
2446 let result = ctx.run_with_caching(program).await.unwrap();
2447 assert_eq!(result.operations.len(), 1);
2448
2449 let mock_ctx = ExecutorContext::new_mock(None).await;
2450 let mock_program = crate::Program::parse_no_errs(code).unwrap();
2451 let mock_result = mock_ctx.run_mock(&mock_program, true).await.unwrap();
2452 assert_eq!(mock_result.operations.len(), 1);
2453
2454 let code2 = code.to_owned()
2455 + r#"
2456extrude001 = extrude(profile001, length = 10)
2457"#;
2458 let program2 = crate::Program::parse_no_errs(&code2).unwrap();
2459 let result = ctx.run_with_caching(program2).await.unwrap();
2460 assert_eq!(result.operations.len(), 2);
2461
2462 ctx.close().await;
2463 mock_ctx.close().await;
2464 }
2465
2466 #[tokio::test(flavor = "multi_thread")]
2467 async fn read_tag_version() {
2468 let ast = r#"fn bar(@t) {
2469 return startSketchOn(XY)
2470 |> startProfile(at = [0,0])
2471 |> angledLine(
2472 angle = -60,
2473 length = segLen(t),
2474 )
2475 |> line(end = [0, 0])
2476 |> close()
2477}
2478
2479sketch = startSketchOn(XY)
2480 |> startProfile(at = [0,0])
2481 |> line(end = [0, 10])
2482 |> line(end = [10, 0], tag = $tag0)
2483 |> line(end = [0, 0])
2484
2485fn foo() {
2486 // tag0 tags an edge
2487 return bar(tag0)
2488}
2489
2490solid = sketch |> extrude(length = 10)
2491// tag0 tags a face
2492sketch2 = startSketchOn(solid, face = tag0)
2493 |> startProfile(at = [0,0])
2494 |> line(end = [0, 1])
2495 |> line(end = [1, 0])
2496 |> line(end = [0, 0])
2497
2498foo() |> extrude(length = 1)
2499"#;
2500 parse_execute(ast).await.unwrap();
2501 }
2502
2503 #[tokio::test(flavor = "multi_thread")]
2504 async fn experimental() {
2505 let code = r#"
2506startSketchOn(XY)
2507 |> startProfile(at = [0, 0], tag = $start)
2508 |> elliptic(center = [0, 0], angleStart = segAng(start), angleEnd = 160deg, majorRadius = 2, minorRadius = 3)
2509"#;
2510 let result = parse_execute(code).await.unwrap();
2511 let errors = result.exec_state.errors();
2512 assert_eq!(errors.len(), 1);
2513 assert_eq!(errors[0].severity, Severity::Error);
2514 let msg = &errors[0].message;
2515 assert!(msg.contains("experimental"), "found {msg}");
2516
2517 let code = r#"@settings(experimentalFeatures = allow)
2518startSketchOn(XY)
2519 |> startProfile(at = [0, 0], tag = $start)
2520 |> elliptic(center = [0, 0], angleStart = segAng(start), angleEnd = 160deg, majorRadius = 2, minorRadius = 3)
2521"#;
2522 let result = parse_execute(code).await.unwrap();
2523 let errors = result.exec_state.errors();
2524 assert!(errors.is_empty());
2525
2526 let code = r#"@settings(experimentalFeatures = warn)
2527startSketchOn(XY)
2528 |> startProfile(at = [0, 0], tag = $start)
2529 |> elliptic(center = [0, 0], angleStart = segAng(start), angleEnd = 160deg, majorRadius = 2, minorRadius = 3)
2530"#;
2531 let result = parse_execute(code).await.unwrap();
2532 let errors = result.exec_state.errors();
2533 assert_eq!(errors.len(), 1);
2534 assert_eq!(errors[0].severity, Severity::Warning);
2535 let msg = &errors[0].message;
2536 assert!(msg.contains("experimental"), "found {msg}");
2537
2538 let code = r#"@settings(experimentalFeatures = deny)
2539startSketchOn(XY)
2540 |> startProfile(at = [0, 0], tag = $start)
2541 |> elliptic(center = [0, 0], angleStart = segAng(start), angleEnd = 160deg, majorRadius = 2, minorRadius = 3)
2542"#;
2543 let result = parse_execute(code).await.unwrap();
2544 let errors = result.exec_state.errors();
2545 assert_eq!(errors.len(), 1);
2546 assert_eq!(errors[0].severity, Severity::Error);
2547 let msg = &errors[0].message;
2548 assert!(msg.contains("experimental"), "found {msg}");
2549
2550 let code = r#"@settings(experimentalFeatures = foo)
2551startSketchOn(XY)
2552 |> startProfile(at = [0, 0], tag = $start)
2553 |> elliptic(center = [0, 0], angleStart = segAng(start), angleEnd = 160deg, majorRadius = 2, minorRadius = 3)
2554"#;
2555 parse_execute(code).await.unwrap_err();
2556 }
2557}