kcl_lib/execution/
state.rs

1use std::{str::FromStr, sync::Arc};
2
3use anyhow::Result;
4use indexmap::IndexMap;
5use kittycad_modeling_cmds::units::{UnitAngle, UnitLength};
6use serde::{Deserialize, Serialize};
7use uuid::Uuid;
8
9#[cfg(feature = "artifact-graph")]
10use crate::execution::{Artifact, ArtifactCommand, ArtifactGraph, ArtifactId};
11use crate::{
12    CompilationError, EngineManager, ExecutorContext, KclErrorWithOutputs, SourceRange,
13    errors::{KclError, KclErrorDetails, Severity},
14    exec::DefaultPlanes,
15    execution::{
16        EnvironmentRef, ExecOutcome, ExecutorSettings, KclValue, SketchVarId, annotations,
17        cad_op::Operation,
18        id_generator::IdGenerator,
19        memory::{ProgramMemory, Stack},
20        types::NumericType,
21    },
22    modules::{ModuleId, ModuleInfo, ModuleLoader, ModulePath, ModuleRepr, ModuleSource},
23    parsing::ast::types::{Annotation, NodeRef},
24};
25
26/// State for executing a program.
27#[derive(Debug, Clone)]
28pub struct ExecState {
29    pub(super) global: GlobalState,
30    pub(super) mod_local: ModuleState,
31}
32
33pub type ModuleInfoMap = IndexMap<ModuleId, ModuleInfo>;
34
35#[derive(Debug, Clone)]
36pub(super) struct GlobalState {
37    /// Map from source file absolute path to module ID.
38    pub path_to_source_id: IndexMap<ModulePath, ModuleId>,
39    /// Map from module ID to source file.
40    pub id_to_source: IndexMap<ModuleId, ModuleSource>,
41    /// Map from module ID to module info.
42    pub module_infos: ModuleInfoMap,
43    /// Module loader.
44    pub mod_loader: ModuleLoader,
45    /// Errors and warnings.
46    pub errors: Vec<CompilationError>,
47    /// Global artifacts that represent the entire program.
48    pub artifacts: ArtifactState,
49    /// Artifacts for only the root module.
50    pub root_module_artifacts: ModuleArtifactState,
51}
52
53#[cfg(feature = "artifact-graph")]
54#[derive(Debug, Clone, Default)]
55pub(super) struct ArtifactState {
56    /// Internal map of UUIDs to exec artifacts.  This needs to persist across
57    /// executions to allow the graph building to refer to cached artifacts.
58    pub artifacts: IndexMap<ArtifactId, Artifact>,
59    /// Output artifact graph.
60    pub graph: ArtifactGraph,
61}
62
63#[cfg(not(feature = "artifact-graph"))]
64#[derive(Debug, Clone, Default)]
65pub(super) struct ArtifactState {}
66
67/// Artifact state for a single module.
68#[cfg(feature = "artifact-graph")]
69#[derive(Debug, Clone, Default, PartialEq, Serialize)]
70pub struct ModuleArtifactState {
71    /// Internal map of UUIDs to exec artifacts.
72    pub artifacts: IndexMap<ArtifactId, Artifact>,
73    /// Outgoing engine commands that have not yet been processed and integrated
74    /// into the artifact graph.
75    #[serde(skip)]
76    pub unprocessed_commands: Vec<ArtifactCommand>,
77    /// Outgoing engine commands.
78    pub commands: Vec<ArtifactCommand>,
79    /// Operations that have been performed in execution order, for display in
80    /// the Feature Tree.
81    pub operations: Vec<Operation>,
82}
83
84#[cfg(not(feature = "artifact-graph"))]
85#[derive(Debug, Clone, Default, PartialEq, Serialize)]
86pub struct ModuleArtifactState {}
87
88#[derive(Debug, Clone)]
89pub(super) struct ModuleState {
90    /// The id generator for this module.
91    pub id_generator: IdGenerator,
92    pub stack: Stack,
93    /// The current value of the pipe operator returned from the previous
94    /// expression.  If we're not currently in a pipeline, this will be None.
95    pub pipe_value: Option<KclValue>,
96    /// The closest variable declaration being executed in any parent node in the AST.
97    /// This is used to provide better error messages, e.g. noticing when the user is trying
98    /// to use the variable `length` inside the RHS of its own definition, like `length = tan(length)`.
99    pub being_declared: Option<String>,
100    /// Present if we're currently executing inside a sketch block.
101    pub sketch_block: Option<SketchBlockState>,
102    /// Tracks if KCL being executed is currently inside a stdlib function or not.
103    /// This matters because e.g. we shouldn't emit artifacts from declarations declared inside a stdlib function.
104    pub inside_stdlib: bool,
105    /// Identifiers that have been exported from the current module.
106    pub module_exports: Vec<String>,
107    /// Settings specified from annotations.
108    pub settings: MetaSettings,
109    pub(super) explicit_length_units: bool,
110    pub(super) path: ModulePath,
111    /// Artifacts for only this module.
112    pub artifacts: ModuleArtifactState,
113
114    pub(super) allowed_warnings: Vec<&'static str>,
115    pub(super) denied_warnings: Vec<&'static str>,
116}
117
118#[derive(Debug, Clone, Default)]
119pub(super) struct SketchBlockState {
120    pub sketch_vars: Vec<KclValue>,
121    pub constraints: Vec<kcl_ezpz::Constraint>,
122}
123
124impl ExecState {
125    pub fn new(exec_context: &super::ExecutorContext) -> Self {
126        ExecState {
127            global: GlobalState::new(&exec_context.settings),
128            mod_local: ModuleState::new(ModulePath::Main, ProgramMemory::new(), Default::default()),
129        }
130    }
131
132    pub(super) fn reset(&mut self, exec_context: &super::ExecutorContext) {
133        let global = GlobalState::new(&exec_context.settings);
134
135        *self = ExecState {
136            global,
137            mod_local: ModuleState::new(self.mod_local.path.clone(), ProgramMemory::new(), Default::default()),
138        };
139    }
140
141    /// Log a non-fatal error.
142    pub fn err(&mut self, e: CompilationError) {
143        self.global.errors.push(e);
144    }
145
146    /// Log a warning.
147    pub fn warn(&mut self, mut e: CompilationError, name: &'static str) {
148        debug_assert!(annotations::WARN_VALUES.contains(&name));
149
150        if self.mod_local.allowed_warnings.contains(&name) {
151            return;
152        }
153
154        if self.mod_local.denied_warnings.contains(&name) {
155            e.severity = Severity::Error;
156        } else {
157            e.severity = Severity::Warning;
158        }
159
160        self.global.errors.push(e);
161    }
162
163    pub fn warn_experimental(&mut self, feature_name: &str, source_range: SourceRange) {
164        let Some(severity) = self.mod_local.settings.experimental_features.severity() else {
165            return;
166        };
167        let error = CompilationError {
168            source_range,
169            message: format!("Use of {feature_name} is experimental and may change or be removed."),
170            suggestion: None,
171            severity,
172            tag: crate::errors::Tag::None,
173        };
174
175        self.global.errors.push(error);
176    }
177
178    pub fn clear_units_warnings(&mut self, source_range: &SourceRange) {
179        self.global.errors = std::mem::take(&mut self.global.errors)
180            .into_iter()
181            .filter(|e| {
182                e.severity != Severity::Warning
183                    || !source_range.contains_range(&e.source_range)
184                    || e.tag != crate::errors::Tag::UnknownNumericUnits
185            })
186            .collect();
187    }
188
189    pub fn errors(&self) -> &[CompilationError] {
190        &self.global.errors
191    }
192
193    /// Convert to execution outcome when running in WebAssembly.  We want to
194    /// reduce the amount of data that crosses the WASM boundary as much as
195    /// possible.
196    pub async fn into_exec_outcome(self, main_ref: EnvironmentRef, ctx: &ExecutorContext) -> ExecOutcome {
197        // Fields are opt-in so that we don't accidentally leak private internal
198        // state when we add more to ExecState.
199        ExecOutcome {
200            variables: self.mod_local.variables(main_ref),
201            filenames: self.global.filenames(),
202            #[cfg(feature = "artifact-graph")]
203            operations: self.global.root_module_artifacts.operations,
204            #[cfg(feature = "artifact-graph")]
205            artifact_graph: self.global.artifacts.graph,
206            errors: self.global.errors,
207            default_planes: ctx.engine.get_default_planes().read().await.clone(),
208        }
209    }
210
211    pub(crate) fn stack(&self) -> &Stack {
212        &self.mod_local.stack
213    }
214
215    pub(crate) fn mut_stack(&mut self) -> &mut Stack {
216        &mut self.mod_local.stack
217    }
218
219    pub fn next_uuid(&mut self) -> Uuid {
220        self.mod_local.id_generator.next_uuid()
221    }
222
223    pub fn id_generator(&mut self) -> &mut IdGenerator {
224        &mut self.mod_local.id_generator
225    }
226
227    #[cfg(feature = "artifact-graph")]
228    pub(crate) fn add_artifact(&mut self, artifact: Artifact) {
229        let id = artifact.id();
230        self.mod_local.artifacts.artifacts.insert(id, artifact);
231    }
232
233    pub(crate) fn push_op(&mut self, op: Operation) {
234        #[cfg(feature = "artifact-graph")]
235        self.mod_local.artifacts.operations.push(op.clone());
236        #[cfg(not(feature = "artifact-graph"))]
237        drop(op);
238    }
239
240    #[cfg(feature = "artifact-graph")]
241    pub(crate) fn push_command(&mut self, command: ArtifactCommand) {
242        self.mod_local.artifacts.unprocessed_commands.push(command);
243        #[cfg(not(feature = "artifact-graph"))]
244        drop(command);
245    }
246
247    pub(super) fn next_module_id(&self) -> ModuleId {
248        ModuleId::from_usize(self.global.path_to_source_id.len())
249    }
250
251    pub(super) fn id_for_module(&self, path: &ModulePath) -> Option<ModuleId> {
252        self.global.path_to_source_id.get(path).cloned()
253    }
254
255    pub(super) fn add_path_to_source_id(&mut self, path: ModulePath, id: ModuleId) {
256        debug_assert!(!self.global.path_to_source_id.contains_key(&path));
257        self.global.path_to_source_id.insert(path.clone(), id);
258    }
259
260    pub(crate) fn add_root_module_contents(&mut self, program: &crate::Program) {
261        let root_id = ModuleId::default();
262        // Get the path for the root module.
263        let path = self
264            .global
265            .path_to_source_id
266            .iter()
267            .find(|(_, v)| **v == root_id)
268            .unwrap()
269            .0
270            .clone();
271        self.add_id_to_source(
272            root_id,
273            ModuleSource {
274                path,
275                source: program.original_file_contents.to_string(),
276            },
277        );
278    }
279
280    pub(super) fn add_id_to_source(&mut self, id: ModuleId, source: ModuleSource) {
281        self.global.id_to_source.insert(id, source.clone());
282    }
283
284    pub(super) fn add_module(&mut self, id: ModuleId, path: ModulePath, repr: ModuleRepr) {
285        debug_assert!(self.global.path_to_source_id.contains_key(&path));
286        let module_info = ModuleInfo { id, repr, path };
287        self.global.module_infos.insert(id, module_info);
288    }
289
290    pub fn get_module(&mut self, id: ModuleId) -> Option<&ModuleInfo> {
291        self.global.module_infos.get(&id)
292    }
293
294    #[cfg(all(test, feature = "artifact-graph"))]
295    pub(crate) fn modules(&self) -> &ModuleInfoMap {
296        &self.global.module_infos
297    }
298
299    #[cfg(all(test, feature = "artifact-graph"))]
300    pub(crate) fn root_module_artifact_state(&self) -> &ModuleArtifactState {
301        &self.global.root_module_artifacts
302    }
303
304    pub fn current_default_units(&self) -> NumericType {
305        NumericType::Default {
306            len: self.length_unit(),
307            angle: self.angle_unit(),
308        }
309    }
310
311    pub fn length_unit(&self) -> UnitLength {
312        self.mod_local.settings.default_length_units
313    }
314
315    pub fn angle_unit(&self) -> UnitAngle {
316        self.mod_local.settings.default_angle_units
317    }
318
319    pub(super) fn circular_import_error(&self, path: &ModulePath, source_range: SourceRange) -> KclError {
320        KclError::new_import_cycle(KclErrorDetails::new(
321            format!(
322                "circular import of modules is not allowed: {} -> {}",
323                self.global
324                    .mod_loader
325                    .import_stack
326                    .iter()
327                    .map(|p| p.to_string_lossy())
328                    .collect::<Vec<_>>()
329                    .join(" -> "),
330                path,
331            ),
332            vec![source_range],
333        ))
334    }
335
336    pub(crate) fn pipe_value(&self) -> Option<&KclValue> {
337        self.mod_local.pipe_value.as_ref()
338    }
339
340    pub(crate) fn error_with_outputs(
341        &self,
342        error: KclError,
343        main_ref: Option<EnvironmentRef>,
344        default_planes: Option<DefaultPlanes>,
345    ) -> KclErrorWithOutputs {
346        let module_id_to_module_path: IndexMap<ModuleId, ModulePath> = self
347            .global
348            .path_to_source_id
349            .iter()
350            .map(|(k, v)| ((*v), k.clone()))
351            .collect();
352
353        KclErrorWithOutputs::new(
354            error,
355            self.errors().to_vec(),
356            main_ref
357                .map(|main_ref| self.mod_local.variables(main_ref))
358                .unwrap_or_default(),
359            #[cfg(feature = "artifact-graph")]
360            self.global.root_module_artifacts.operations.clone(),
361            #[cfg(feature = "artifact-graph")]
362            Default::default(),
363            #[cfg(feature = "artifact-graph")]
364            self.global.artifacts.graph.clone(),
365            module_id_to_module_path,
366            self.global.id_to_source.clone(),
367            default_planes,
368        )
369    }
370
371    #[cfg(feature = "artifact-graph")]
372    pub(crate) async fn build_artifact_graph(
373        &mut self,
374        engine: &Arc<Box<dyn EngineManager>>,
375        program: NodeRef<'_, crate::parsing::ast::types::Program>,
376    ) -> Result<(), KclError> {
377        let mut new_commands = Vec::new();
378        let mut new_exec_artifacts = IndexMap::new();
379        for module in self.global.module_infos.values_mut() {
380            match &mut module.repr {
381                ModuleRepr::Kcl(_, Some((_, _, _, module_artifacts)))
382                | ModuleRepr::Foreign(_, Some((_, module_artifacts))) => {
383                    new_commands.extend(module_artifacts.process_commands());
384                    new_exec_artifacts.extend(module_artifacts.artifacts.clone());
385                }
386                ModuleRepr::Root | ModuleRepr::Kcl(_, None) | ModuleRepr::Foreign(_, None) | ModuleRepr::Dummy => {}
387            }
388        }
389        // Take from the module artifacts so that we don't try to process them
390        // again next time due to execution caching.
391        new_commands.extend(self.global.root_module_artifacts.process_commands());
392        // Note: These will get re-processed, but since we're just adding them
393        // to a map, it's fine.
394        new_exec_artifacts.extend(self.global.root_module_artifacts.artifacts.clone());
395        let new_responses = engine.take_responses().await;
396
397        // Move the artifacts into ExecState global to simplify cache
398        // management.
399        self.global.artifacts.artifacts.extend(new_exec_artifacts);
400
401        let initial_graph = self.global.artifacts.graph.clone();
402
403        // Build the artifact graph.
404        let graph_result = crate::execution::artifact::build_artifact_graph(
405            &new_commands,
406            &new_responses,
407            program,
408            &mut self.global.artifacts.artifacts,
409            initial_graph,
410        );
411
412        let artifact_graph = graph_result?;
413        self.global.artifacts.graph = artifact_graph;
414
415        Ok(())
416    }
417
418    #[cfg(not(feature = "artifact-graph"))]
419    pub(crate) async fn build_artifact_graph(
420        &mut self,
421        _engine: &Arc<Box<dyn EngineManager>>,
422        _program: NodeRef<'_, crate::parsing::ast::types::Program>,
423    ) -> Result<(), KclError> {
424        Ok(())
425    }
426}
427
428impl GlobalState {
429    fn new(settings: &ExecutorSettings) -> Self {
430        let mut global = GlobalState {
431            path_to_source_id: Default::default(),
432            module_infos: Default::default(),
433            artifacts: Default::default(),
434            root_module_artifacts: Default::default(),
435            mod_loader: Default::default(),
436            errors: Default::default(),
437            id_to_source: Default::default(),
438        };
439
440        let root_id = ModuleId::default();
441        let root_path = settings.current_file.clone().unwrap_or_default();
442        global.module_infos.insert(
443            root_id,
444            ModuleInfo {
445                id: root_id,
446                path: ModulePath::Local {
447                    value: root_path.clone(),
448                    original_import_path: None,
449                },
450                repr: ModuleRepr::Root,
451            },
452        );
453        global.path_to_source_id.insert(
454            ModulePath::Local {
455                value: root_path.clone(),
456                original_import_path: None,
457            },
458            root_id,
459        );
460        global
461    }
462
463    pub(super) fn filenames(&self) -> IndexMap<ModuleId, ModulePath> {
464        self.path_to_source_id.iter().map(|(k, v)| ((*v), k.clone())).collect()
465    }
466
467    pub(super) fn get_source(&self, id: ModuleId) -> Option<&ModuleSource> {
468        self.id_to_source.get(&id)
469    }
470}
471
472impl ArtifactState {
473    #[cfg(feature = "artifact-graph")]
474    pub fn cached_body_items(&self) -> usize {
475        self.graph.item_count
476    }
477
478    pub(crate) fn clear(&mut self) {
479        #[cfg(feature = "artifact-graph")]
480        {
481            self.artifacts.clear();
482            self.graph.clear();
483        }
484    }
485}
486
487impl ModuleArtifactState {
488    pub(crate) fn clear(&mut self) {
489        #[cfg(feature = "artifact-graph")]
490        {
491            self.artifacts.clear();
492            self.unprocessed_commands.clear();
493            self.commands.clear();
494            self.operations.clear();
495        }
496    }
497
498    #[cfg(not(feature = "artifact-graph"))]
499    pub(crate) fn extend(&mut self, _other: ModuleArtifactState) {}
500
501    /// When self is a cached state, extend it with new state.
502    #[cfg(feature = "artifact-graph")]
503    pub(crate) fn extend(&mut self, other: ModuleArtifactState) {
504        self.artifacts.extend(other.artifacts);
505        self.unprocessed_commands.extend(other.unprocessed_commands);
506        self.commands.extend(other.commands);
507        self.operations.extend(other.operations);
508    }
509
510    // Move unprocessed artifact commands so that we don't try to process them
511    // again next time due to execution caching.  Returns a clone of the
512    // commands that were moved.
513    #[cfg(feature = "artifact-graph")]
514    pub(crate) fn process_commands(&mut self) -> Vec<ArtifactCommand> {
515        let unprocessed = std::mem::take(&mut self.unprocessed_commands);
516        let new_module_commands = unprocessed.clone();
517        self.commands.extend(unprocessed);
518        new_module_commands
519    }
520}
521
522impl ModuleState {
523    pub(super) fn new(path: ModulePath, memory: Arc<ProgramMemory>, module_id: Option<ModuleId>) -> Self {
524        ModuleState {
525            id_generator: IdGenerator::new(module_id),
526            stack: memory.new_stack(),
527            pipe_value: Default::default(),
528            being_declared: Default::default(),
529            sketch_block: Default::default(),
530            module_exports: Default::default(),
531            explicit_length_units: false,
532            path,
533            settings: Default::default(),
534            artifacts: Default::default(),
535            allowed_warnings: Vec::new(),
536            denied_warnings: Vec::new(),
537            inside_stdlib: false,
538        }
539    }
540
541    pub(super) fn variables(&self, main_ref: EnvironmentRef) -> IndexMap<String, KclValue> {
542        self.stack
543            .find_all_in_env(main_ref)
544            .map(|(k, v)| (k.clone(), v.clone()))
545            .collect()
546    }
547}
548
549impl SketchBlockState {
550    pub(crate) fn next_sketch_var_id(&self) -> SketchVarId {
551        SketchVarId(self.sketch_vars.len())
552    }
553}
554
555#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, ts_rs::TS)]
556#[ts(export)]
557#[serde(rename_all = "camelCase")]
558pub struct MetaSettings {
559    pub default_length_units: UnitLength,
560    pub default_angle_units: UnitAngle,
561    pub experimental_features: annotations::WarningLevel,
562    pub kcl_version: String,
563}
564
565impl Default for MetaSettings {
566    fn default() -> Self {
567        MetaSettings {
568            default_length_units: UnitLength::Millimeters,
569            default_angle_units: UnitAngle::Degrees,
570            experimental_features: annotations::WarningLevel::Deny,
571            kcl_version: "1.0".to_owned(),
572        }
573    }
574}
575
576impl MetaSettings {
577    pub(crate) fn update_from_annotation(
578        &mut self,
579        annotation: &crate::parsing::ast::types::Node<Annotation>,
580    ) -> Result<(bool, bool), KclError> {
581        let properties = annotations::expect_properties(annotations::SETTINGS, annotation)?;
582
583        let mut updated_len = false;
584        let mut updated_angle = false;
585        for p in properties {
586            match &*p.inner.key.name {
587                annotations::SETTINGS_UNIT_LENGTH => {
588                    let value = annotations::expect_ident(&p.inner.value)?;
589                    let value = super::types::length_from_str(value, annotation.as_source_range())?;
590                    self.default_length_units = value;
591                    updated_len = true;
592                }
593                annotations::SETTINGS_UNIT_ANGLE => {
594                    let value = annotations::expect_ident(&p.inner.value)?;
595                    let value = super::types::angle_from_str(value, annotation.as_source_range())?;
596                    self.default_angle_units = value;
597                    updated_angle = true;
598                }
599                annotations::SETTINGS_VERSION => {
600                    let value = annotations::expect_number(&p.inner.value)?;
601                    self.kcl_version = value;
602                }
603                annotations::SETTINGS_EXPERIMENTAL_FEATURES => {
604                    let value = annotations::expect_ident(&p.inner.value)?;
605                    let value = annotations::WarningLevel::from_str(value).map_err(|_| {
606                        KclError::new_semantic(KclErrorDetails::new(
607                            format!(
608                                "Invalid value for {} settings property, expected one of: {}",
609                                annotations::SETTINGS_EXPERIMENTAL_FEATURES,
610                                annotations::WARN_LEVELS.join(", ")
611                            ),
612                            annotation.as_source_ranges(),
613                        ))
614                    })?;
615                    self.experimental_features = value;
616                }
617                name => {
618                    return Err(KclError::new_semantic(KclErrorDetails::new(
619                        format!(
620                            "Unexpected settings key: `{name}`; expected one of `{}`, `{}`",
621                            annotations::SETTINGS_UNIT_LENGTH,
622                            annotations::SETTINGS_UNIT_ANGLE
623                        ),
624                        vec![annotation.as_source_range()],
625                    )));
626                }
627            }
628        }
629
630        Ok((updated_len, updated_angle))
631    }
632}