Skip to main content

kcl_lib/execution/
state.rs

1use std::collections::BTreeMap;
2use std::str::FromStr;
3use std::sync::Arc;
4
5use ahash::AHashMap;
6use anyhow::Result;
7use indexmap::IndexMap;
8pub use kcl_api::KclVersion;
9use kcl_api::UnitAngle;
10use kcl_api::UnitLength;
11use serde::Deserialize;
12use serde::Serialize;
13use uuid::Uuid;
14
15use crate::CompilationIssue;
16use crate::ExecutorContext;
17use crate::KclErrorWithOutputs;
18use crate::MockConfig;
19use crate::NodePath;
20use crate::SegmentDragAnchor;
21use crate::SourceRange;
22use crate::collections::AhashIndexSet;
23use crate::engine::engine_manager::EngineManager;
24use crate::errors::KclError;
25use crate::errors::KclErrorDetails;
26use crate::errors::Severity;
27use crate::exec::DefaultPlanes;
28use crate::execution::Artifact;
29use crate::execution::ArtifactCommand;
30use crate::execution::ArtifactGraph;
31use crate::execution::ArtifactId;
32use crate::execution::ConstrainableLine2d;
33use crate::execution::EnvironmentRef;
34use crate::execution::ExecOutcome;
35use crate::execution::ExecutorSettings;
36use crate::execution::KclValue;
37use crate::execution::KclValueView;
38use crate::execution::OperationCallbackArgs;
39use crate::execution::OperationsByModule;
40use crate::execution::ProgramLookup;
41use crate::execution::SketchVarId;
42use crate::execution::UnsolvedSegment;
43use crate::execution::annotations;
44use crate::execution::cad_op::Operation;
45use crate::execution::id_generator::IdGenerator;
46#[cfg(test)]
47use crate::execution::memory::MemoryBackendKind;
48use crate::execution::memory::ProgramMemory;
49use crate::execution::memory::Stack;
50use crate::execution::sketch_solve::Solved;
51use crate::execution::types::NumericType;
52use crate::front::Number;
53use crate::front::Object;
54use crate::front::ObjectId;
55use crate::front::ObjectKind;
56use crate::id::IncIdGenerator;
57use crate::modules::ModuleId;
58use crate::modules::ModuleInfo;
59use crate::modules::ModuleLoader;
60use crate::modules::ModulePath;
61use crate::modules::ModuleRepr;
62use crate::modules::ModuleSource;
63use crate::parsing::ast::types::Annotation;
64use crate::parsing::ast::types::Node;
65use crate::parsing::ast::types::NodeRef;
66use crate::parsing::ast::types::Program;
67use crate::parsing::ast::types::TagNode;
68
69/// State for executing a program.
70#[derive(Debug, Clone)]
71pub struct ExecState {
72    pub(super) execution_callbacks: Option<std::sync::Arc<dyn crate::execution::ExecutionCallbacks>>,
73    pub(super) global: GlobalState,
74    pub(super) mod_local: ModuleState,
75}
76
77pub type ModuleInfoMap = IndexMap<ModuleId, ModuleInfo>;
78
79#[derive(Debug, Clone)]
80pub(super) struct GlobalState {
81    /// The deepest machine-executor call depth reached by executions sharing
82    /// this state: the root module, its callbacks, and module bodies executed
83    /// inline on it. Imported modules pre-executed in parallel run on cloned
84    /// state whose counter is dropped, so their depths are not aggregated
85    /// here. Used to survey real-world depth against the runaway guard's
86    /// limit; see `machine::DEFAULT_MACHINE_CALL_DEPTH_LIMIT`.
87    pub(crate) machine_depth_high_water: usize,
88    /// Map from source file absolute path to module ID.
89    pub path_to_source_id: IndexMap<ModulePath, ModuleId>,
90    /// Map from module ID to source file.
91    pub id_to_source: IndexMap<ModuleId, ModuleSource>,
92    /// Map from module ID to module info.
93    pub module_infos: ModuleInfoMap,
94    /// `never` type uses in local imports, retained until their versions are validated.
95    pub never_type_ranges: IndexMap<ModuleId, Vec<SourceRange>>,
96    /// Module loader.
97    pub mod_loader: ModuleLoader,
98    /// Errors and warnings.
99    pub issues: Vec<CompilationIssue>,
100    /// If set, use this version only when deciding whether to emit
101    /// `deprecated_since` warnings. Runtime behavior still uses the version
102    /// declared by the KCL program.
103    pub deprecation_version_override: Option<String>,
104    /// The entry-point (root) module's declared kclVersion, or `None` when it
105    /// declares none. When this is KCL 3.0 or later, this single version
106    /// governs version-conditional runtime behavior for the whole execution --
107    /// every module and every function body. Otherwise (1.0, 2.0, or
108    /// undeclared) the legacy per-module lookup and its caller-version quirk
109    /// apply, see [`ExecState::legacy_caller_kcl_version`], and no imported
110    /// file may declare KCL 3.0 or later, see
111    /// [`ExecState::check_imported_module_kcl_version`]. Assigned
112    /// unconditionally at the start of every execution.
113    pub entry_point_kcl_version: Option<KclVersion>,
114    /// Global artifacts that represent the entire program.
115    pub artifacts: ArtifactState,
116    /// Artifacts for only the root module.
117    pub root_module_artifacts: ModuleArtifactState,
118    /// The segments that were edited that triggered this execution.
119    pub segment_ids_edited: AhashIndexSet<ObjectId>,
120    /// Segment-body drag anchors that temporarily pull a point on a segment toward the cursor.
121    pub drag_anchors: Vec<SegmentDragAnchor>,
122    /// True if this execution is sketch mode execution, executing a single
123    /// sketch block. Unlike [`ModuleState::sketch_mode`], this is constant for
124    /// the entire execution, including while executing the body of the sketch
125    /// block being edited.
126    pub sketch_mode: bool,
127    /// True when the engine being used for execution is CPU only with no graphical environment
128    pub geometry_only: bool,
129    /// Std's exported declarations skipped as not yet added. Set once by
130    /// `eval_prelude`, since root environments reach the prelude without an
131    /// import statement; the mock memory cache carries it like `module_infos`.
132    pub std_not_yet_added: IndexMap<String, NotYetAdded>,
133    /// Test-only: explain missing names for user declarations too, so tests
134    /// can cover the hint path while std declares nothing gated.
135    #[cfg(test)]
136    pub(crate) hint_all_not_yet_added: bool,
137}
138
139/// A declaration skipped because the program's KCL version predates its
140/// `added_in`, kept so a failed lookup of the name can explain why. Records
141/// flow like names: module scope, the module's outcome if exported, glob imports.
142#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
143pub struct NotYetAdded {
144    /// The KCL version the declaration is available from.
145    pub added_in: annotations::VersionConstraint,
146    /// Whether the declaration belongs to std. Only std declarations get the hint.
147    pub is_std: bool,
148}
149
150/// A record in a module's scope and whether the module exports it, by its own
151/// `export` or an `export import *`. Only exported records leave in the outcome.
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub(crate) struct ScopedNotYetAdded {
154    pub item: NotYetAdded,
155    pub exported: bool,
156}
157
158impl GlobalState {
159    pub(crate) fn operations_by_module(&self) -> OperationsByModule {
160        let mut operations = OperationsByModule::default();
161        operations.insert(ModuleId::default(), self.root_module_artifacts.operations.clone());
162
163        for (module_id, module_info) in &self.module_infos {
164            match &module_info.repr {
165                ModuleRepr::Root => {}
166                ModuleRepr::Kcl(_, Some(outcome)) => {
167                    operations.insert(*module_id, outcome.artifacts.operations.clone());
168                }
169                ModuleRepr::Foreign(_, Some((_, artifacts))) => {
170                    operations.insert(*module_id, artifacts.operations.clone());
171                }
172                ModuleRepr::Kcl(_, None) | ModuleRepr::Foreign(_, None) | ModuleRepr::Dummy => {}
173            }
174        }
175
176        operations
177    }
178}
179
180#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
181pub(crate) enum ConstraintKey {
182    LineCircle([usize; 10]),
183    CircleCircle([usize; 12]),
184}
185
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187pub(crate) enum TangencyMode {
188    LineCircle(ezpz::LineSide),
189    CircleCircle(ezpz::CircleSide),
190}
191
192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
193pub(crate) enum ConstraintState {
194    Tangency(TangencyMode),
195}
196
197#[derive(Debug, Clone, Default)]
198pub(super) struct ArtifactState {
199    /// Internal map of UUIDs to exec artifacts.  This needs to persist across
200    /// executions to allow the graph building to refer to cached artifacts.
201    pub artifacts: IndexMap<ArtifactId, Artifact>,
202    /// Output artifact graph.
203    pub graph: ArtifactGraph,
204}
205
206/// Which stdlib edge function produced this refactor metadata (for lint/code mod).
207#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
208#[ts(export)]
209#[serde(rename_all = "camelCase")]
210pub enum EdgeRefactorStdlibFn {
211    GetOppositeEdge,
212    GetNextAdjacentEdge,
213    GetPreviousAdjacentEdge,
214    GetCommonEdge,
215    EdgeId,
216}
217
218/// Metadata collected when a deprecated edge stdlib function runs, for refactor-to-edgeRefs lint/code mod.
219#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
220#[ts(export)]
221#[serde(rename_all = "camelCase")]
222pub struct EdgeRefactorMeta {
223    pub edge_id: Uuid,
224    pub face_ids: [Uuid; 2],
225    #[serde(default, skip_serializing_if = "Vec::is_empty")]
226    pub end_face_ids: Vec<Uuid>,
227    pub source_range: SourceRange,
228    pub stdlib_fn: EdgeRefactorStdlibFn,
229}
230
231/// Metadata for a deprecated edge stdlib function whose edge ID was resolved,
232/// but whose adjacent face IDs could not be recorded at the helper callsite.
233#[derive(Debug, Clone, PartialEq, Eq)]
234pub(crate) struct PendingEdgeRefactorMeta {
235    pub edge_id: Uuid,
236    pub source_range: SourceRange,
237    pub stdlib_fn: EdgeRefactorStdlibFn,
238}
239
240/// One tag entry in a fillet/chamfer call that used `tags` directly (for refactor to edgeRefs).
241#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
242#[ts(export)]
243#[serde(rename_all = "camelCase")]
244pub struct DirectTagFilletTagEntry {
245    pub tag_identifier: String,
246    pub edge_id: Uuid,
247    pub face_ids: [Uuid; 2],
248}
249
250/// Metadata for one fillet/chamfer call that used `tags` directly (no stdlib call).
251#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
252#[ts(export)]
253#[serde(rename_all = "camelCase")]
254pub struct DirectTagFilletMeta {
255    pub call_source_range: SourceRange,
256    pub tags: Vec<DirectTagFilletTagEntry>,
257}
258
259/// Information needed to rewrite one legacy `angle` call while preserving its
260/// currently solved directed-angle branch.
261#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
262#[ts(export)]
263#[serde(rename_all = "camelCase")]
264pub struct LegacyAngleRefactorMeta {
265    pub source_range: SourceRange,
266    pub sector: u8,
267    pub inverse: bool,
268}
269
270/// Unified metadata stream for Z0006 and future execution-backed refactors.
271#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
272#[ts(export)]
273#[serde(tag = "kind", content = "data", rename_all = "camelCase")]
274pub enum RefactorMetadata {
275    EdgeRefactor(Box<EdgeRefactorMeta>),
276    DirectTagFillet(DirectTagFilletMeta),
277    LegacyAngle(LegacyAngleRefactorMeta),
278}
279
280#[derive(Debug, Clone)]
281pub(crate) struct PendingLegacyAngleRefactorMeta {
282    pub source_range: SourceRange,
283    pub lines: [ConstrainableLine2d; 2],
284    pub desired_angle_radians: f64,
285}
286
287/// Artifact state for a single module.
288#[derive(Debug, Clone, Default, PartialEq, Serialize)]
289pub struct ModuleArtifactState {
290    /// Internal map of UUIDs to exec artifacts.
291    pub artifacts: IndexMap<ArtifactId, Artifact>,
292    /// Outgoing engine commands that have not yet been processed and integrated
293    /// into the artifact graph.
294    #[serde(skip)]
295    pub unprocessed_commands: Vec<ArtifactCommand>,
296    /// Outgoing engine commands.
297    pub commands: Vec<ArtifactCommand>,
298    /// Incoming engine commands.
299    #[cfg(feature = "snapshot-engine-responses")]
300    pub responses: IndexMap<Uuid, kittycad_modeling_cmds::websocket::WebSocketResponse>,
301    /// Operations that have been performed in execution order, for display in
302    /// the Feature Tree.
303    pub operations: Vec<Operation>,
304    /// [`ObjectId`] generator.
305    pub object_id_generator: IncIdGenerator<usize>,
306    /// Objects in the scene, created from execution.
307    pub scene_objects: Vec<Object>,
308    /// Map from source range to object ID for lookup of objects by their source
309    /// range.
310    pub source_range_to_object: BTreeMap<SourceRange, ObjectId>,
311    /// Map from artifact ID to object ID in the scene.
312    pub artifact_id_to_scene_object: IndexMap<ArtifactId, ObjectId>,
313    /// Solutions for sketch variables.
314    pub var_solutions: Vec<(SourceRange, Option<NodePath>, Number)>,
315    /// Metadata collected during execution for refactor lint/code-mod paths (Z0006 and future).
316    pub refactor_metadata: Vec<RefactorMetadata>,
317    /// Deprecated edge helper callsites that may be completed by a downstream
318    /// operation that knows the target solid.
319    #[serde(skip)]
320    pub(crate) pending_edge_refactor_metadata: Vec<PendingEdgeRefactorMeta>,
321}
322
323#[derive(Debug, Clone)]
324pub(super) struct ModuleState {
325    /// The id of this module.
326    pub module_id: ModuleId,
327    /// The id generator for this module.
328    pub id_generator: IdGenerator,
329    pub stack: Stack,
330    /// The size of the call stack. This is used to prevent stack overflows with
331    /// recursive function calls. In general, this doesn't match `stack`'s size
332    /// since it's conservative in reclaiming frames between executions.
333    pub(super) call_stack_size: usize,
334    /// Live call depth of the machine executor within this module, for its
335    /// runaway-recursion guard. The machine's analog of `call_stack_size`.
336    pub(crate) machine_call_depth: usize,
337    /// The current value of the pipe operator returned from the previous
338    /// expression.  If we're not currently in a pipeline, this will be None.
339    pub pipe_value: Option<KclValue>,
340    /// The closest variable declaration being executed in any parent node in the AST.
341    /// This is used to provide better error messages, e.g. noticing when the user is trying
342    /// to use the variable `length` inside the RHS of its own definition, like `length = tan(length)`.
343    pub being_declared: Option<String>,
344    /// Present if we're currently executing inside a sketch block.
345    pub sketch_block: Option<SketchBlockState>,
346    /// Tracks if KCL being executed is currently inside a stdlib function or not.
347    /// This matters because e.g. we shouldn't emit artifacts from declarations declared inside a stdlib function.
348    pub inside_stdlib: bool,
349    /// The source range where we entered the standard library.
350    pub stdlib_entry_source_range: Option<SourceRange>,
351    /// Identifiers that have been exported from the current module.
352    pub module_exports: Vec<String>,
353    /// Not-yet-added records in scope here: this module's own plus those from
354    /// glob imports. Only the exported ones travel in the module's outcome.
355    pub not_yet_added: IndexMap<String, ScopedNotYetAdded>,
356    /// Settings specified from annotations.
357    pub settings: MetaSettings,
358    /// True if executing in sketch mode. Only a single sketch block will be
359    /// executed. All other code is ignored.
360    pub sketch_mode: bool,
361    /// True to do more costly analysis of whether the sketch block segments are
362    /// under-constrained. The only time we disable this is when a user is
363    /// dragging segments.
364    pub freedom_analysis: bool,
365    pub(super) explicit_length_units: bool,
366    pub(super) path: ModulePath,
367    /// Artifacts for only this module.
368    pub artifacts: ModuleArtifactState,
369    /// Sticky per-constraint state persisted across sketch-mode mock solves.
370    /// Maps from sketch block ID to a map for that sketch.
371    /// Then the inner map is per constraint (in that sketch block) to its state.
372    pub constraint_state: IndexMap<ObjectId, IndexMap<ConstraintKey, ConstraintState>>,
373
374    pub(super) allowed_warnings: Vec<&'static str>,
375    pub(super) denied_warnings: Vec<&'static str>,
376
377    /// Map from consumed solid values to information about the operation that
378    /// consumed them. Populated by operations that destroy their inputs so that
379    /// subsequent attempts to use a consumed solid produce a clear KCL-level
380    /// error rather than a cryptic engine error.
381    pub(super) consumed_solids: AHashMap<ConsumedSolidKey, ConsumedSolidInfo>,
382    /// Defensive map from consumed engine UUID to consumption info.
383    /// Rust code may create a `Solid` with a consumed `engine_id` and a
384    /// different `instance_id` that was not recorded in `consumed_solids`. When
385    /// the exact key lookup misses, this map lets us reject that solid by
386    /// `engine_id`, unless the key is a recorded operation output.
387    pub(super) consumed_solid_ids: AHashMap<Uuid, ConsumedSolidInfo>,
388    /// Region engine UUIDs consumed by successful modeling operations. Regions
389    /// use the KCL `Sketch` representation, so this state keeps stale Region
390    /// values from reaching an engine object that has become something else.
391    pub(super) consumed_regions: AHashMap<Uuid, ConsumedRegionInfo>,
392}
393
394/// Information about the operation that consumed a Region.
395#[derive(Debug, Clone, Copy)]
396pub(crate) struct ConsumedRegionInfo {
397    operation: ConsumedRegionOperation,
398}
399
400impl ConsumedRegionInfo {
401    pub(crate) fn new(operation: ConsumedRegionOperation) -> Self {
402        Self { operation }
403    }
404
405    pub(crate) fn operation(self) -> ConsumedRegionOperation {
406        self.operation
407    }
408}
409
410#[derive(Debug, Clone, Copy, PartialEq, Eq)]
411pub(crate) enum ConsumedRegionOperation {
412    Extrude,
413    Revolve,
414    Sweep,
415    Delete,
416}
417
418impl std::fmt::Display for ConsumedRegionOperation {
419    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
420        match self {
421            Self::Extrude => f.write_str("extrude"),
422            Self::Revolve => f.write_str("revolve"),
423            Self::Sweep => f.write_str("sweep"),
424            Self::Delete => f.write_str("delete"),
425        }
426    }
427}
428
429/// Internal identity for one runtime KCL solid value.
430#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
431pub(crate) struct ConsumedSolidKey {
432    /// The engine body UUID.
433    engine_id: Uuid,
434    /// Distinguishes this KCL runtime instance from other values that may reuse
435    /// the same engine body UUID.
436    instance_id: Uuid,
437}
438
439impl ConsumedSolidKey {
440    pub(crate) fn new(engine_id: Uuid, instance_id: Uuid) -> Self {
441        Self { engine_id, instance_id }
442    }
443
444    pub(crate) fn engine_id(&self) -> Uuid {
445        self.engine_id
446    }
447
448    pub(crate) fn instance_id(&self) -> Uuid {
449        self.instance_id
450    }
451}
452
453/// Information about a solid value that was consumed by an operation.
454/// Stored in `ModuleState.consumed_solids` so subsequent attempts to use the
455/// solid produce a clear error pointing at the operation that consumed it.
456#[derive(Debug, Clone)]
457pub(crate) struct ConsumedSolidInfo {
458    /// The operation that consumed the solid.
459    operation: ConsumedSolidOperation,
460    /// First returned solid value, used only for replacement suggestions in
461    /// error messages. When present, this key is also included in
462    /// `returned_solid_keys`.
463    suggested_replacement_key: Option<ConsumedSolidKey>,
464    /// All solid values returned by that operation. This is used as the
465    /// allow-list for returned solids that reuse a consumed engine UUID.
466    returned_solid_keys: Vec<ConsumedSolidKey>,
467}
468
469impl ConsumedSolidInfo {
470    pub(crate) fn new(operation: ConsumedSolidOperation, returned_solid_keys: Vec<ConsumedSolidKey>) -> Self {
471        Self {
472            operation,
473            suggested_replacement_key: returned_solid_keys.first().copied(),
474            returned_solid_keys,
475        }
476    }
477
478    pub(crate) fn operation(&self) -> ConsumedSolidOperation {
479        self.operation
480    }
481
482    pub(crate) fn suggested_replacement_key(&self) -> Option<ConsumedSolidKey> {
483        self.suggested_replacement_key
484    }
485
486    pub(crate) fn should_report_reused_engine_id_as_consumed(&self, key: ConsumedSolidKey) -> bool {
487        !self.returned_solid_keys.contains(&key)
488    }
489}
490
491#[derive(Debug, Clone, Copy, PartialEq, Eq)]
492pub(crate) enum ConsumedSolidOperation {
493    Union,
494    Intersect,
495    Subtract,
496    Split,
497    JoinSurfaces,
498}
499
500impl ConsumedSolidOperation {
501    pub(crate) fn indefinite_article(self) -> &'static str {
502        match self {
503            Self::Intersect => "an",
504            Self::Union | Self::Subtract | Self::Split | Self::JoinSurfaces => "a",
505        }
506    }
507}
508
509impl std::fmt::Display for ConsumedSolidOperation {
510    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
511        match self {
512            Self::Union => f.write_str("union"),
513            Self::Intersect => f.write_str("intersect"),
514            Self::Subtract => f.write_str("subtract"),
515            Self::Split => f.write_str("split"),
516            Self::JoinSurfaces => f.write_str("joinSurfaces"),
517        }
518    }
519}
520
521#[derive(Debug, Clone, Default)]
522pub(crate) struct SketchBlockState {
523    pub sketch_vars: Vec<KclValue>,
524    pub sketch_id: Option<ObjectId>,
525    pub sketch_constraints: Vec<ObjectId>,
526    pub solver_constraints: Vec<ezpz::Constraint>,
527    pub solver_optional_constraints: Vec<ezpz::Constraint>,
528    pub needed_by_engine: Vec<UnsolvedSegment>,
529    pub segment_tags: IndexMap<ObjectId, TagNode>,
530    pub pending_legacy_angle_refactor_metadata: Vec<PendingLegacyAngleRefactorMeta>,
531}
532
533impl ExecState {
534    pub fn new(exec_context: &super::ExecutorContext) -> Self {
535        ExecState {
536            execution_callbacks: exec_context.execution_callbacks.clone(),
537            global: GlobalState::new(&exec_context.settings, Default::default()),
538            mod_local: ModuleState::new(ModulePath::Main, ProgramMemory::new(), Default::default(), false, true),
539        }
540    }
541
542    #[cfg(test)]
543    pub(crate) fn new_with_memory_backend(exec_context: &super::ExecutorContext, backend: MemoryBackendKind) -> Self {
544        ExecState {
545            execution_callbacks: exec_context.execution_callbacks.clone(),
546            global: GlobalState::new(&exec_context.settings, Default::default()),
547            mod_local: ModuleState::new(
548                ModulePath::Main,
549                ProgramMemory::new_with_backend(backend),
550                Default::default(),
551                false,
552                true,
553            ),
554        }
555    }
556
557    pub fn new_mock(exec_context: &super::ExecutorContext, mock_config: &MockConfig) -> Self {
558        let segment_ids_edited = mock_config.segment_ids_edited.clone();
559        let mut global = GlobalState::new(&exec_context.settings, segment_ids_edited);
560        global.drag_anchors = mock_config.drag_anchors.clone();
561        global.sketch_mode = mock_config.sketch_block_id.is_some();
562        ExecState {
563            execution_callbacks: exec_context.execution_callbacks.clone(),
564            global,
565            mod_local: ModuleState::new(
566                ModulePath::Main,
567                ProgramMemory::new(),
568                Default::default(),
569                mock_config.sketch_block_id.is_some(),
570                mock_config.freedom_analysis,
571            ),
572        }
573    }
574
575    #[cfg(test)]
576    pub(crate) fn new_mock_with_memory_backend(
577        exec_context: &super::ExecutorContext,
578        mock_config: &MockConfig,
579        backend: MemoryBackendKind,
580    ) -> Self {
581        let segment_ids_edited = mock_config.segment_ids_edited.clone();
582        let mut global = GlobalState::new(&exec_context.settings, segment_ids_edited);
583        global.drag_anchors = mock_config.drag_anchors.clone();
584        global.sketch_mode = mock_config.sketch_block_id.is_some();
585        ExecState {
586            execution_callbacks: exec_context.execution_callbacks.clone(),
587            global,
588            mod_local: ModuleState::new(
589                ModulePath::Main,
590                ProgramMemory::new_with_backend(backend),
591                Default::default(),
592                mock_config.sketch_block_id.is_some(),
593                mock_config.freedom_analysis,
594            ),
595        }
596    }
597
598    pub(super) fn reset(&mut self, exec_context: &super::ExecutorContext) {
599        let global = GlobalState::new(&exec_context.settings, Default::default());
600
601        *self = ExecState {
602            execution_callbacks: exec_context.execution_callbacks.clone(),
603            global,
604            mod_local: ModuleState::new(
605                self.mod_local.path.clone(),
606                ProgramMemory::new(),
607                Default::default(),
608                false,
609                true,
610            ),
611        };
612    }
613
614    /// Log a non-fatal error.
615    pub fn err(&mut self, e: CompilationIssue) {
616        self.global.issues.push(e);
617    }
618
619    /// Log a warning.
620    pub fn warn(&mut self, mut e: CompilationIssue, name: &'static str) {
621        debug_assert!(annotations::WARN_VALUES.contains(&name));
622
623        if self.mod_local.allowed_warnings.contains(&name) {
624            return;
625        }
626
627        if self.mod_local.denied_warnings.contains(&name) {
628            e.severity = Severity::Error;
629        } else {
630            e.severity = Severity::Warning;
631        }
632
633        self.global.issues.push(e);
634    }
635
636    pub fn warn_experimental(&mut self, feature_name: &str, source_range: SourceRange) {
637        let Some(severity) = self.mod_local.settings.experimental_features.severity() else {
638            return;
639        };
640        let error = CompilationIssue {
641            source_range,
642            message: format!("Use of {feature_name} is experimental and may change or be removed."),
643            suggestion: None,
644            severity,
645            tag: crate::errors::Tag::None,
646        };
647
648        self.global.issues.push(error);
649    }
650
651    pub fn clear_units_warnings(&mut self, source_range: &SourceRange) {
652        self.global.issues = std::mem::take(&mut self.global.issues)
653            .into_iter()
654            .filter(|e| {
655                e.severity != Severity::Warning
656                    || !source_range.contains_range(&e.source_range)
657                    || e.tag != crate::errors::Tag::UnknownNumericUnits
658            })
659            .collect();
660    }
661
662    pub fn issues(&self) -> &[CompilationIssue] {
663        &self.global.issues
664    }
665
666    pub(crate) fn deprecation_version(&self) -> &str {
667        self.global
668            .deprecation_version_override
669            .as_deref()
670            .unwrap_or(self.mod_local.settings.kcl_version.as_str())
671    }
672
673    /// The entry point's declared KCL version, or the default. `added_in`
674    /// gating uses this rather than [`Self::kcl_version`] because std modules
675    /// declare no version of their own.
676    pub(crate) fn entry_point_kcl_version(&self) -> KclVersion {
677        self.global.entry_point_kcl_version.unwrap_or_default()
678    }
679
680    /// Record that `key` was skipped in the current module because the
681    /// program's KCL version predates `added_in`.
682    pub(crate) fn record_not_yet_added(
683        &mut self,
684        key: String,
685        added_in: annotations::VersionConstraint,
686        exported: bool,
687    ) {
688        let item = NotYetAdded {
689            added_in,
690            is_std: matches!(self.mod_local.path, ModulePath::Std { .. }),
691        };
692        self.mod_local
693            .not_yet_added
694            .insert(key, ScopedNotYetAdded { item, exported });
695    }
696
697    /// Bring a glob-imported module's exported records into this scope, as
698    /// `import *` does for names. Records already here are left alone.
699    pub(crate) fn import_not_yet_added(&mut self, records: &IndexMap<String, NotYetAdded>, exported: bool) {
700        for (key, item) in records {
701            self.mod_local
702                .not_yet_added
703                .entry(key.clone())
704                .or_insert_with(|| ScopedNotYetAdded {
705                    item: item.clone(),
706                    exported,
707                });
708        }
709    }
710
711    /// The record for `key` in this module's scope, then in std's.
712    pub(crate) fn not_yet_added_in_scope(&self, key: &str) -> Option<&NotYetAdded> {
713        self.mod_local
714            .not_yet_added
715            .get(key)
716            .map(|scoped| &scoped.item)
717            .or_else(|| self.global.std_not_yet_added.get(key))
718    }
719
720    /// Append the version help to `err` if one of `keys` is a std declaration
721    /// skipped in the current scope, mirroring the not-yet-added parameter
722    /// message.
723    pub(crate) fn with_not_yet_added_hint(&self, keys: &[&str], err: KclError) -> KclError {
724        match keys.iter().find_map(|key| self.not_yet_added_in_scope(key)) {
725            Some(item) if self.hints_for(item) => self.not_yet_added_hint(item, err),
726            _ => err,
727        }
728    }
729
730    /// Like [`Self::with_not_yet_added_hint`], but consulting another module's
731    /// exported `records`.
732    pub(crate) fn with_not_yet_added_hint_from(
733        &self,
734        records: &IndexMap<String, NotYetAdded>,
735        keys: &[&str],
736        err: KclError,
737    ) -> KclError {
738        match keys.iter().find_map(|key| records.get(*key)) {
739            Some(item) if self.hints_for(item) => self.not_yet_added_hint(item, err),
740            _ => err,
741        }
742    }
743
744    /// Whether a failed lookup should mention `item`. Only std declarations
745    /// qualify, so a mismatch with the library is explained while user code
746    /// keeps the plain message; hints for user code would also have to follow
747    /// lexical scope, which these records do not.
748    fn hints_for(&self, item: &NotYetAdded) -> bool {
749        #[cfg(test)]
750        if self.global.hint_all_not_yet_added {
751            return true;
752        }
753        item.is_std
754    }
755
756    fn not_yet_added_hint(&self, item: &NotYetAdded, mut err: KclError) -> KclError {
757        let details = err.details_mut();
758        details.message = format!(
759            "{}; it was added in KCL {}, but this program uses KCL {}",
760            details.message,
761            item.added_in,
762            self.entry_point_kcl_version().as_str()
763        );
764        err
765    }
766
767    #[cfg(test)]
768    pub(crate) fn set_deprecation_version_override(&mut self, version: Option<&str>) {
769        self.global.deprecation_version_override = version.map(str::to_owned);
770    }
771
772    #[cfg(test)]
773    pub(crate) fn program_memory_for_tests(
774        &self,
775        main_ref: EnvironmentRef,
776    ) -> Result<IndexMap<String, KclValue>, KclError> {
777        self.mod_local.variables(main_ref)
778    }
779
780    /// Convert to execution outcome when running in WebAssembly.  We want to
781    /// reduce the amount of data that crosses the WASM boundary as much as
782    /// possible.
783    pub async fn into_exec_outcome(
784        self,
785        main_ref: EnvironmentRef,
786        ctx: &ExecutorContext,
787    ) -> Result<ExecOutcome, KclError> {
788        // Fields are opt-in so that we don't accidentally leak private internal
789        // state when we add more to ExecState.
790        let variables = self.mod_local.variables(main_ref)?;
791        #[cfg(test)]
792        let test_program_memory = variables.clone();
793        let variables = variables
794            .into_iter()
795            .map(|(key, value)| (key, KclValueView::from(value)))
796            .collect();
797        Ok(ExecOutcome {
798            variables,
799            filenames: self.global.filenames(),
800            operations: self.global.operations_by_module(),
801            artifact_graph: self.global.artifacts.graph,
802            scene_objects: self.global.root_module_artifacts.scene_objects,
803            source_range_to_object: self.global.root_module_artifacts.source_range_to_object,
804            var_solutions: self.global.root_module_artifacts.var_solutions,
805            refactor_metadata: self.global.root_module_artifacts.refactor_metadata.clone(),
806            issues: self.global.issues,
807            source_files: self.global.id_to_source,
808            default_planes: ctx.engine.get_default_planes().read().await.clone(),
809            #[cfg(test)]
810            test_program_memory,
811        })
812    }
813
814    #[cfg(feature = "snapshot-engine-responses")]
815    pub(crate) fn take_root_module_responses(
816        &mut self,
817    ) -> IndexMap<Uuid, kittycad_modeling_cmds::websocket::WebSocketResponse> {
818        std::mem::take(&mut self.global.root_module_artifacts.responses)
819    }
820
821    pub(crate) fn geometry_only(&self) -> bool {
822        self.global.geometry_only
823    }
824
825    pub(crate) fn stack(&self) -> &Stack {
826        &self.mod_local.stack
827    }
828
829    pub(crate) fn mut_stack(&mut self) -> &mut Stack {
830        &mut self.mod_local.stack
831    }
832
833    /// Increment the user-level call stack size, returning an error if it
834    /// exceeds the maximum.
835    pub(super) fn inc_call_stack_size(&mut self, range: SourceRange) -> Result<(), KclError> {
836        // If you change this, make sure to test in WebAssembly in the app since
837        // that's the limiting factor.
838        const LIMIT: usize = 50;
839        if self.mod_local.call_stack_size >= LIMIT {
840            return Err(KclError::new_max_call_stack(KclErrorDetails::new(
841                format!(
842                    "Call depth limit ({LIMIT}) exceeded. This usually means a function is recursing without a base case."
843                ),
844                vec![range],
845            )));
846        }
847        self.mod_local.call_stack_size += 1;
848        Ok(())
849    }
850
851    /// Decrement the user-level call stack size, returning an error if it would
852    /// go below zero.
853    pub(super) fn dec_call_stack_size(&mut self, range: SourceRange) -> Result<(), KclError> {
854        // Prevent underflow.
855        if self.mod_local.call_stack_size == 0 {
856            let message = "call stack size below zero".to_owned();
857            debug_assert!(false, "{message}");
858            return Err(KclError::new_internal(KclErrorDetails::new(message, vec![range])));
859        }
860        self.mod_local.call_stack_size -= 1;
861        Ok(())
862    }
863
864    /// The deepest machine-executor call depth reached in this execution.
865    /// The machine maintains the counter in all builds; today only the test
866    /// harnesses' depth survey reads it.
867    // Unused outside test builds, but kept available so release diagnostics
868    // can read the counter the machine already maintains.
869    #[allow(dead_code)]
870    pub(crate) fn machine_depth_high_water(&self) -> usize {
871        self.global.machine_depth_high_water
872    }
873
874    /// Returns true if we're executing in sketch mode for the current module.
875    /// In sketch mode, we still want to execute the prelude and other stdlib
876    /// modules as normal, so it can vary per module within a single overall
877    /// execution.
878    pub(crate) fn sketch_mode(&self) -> bool {
879        self.mod_local.sketch_mode
880            && match &self.mod_local.path {
881                ModulePath::Main => true,
882                ModulePath::Local { .. } => true,
883                ModulePath::Std { .. } => false,
884            }
885    }
886
887    /// Returns true if this execution is sketch mode execution, executing a
888    /// single sketch block. Unlike [`Self::sketch_mode`], this doesn't vary
889    /// during the execution.
890    pub(crate) fn is_sketch_mode_execution(&self) -> bool {
891        self.global.sketch_mode
892    }
893
894    pub fn next_object_id(&mut self) -> ObjectId {
895        ObjectId(self.mod_local.artifacts.object_id_generator.next_id())
896    }
897
898    pub fn peek_object_id(&self) -> ObjectId {
899        ObjectId(self.mod_local.artifacts.object_id_generator.peek_id())
900    }
901
902    pub(crate) fn constraint_state(&self, sketch_block_id: ObjectId, key: &ConstraintKey) -> Option<ConstraintState> {
903        let map = self.mod_local.constraint_state.get(&sketch_block_id)?;
904        map.get(key).copied()
905    }
906
907    pub(crate) fn set_constraint_state(
908        &mut self,
909        sketch_block_id: ObjectId,
910        key: ConstraintKey,
911        state: ConstraintState,
912    ) {
913        let map = self.mod_local.constraint_state.entry(sketch_block_id).or_default();
914        map.insert(key, state);
915    }
916
917    pub fn add_scene_object(&mut self, obj: Object, source_range: SourceRange) -> ObjectId {
918        let id = obj.id;
919        debug_assert!(
920            id.0 == self.mod_local.artifacts.scene_objects.len(),
921            "Adding scene object with ID {} but next ID is {}",
922            id.0,
923            self.mod_local.artifacts.scene_objects.len()
924        );
925        let artifact_id = obj.artifact_id;
926        self.mod_local.artifacts.scene_objects.push(obj);
927        self.mod_local.artifacts.source_range_to_object.insert(source_range, id);
928        self.mod_local
929            .artifacts
930            .artifact_id_to_scene_object
931            .insert(artifact_id, id);
932        id
933    }
934
935    /// Add a placeholder scene object. This is useful when we need to reserve
936    /// an ID before we have all the information to create the full object.
937    pub fn add_placeholder_scene_object(
938        &mut self,
939        id: ObjectId,
940        source_range: SourceRange,
941        node_path: Option<NodePath>,
942    ) -> ObjectId {
943        debug_assert!(id.0 == self.mod_local.artifacts.scene_objects.len());
944        self.mod_local
945            .artifacts
946            .scene_objects
947            .push(Object::placeholder(id, source_range, node_path));
948        self.mod_local.artifacts.source_range_to_object.insert(source_range, id);
949        id
950    }
951
952    /// Update a scene object. This is useful to replace a placeholder.
953    pub fn set_scene_object(&mut self, object: Object) {
954        let id = object.id;
955        let artifact_id = object.artifact_id;
956        self.mod_local.artifacts.scene_objects[id.0] = object;
957        self.mod_local
958            .artifacts
959            .artifact_id_to_scene_object
960            .insert(artifact_id, id);
961    }
962
963    pub fn scene_object_id_by_artifact_id(&self, artifact_id: ArtifactId) -> Option<ObjectId> {
964        self.mod_local
965            .artifacts
966            .artifact_id_to_scene_object
967            .get(&artifact_id)
968            .cloned()
969    }
970
971    pub fn segment_ids_edited_contains(&self, object_id: &ObjectId) -> bool {
972        self.global.segment_ids_edited.contains(object_id)
973    }
974
975    pub fn drag_anchor_target(&self, object_id: &ObjectId) -> Option<&crate::front::Point2d<crate::front::Number>> {
976        self.global
977            .drag_anchors
978            .iter()
979            .find(|anchor| &anchor.segment_id == object_id)
980            .map(|anchor| &anchor.target)
981    }
982
983    pub(super) fn is_in_sketch_block(&self) -> bool {
984        self.mod_local.sketch_block.is_some()
985    }
986
987    pub(crate) fn sketch_block_mut(&mut self) -> Option<&mut SketchBlockState> {
988        self.mod_local.sketch_block.as_mut()
989    }
990
991    pub(crate) fn sketch_block(&mut self) -> Option<&SketchBlockState> {
992        self.mod_local.sketch_block.as_ref()
993    }
994
995    pub fn next_uuid(&mut self) -> Uuid {
996        self.mod_local.id_generator.next_uuid()
997    }
998
999    pub fn next_artifact_id(&mut self) -> ArtifactId {
1000        self.mod_local.id_generator.next_artifact_id()
1001    }
1002
1003    pub fn id_generator(&mut self) -> &mut IdGenerator {
1004        &mut self.mod_local.id_generator
1005    }
1006
1007    /// Record that a solid value has been consumed by a CSG boolean operation.
1008    pub(crate) fn mark_solid_consumed(&mut self, consumed_key: ConsumedSolidKey, info: ConsumedSolidInfo) {
1009        self.mod_local.consumed_solids.insert(consumed_key, info);
1010    }
1011
1012    /// Record that an engine body UUID has been consumed by a CSG boolean
1013    /// operation.
1014    pub(crate) fn mark_solid_id_consumed(&mut self, consumed_id: Uuid, info: ConsumedSolidInfo) {
1015        self.mod_local.consumed_solid_ids.insert(consumed_id, info);
1016    }
1017
1018    /// Look up whether a solid value was consumed by a previous CSG boolean
1019    /// operation.
1020    pub(crate) fn check_solid_consumed(&self, key: &ConsumedSolidKey) -> Option<&ConsumedSolidInfo> {
1021        self.mod_local.consumed_solids.get(key)
1022    }
1023
1024    /// Look up whether an engine body UUID was consumed by a previous CSG
1025    /// boolean operation.
1026    pub(crate) fn check_solid_id_consumed(&self, id: &Uuid) -> Option<&ConsumedSolidInfo> {
1027        self.mod_local.consumed_solid_ids.get(id)
1028    }
1029
1030    pub(crate) fn mark_region_consumed(&mut self, id: Uuid, info: ConsumedRegionInfo) {
1031        self.mod_local.consumed_regions.insert(id, info);
1032    }
1033
1034    pub(crate) fn check_region_consumed(&self, id: &Uuid) -> Option<ConsumedRegionInfo> {
1035        self.mod_local.consumed_regions.get(id).copied()
1036    }
1037
1038    /// Find the current variable containing a Region engine UUID. This runs
1039    /// only while constructing a diagnostic, so recursively searching arrays
1040    /// and objects is preferable to storing variable names in liveness state.
1041    pub(crate) fn find_var_name_for_region_id(&self, target_id: Uuid) -> Result<Option<String>, KclError> {
1042        fn contains_region_id(value: &KclValue, target_id: Uuid) -> bool {
1043            match value {
1044                KclValue::Sketch { value } => value.origin_sketch_id.is_some() && value.id == target_id,
1045                KclValue::HomArray { value, .. } | KclValue::Tuple { value, .. } => {
1046                    value.iter().any(|value| contains_region_id(value, target_id))
1047                }
1048                KclValue::Object { value, .. } => value.values().any(|value| contains_region_id(value, target_id)),
1049                _ => false,
1050            }
1051        }
1052
1053        self.mod_local
1054            .stack
1055            .find_var_name_in_all_envs(|value| contains_region_id(value, target_id))
1056    }
1057
1058    /// Follow direct replacement links until we find the latest known output.
1059    /// Used only on error paths so diagnostics can suggest the current solid.
1060    pub(crate) fn latest_consumed_output(
1061        &self,
1062        suggested_replacement_key: Option<ConsumedSolidKey>,
1063    ) -> Option<ConsumedSolidKey> {
1064        let mut latest = suggested_replacement_key?;
1065        let mut seen = AhashIndexSet::default();
1066
1067        while seen.insert(latest) {
1068            let Some(next) = self
1069                .mod_local
1070                .consumed_solids
1071                .get(&latest)
1072                .and_then(|info| info.suggested_replacement_key())
1073            else {
1074                break;
1075            };
1076            latest = next;
1077        }
1078
1079        Some(latest)
1080    }
1081
1082    /// Search the live environment for the name of a variable holding a Solid
1083    /// (or an array of Solids) whose value identity matches `target_key`. Used only on
1084    /// error paths to recover variable names for diagnostics.
1085    pub(crate) fn find_var_name_for_solid_key(&self, target_key: ConsumedSolidKey) -> Result<Option<String>, KclError> {
1086        fn contains_solid_key(value: &KclValue, target_key: ConsumedSolidKey) -> bool {
1087            match value {
1088                KclValue::Solid { value } => {
1089                    value.id == target_key.engine_id() && value.value_id == target_key.instance_id()
1090                }
1091                KclValue::HomArray { value, .. } => value.iter().any(|v| contains_solid_key(v, target_key)),
1092                _ => false,
1093            }
1094        }
1095        self.mod_local
1096            .stack
1097            .find_var_name_in_all_envs(|value| contains_solid_key(value, target_key))
1098    }
1099
1100    pub(crate) fn add_artifact(&mut self, artifact: Artifact) {
1101        let id = artifact.id();
1102        self.mod_local.artifacts.artifacts.insert(id, artifact);
1103    }
1104
1105    /// The declaring module and display name of every named view registered so
1106    /// far. `view::named` needs these to reject a name that a view declared by
1107    /// the same module already uses.
1108    ///
1109    /// Both artifact maps are scanned, because incremental re-execution divides
1110    /// the views between them:
1111    /// - a run that clears the scene empties `global.artifacts` beforehand, so
1112    ///   every view it can see is one the current run registered into
1113    ///   `mod_local.artifacts`;
1114    /// - a run that only appends statements to an unchanged prefix does not
1115    ///   re-execute that prefix, so the views the prefix declared stay in
1116    ///   `global.artifacts` from the previous run while the appended
1117    ///   declarations register into `mod_local.artifacts`.
1118    ///
1119    /// Reading one map alone would accept a duplicate name on one of those
1120    /// paths and reject it on the other, which an author would see as the same
1121    /// file being accepted while typed and rejected after an unrelated edit.
1122    /// Neither path can report a view against its own earlier registration: a
1123    /// re-executed declaration is only reached after `global.artifacts` was
1124    /// cleared, and an appended declaration has no earlier registration.
1125    pub(crate) fn registered_named_views(&self) -> impl Iterator<Item = (ModuleId, &str)> {
1126        self.mod_local
1127            .artifacts
1128            .artifacts
1129            .values()
1130            .chain(self.global.artifacts.artifacts.values())
1131            .filter_map(|artifact| match artifact {
1132                Artifact::NamedView(view) => Some((view.code_ref.range.module_id(), view.name.as_str())),
1133                _ => None,
1134            })
1135    }
1136
1137    pub(crate) fn artifact_mut(&mut self, id: ArtifactId) -> Option<&mut Artifact> {
1138        self.mod_local.artifacts.artifacts.get_mut(&id)
1139    }
1140
1141    pub(crate) fn is_sketch_block_path(&self, path_id: ArtifactId) -> bool {
1142        self.mod_local
1143            .artifacts
1144            .artifacts
1145            .values()
1146            .chain(self.global.artifacts.artifacts.values())
1147            .any(|artifact| {
1148                matches!(artifact, Artifact::SketchBlock(sketch_block) if sketch_block.path_id == Some(path_id))
1149            })
1150    }
1151
1152    pub(crate) fn push_op(&mut self, op: Operation) {
1153        let index = self.mod_local.artifacts.operations.len();
1154        self.mod_local.artifacts.operations.push(op);
1155        if let Some(operation) = self.mod_local.artifacts.operations.last().cloned()
1156            && let Some(callbacks) = &self.execution_callbacks
1157        {
1158            callbacks.on_operation(OperationCallbackArgs {
1159                module_id: self.mod_local.module_id,
1160                operation,
1161                index,
1162            });
1163        }
1164    }
1165
1166    pub(crate) fn push_command(&mut self, command: ArtifactCommand) {
1167        self.mod_local.artifacts.unprocessed_commands.push(command);
1168    }
1169
1170    pub(super) fn next_module_id(&self) -> ModuleId {
1171        ModuleId::from_usize(self.global.path_to_source_id.len())
1172    }
1173
1174    pub(super) fn id_for_module(&self, path: &ModulePath) -> Option<ModuleId> {
1175        self.global.path_to_source_id.get(path).cloned()
1176    }
1177
1178    pub(super) fn add_path_to_source_id(&mut self, path: ModulePath, id: ModuleId) {
1179        debug_assert!(!self.global.path_to_source_id.contains_key(&path));
1180        self.global.path_to_source_id.insert(path, id);
1181    }
1182
1183    pub(crate) fn add_root_module_contents(&mut self, program: &crate::Program) {
1184        let root_id = ModuleId::default();
1185        // Get the path for the root module.
1186        let path = self
1187            .global
1188            .path_to_source_id
1189            .iter()
1190            .find(|(_, v)| **v == root_id)
1191            .unwrap()
1192            .0
1193            .clone();
1194        self.add_id_to_source(
1195            root_id,
1196            ModuleSource {
1197                path,
1198                source: program.original_file_contents.to_string(),
1199            },
1200        );
1201    }
1202
1203    pub(super) fn add_id_to_source(&mut self, id: ModuleId, source: ModuleSource) {
1204        self.global.id_to_source.insert(id, source);
1205    }
1206
1207    pub(super) fn add_module(&mut self, id: ModuleId, path: ModulePath, repr: ModuleRepr) {
1208        debug_assert!(self.global.path_to_source_id.contains_key(&path));
1209        let module_info = ModuleInfo { id, repr, path };
1210        self.global.module_infos.insert(id, module_info);
1211    }
1212
1213    pub fn get_module(&mut self, id: ModuleId) -> Option<&ModuleInfo> {
1214        self.global.module_infos.get(&id)
1215    }
1216
1217    #[cfg(test)]
1218    pub(crate) fn modules(&self) -> &ModuleInfoMap {
1219        &self.global.module_infos
1220    }
1221
1222    #[cfg(test)]
1223    pub(crate) fn root_module_artifact_state(&self) -> &ModuleArtifactState {
1224        &self.global.root_module_artifacts
1225    }
1226
1227    /// Record metadata from a deprecated edge stdlib call for the Z0006 refactor.
1228    pub(crate) fn record_edge_refactor_meta(&mut self, meta: EdgeRefactorMeta) {
1229        self.mod_local
1230            .artifacts
1231            .refactor_metadata
1232            .push(RefactorMetadata::EdgeRefactor(Box::new(meta)));
1233    }
1234
1235    pub(crate) fn record_pending_edge_refactor_meta(&mut self, meta: PendingEdgeRefactorMeta) {
1236        self.mod_local.artifacts.pending_edge_refactor_metadata.push(meta);
1237    }
1238
1239    pub(crate) fn pending_edge_refactor_meta(
1240        &self,
1241        edge_id: Uuid,
1242        argument_source_range: SourceRange,
1243    ) -> Option<PendingEdgeRefactorMeta> {
1244        if !crate::runtime_flags::z0006_refactor_metadata_enabled() {
1245            return None;
1246        }
1247        if let Some(pending) = self
1248            .mod_local
1249            .artifacts
1250            .pending_edge_refactor_metadata
1251            .iter()
1252            .find(|meta| meta.edge_id == edge_id && argument_source_range.contains_range(&meta.source_range))
1253        {
1254            return Some(pending.clone());
1255        }
1256
1257        // A helper assigned to a variable is outside the argument's source
1258        // range. Fall back to the edge ID only when it identifies one helper.
1259        let mut matches = self
1260            .mod_local
1261            .artifacts
1262            .pending_edge_refactor_metadata
1263            .iter()
1264            .filter(|meta| meta.edge_id == edge_id);
1265        let pending = matches.next()?.clone();
1266        matches.next().is_none().then_some(pending)
1267    }
1268
1269    pub(crate) fn record_edge_refactor_meta_from_pending(
1270        &mut self,
1271        edge_id: Uuid,
1272        source_range: SourceRange,
1273        face_ids: [Uuid; 2],
1274    ) -> bool {
1275        if self.mod_local.artifacts.refactor_metadata.iter().any(|meta| {
1276            matches!(
1277                meta,
1278                RefactorMetadata::EdgeRefactor(meta)
1279                    if meta.edge_id == edge_id && meta.source_range == source_range
1280            )
1281        }) {
1282            return true;
1283        }
1284
1285        let exact_pending_meta = self
1286            .mod_local
1287            .artifacts
1288            .pending_edge_refactor_metadata
1289            .iter()
1290            .find(|meta| meta.edge_id == edge_id && meta.source_range == source_range)
1291            .cloned();
1292
1293        let edge_pending_meta = || {
1294            let mut matches = self
1295                .mod_local
1296                .artifacts
1297                .pending_edge_refactor_metadata
1298                .iter()
1299                .filter(|meta| meta.edge_id == edge_id);
1300            let pending_meta = matches.next()?.clone();
1301            matches.next().is_none().then_some(pending_meta)
1302        };
1303
1304        let Some(pending_meta) = exact_pending_meta.or_else(edge_pending_meta) else {
1305            return false;
1306        };
1307
1308        self.record_edge_refactor_meta(EdgeRefactorMeta {
1309            edge_id,
1310            face_ids,
1311            end_face_ids: Vec::new(),
1312            source_range: pending_meta.source_range,
1313            stdlib_fn: pending_meta.stdlib_fn,
1314        });
1315
1316        true
1317    }
1318
1319    /// Record metadata from a fillet/chamfer call that used `tags` directly.
1320    pub(crate) fn record_direct_tag_fillet_meta(&mut self, meta: DirectTagFilletMeta) {
1321        self.mod_local
1322            .artifacts
1323            .refactor_metadata
1324            .push(RefactorMetadata::DirectTagFillet(meta));
1325    }
1326
1327    /// Refactor metadata collected when deprecated edge stdlib functions run (for tests and lint).
1328    pub fn edge_refactor_metadata(&self) -> Vec<EdgeRefactorMeta> {
1329        self.global
1330            .root_module_artifacts
1331            .refactor_metadata
1332            .iter()
1333            .filter_map(|m| match m {
1334                RefactorMetadata::EdgeRefactor(meta) => Some(meta.as_ref().clone()),
1335                RefactorMetadata::DirectTagFillet(_) | RefactorMetadata::LegacyAngle(_) => None,
1336            })
1337            .collect()
1338    }
1339
1340    /// Direct-tag fillet/chamfer metadata (for Z0006 code mod).
1341    pub fn direct_tag_fillet_metadata(&self) -> Vec<DirectTagFilletMeta> {
1342        self.global
1343            .root_module_artifacts
1344            .refactor_metadata
1345            .iter()
1346            .filter_map(|m| match m {
1347                RefactorMetadata::EdgeRefactor(_) | RefactorMetadata::LegacyAngle(_) => None,
1348                RefactorMetadata::DirectTagFillet(meta) => Some(meta.clone()),
1349            })
1350            .collect()
1351    }
1352
1353    pub fn current_default_units(&self) -> NumericType {
1354        NumericType::Default {
1355            len: self.length_unit(),
1356            angle: self.angle_unit(),
1357        }
1358    }
1359
1360    pub fn length_unit(&self) -> UnitLength {
1361        self.mod_local.settings.default_length_units
1362    }
1363
1364    pub fn angle_unit(&self) -> UnitAngle {
1365        self.mod_local.settings.default_angle_units
1366    }
1367
1368    pub(super) fn circular_import_error(&self, path: &ModulePath, source_range: SourceRange) -> KclError {
1369        KclError::new_import_cycle(KclErrorDetails::new(
1370            format!(
1371                "circular import of modules is not allowed: {} -> {}",
1372                self.global
1373                    .mod_loader
1374                    .import_stack
1375                    .iter()
1376                    .map(|p| p.to_string_lossy())
1377                    .collect::<Vec<_>>()
1378                    .join(" -> "),
1379                path,
1380            ),
1381            vec![source_range],
1382        ))
1383    }
1384
1385    pub(crate) fn pipe_value(&self) -> Option<&KclValue> {
1386        self.mod_local.pipe_value.as_ref()
1387    }
1388
1389    pub(crate) fn error_with_outputs(
1390        &self,
1391        error: KclError,
1392        main_ref: Option<EnvironmentRef>,
1393        default_planes: Option<DefaultPlanes>,
1394    ) -> KclErrorWithOutputs {
1395        let module_id_to_module_path: IndexMap<ModuleId, ModulePath> = self
1396            .global
1397            .path_to_source_id
1398            .iter()
1399            .map(|(k, v)| ((*v), k.clone()))
1400            .collect();
1401
1402        KclErrorWithOutputs::new(
1403            error,
1404            self.issues().to_vec(),
1405            main_ref
1406                .and_then(|main_ref| self.mod_local.variables(main_ref).ok())
1407                .unwrap_or_default(),
1408            self.global.operations_by_module(),
1409            Default::default(),
1410            self.global.artifacts.graph.clone(),
1411            self.global.root_module_artifacts.scene_objects.clone(),
1412            self.global.root_module_artifacts.source_range_to_object.clone(),
1413            self.global.root_module_artifacts.var_solutions.clone(),
1414            self.global.root_module_artifacts.refactor_metadata.clone(),
1415            module_id_to_module_path,
1416            self.global.id_to_source.clone(),
1417            default_planes,
1418        )
1419    }
1420
1421    pub(crate) fn build_program_lookup(
1422        &self,
1423        current: crate::parsing::ast::types::Node<crate::parsing::ast::types::Program>,
1424    ) -> ProgramLookup {
1425        ProgramLookup::new(current, self.global.module_infos.clone())
1426    }
1427
1428    pub(crate) async fn build_artifact_graph(
1429        &mut self,
1430        engine: &Arc<EngineManager>,
1431        program: NodeRef<'_, crate::parsing::ast::types::Program>,
1432    ) -> Result<(), KclError> {
1433        let mut new_commands = Vec::new();
1434        let mut new_exec_artifacts = IndexMap::new();
1435        for module in self.global.module_infos.values_mut() {
1436            match &mut module.repr {
1437                ModuleRepr::Kcl(_, Some(outcome)) => {
1438                    new_commands.extend(outcome.artifacts.process_commands());
1439                    new_exec_artifacts.extend(outcome.artifacts.artifacts.clone());
1440                }
1441                ModuleRepr::Foreign(_, Some((_, module_artifacts))) => {
1442                    new_commands.extend(module_artifacts.process_commands());
1443                    new_exec_artifacts.extend(module_artifacts.artifacts.clone());
1444                }
1445                ModuleRepr::Root | ModuleRepr::Kcl(_, None) | ModuleRepr::Foreign(_, None) | ModuleRepr::Dummy => {}
1446            }
1447        }
1448        // Take from the module artifacts so that we don't try to process them
1449        // again next time due to execution caching.
1450        new_commands.extend(self.global.root_module_artifacts.process_commands());
1451        // Note: These will get re-processed, but since we're just adding them
1452        // to a map, it's fine.
1453        new_exec_artifacts.extend(self.global.root_module_artifacts.artifacts.clone());
1454        let new_responses = engine.take_responses().await;
1455
1456        // Move the artifacts into ExecState global to simplify cache
1457        // management.
1458        for (id, exec_artifact) in new_exec_artifacts {
1459            // Only insert if it wasn't already present. We don't want to
1460            // overwrite what was previously there. We haven't filled in node
1461            // paths yet.
1462            self.global.artifacts.artifacts.entry(id).or_insert(exec_artifact);
1463        }
1464
1465        let initial_graph = self.global.artifacts.graph.clone();
1466
1467        // Build the artifact graph.
1468        let programs = self.build_program_lookup(program.clone());
1469        let graph_result = crate::execution::artifact::build_artifact_graph(
1470            &new_commands,
1471            &new_responses,
1472            program,
1473            &mut self.global.artifacts.artifacts,
1474            initial_graph,
1475            &programs,
1476            &self.global.module_infos,
1477        );
1478
1479        #[cfg(feature = "snapshot-engine-responses")]
1480        {
1481            // Store engine responses for debugging.
1482            self.global.root_module_artifacts.responses.extend(new_responses);
1483        }
1484
1485        let artifact_graph = graph_result?;
1486        self.global.artifacts.graph = artifact_graph;
1487
1488        Ok(())
1489    }
1490
1491    /// The KCL version governing version-conditional runtime behavior.
1492    ///
1493    /// If the entry-point module declared kclVersion 3.0-preview (or later),
1494    /// that single version governs the entire execution -- all modules and
1495    /// all function bodies. Otherwise, falls back to the legacy per-module
1496    /// lookup; see [`Self::legacy_caller_kcl_version`].
1497    pub(crate) fn kcl_version(&self) -> KclVersion {
1498        match self.global.entry_point_kcl_version {
1499            Some(version) if version >= KclVersion::V3Preview => version,
1500            _ => self.legacy_caller_kcl_version(),
1501        }
1502    }
1503
1504    /// The legacy kclVersion lookup: the current module-local settings.
1505    ///
1506    /// Quirk (fixed when the entry point declares 3.0-preview or later):
1507    /// `mod_local` is swapped only around module top-level execution, never
1508    /// around function calls, so module-level code sees its own module's
1509    /// declared version, but a function body sees the CALLING module's
1510    /// version -- a function defined in a 1.0 module but called from a 2.0
1511    /// module observes 2.0 here.
1512    pub(crate) fn legacy_caller_kcl_version(&self) -> KclVersion {
1513        self.mod_local.settings.kcl_version
1514    }
1515
1516    /// Gate for behaviors introduced in KCL 3.0. True only when the entry-point
1517    /// module of this execution declares KCL 3.0 or later. This never looks at
1518    /// [`Self::legacy_caller_kcl_version()`] so that behavior never varies
1519    /// within a single execution.
1520    pub(crate) fn entry_point_version_is_v3_or_higher(&self) -> bool {
1521        self.global
1522            .entry_point_kcl_version
1523            .is_some_and(|v| v >= KclVersion::V3Preview)
1524    }
1525
1526    /// Record the entry-point program's declared kclVersion for this
1527    /// execution, or `None` when it declares no kclVersion. Must be assigned
1528    /// unconditionally at the start of every execution since the state may be
1529    /// reused across executions whose programs declare different versions.
1530    pub(crate) fn set_entry_point_kcl_version(&mut self, program: &crate::Program) -> Result<(), KclError> {
1531        let version = program.language_version()?;
1532        // Import diagnostics distinguish an explicit version from the default.
1533        self.global.entry_point_kcl_version = declared_kcl_version(&program.ast)?.map(|_| version);
1534        Ok(())
1535    }
1536
1537    /// KCL 3.0: the entry point's declared kclVersion decides which kclVersion
1538    /// an imported file may declare, so that KCL 3.0 semantics never apply to
1539    /// only part of a program.
1540    ///
1541    /// - When the entry point declares 3.0-preview or later, that version
1542    ///   governs the whole execution (see [`Self::kcl_version`]), and an
1543    ///   imported file may not declare a different one.
1544    /// - Otherwise (1.0, 2.0, or undeclared), the legacy per-module lookup
1545    ///   applies, and an imported file may not declare 3.0-preview or later,
1546    ///   which the legacy lookup would honor for that file only. Mixing 1.0
1547    ///   and 2.0 remains allowed, as it always has been.
1548    ///
1549    /// A file that declares no kclVersion does not cause a version mismatch:
1550    /// it runs under the version the lookup gives it. Only user files (local
1551    /// imports) are checked. Standard library modules are exempt: they ship
1552    /// with the interpreter, always run under the entry point's pinned
1553    /// version, and the user cannot edit them to resolve a mismatch. Foreign
1554    /// imports carry no KCL settings.
1555    ///
1556    /// `import_range` is the import statement when the check runs at the
1557    /// import site, which is included in the error.
1558    pub(crate) fn check_imported_module_kcl_version(
1559        &self,
1560        path: &ModulePath,
1561        program: &Node<Program>,
1562        import_range: Option<SourceRange>,
1563    ) -> Result<(), KclError> {
1564        if !path.is_local() {
1565            // stdlib is exempt from the restriction, and `Main` is the version
1566            // we're checking against.
1567            return Ok(());
1568        }
1569        let Some((declared, declared_range)) = declared_kcl_version(program)? else {
1570            return Ok(());
1571        };
1572        let entry_point_version = self.global.entry_point_kcl_version;
1573        let allowed = if self.entry_point_version_is_v3_or_higher() {
1574            Some(declared) == entry_point_version
1575        } else {
1576            declared < KclVersion::V3Preview
1577        };
1578        if allowed {
1579            return Ok(());
1580        }
1581
1582        // The root module's path is the executor's current file, which is
1583        // empty when execution was started without one.
1584        let entry_point = match self
1585            .global
1586            .module_infos
1587            .get(&ModuleId::default())
1588            .map(|info| &info.path)
1589        {
1590            Some(root @ ModulePath::Local { .. }) if !root.to_string().is_empty() => {
1591                format!("The entry point `{root}`")
1592            }
1593            _ => "The entry point".to_owned(),
1594        };
1595        let (entry_point_declares, fix) = match entry_point_version {
1596            Some(version) => (
1597                format!("declares kclVersion {}", version.as_str()),
1598                "Update the kclVersion setting in one of these files to match the other.",
1599            ),
1600            None => (
1601                "does not declare a kclVersion".to_owned(),
1602                "Declare the same kclVersion in the entry point, or update the setting in the imported file.",
1603            ),
1604        };
1605        let mut source_ranges = vec![declared_range];
1606        source_ranges.extend(import_range);
1607        Err(KclError::new_semantic(KclErrorDetails::new(
1608            format!(
1609                "Mixing KCL versions in a single program is not allowed. {entry_point} {entry_point_declares}, but the imported file `{path}` declares kclVersion {}. {fix}",
1610                declared.as_str(),
1611            ),
1612            source_ranges,
1613        )))
1614    }
1615
1616    /// Check an imported file before executing it. Version mismatches take
1617    /// priority over versioned syntax restrictions.
1618    /// The loader-assigned module ID identifies source and syntax metadata;
1619    /// an empty parsed program retains the default AST module ID.
1620    pub(crate) fn validate_imported_module(
1621        &self,
1622        path: &ModulePath,
1623        module_id: ModuleId,
1624        program: &Node<Program>,
1625        import_range: Option<SourceRange>,
1626    ) -> Result<(), KclError> {
1627        self.check_imported_module_kcl_version(path, program, import_range)?;
1628        if !path.is_local() {
1629            return Ok(());
1630        }
1631
1632        let ranges = self.global.never_type_ranges.get(&module_id).ok_or_else(|| {
1633            KclError::new_internal(KclErrorDetails::new(
1634                format!("Missing `never` type ranges for imported KCL module `{path}`"),
1635                import_range.into_iter().collect(),
1636            ))
1637        })?;
1638        crate::parsing::validate_never_type_ranges(
1639            ranges,
1640            crate::parsing::SyntaxSource::UserCode(self.entry_point_kcl_version()),
1641        )
1642        .map_err(|error| match import_range {
1643            Some(range) => error.add_import_location(&path.import_name(), range),
1644            None => error,
1645        })?;
1646        if !self.entry_point_version_is_v3_or_higher() {
1647            return Ok(());
1648        }
1649
1650        let source = self.global.id_to_source.get(&module_id).ok_or_else(|| {
1651            KclError::new_internal(KclErrorDetails::new(
1652                format!("Missing source for imported KCL module `{path}`"),
1653                import_range.into_iter().collect(),
1654            ))
1655        })?;
1656        let validation = crate::parsing::validate_use_keyword_source(&source.source, module_id)
1657            .and_then(|_| crate::parsing::validate_enum_keyword_source(&source.source, module_id))
1658            .and_then(|_| crate::parsing::validate_import_modifier_source(&source.source, module_id));
1659        validation.map_err(|error| match import_range {
1660            Some(range) => error.add_import_location(&path.import_name(), range),
1661            None => error,
1662        })
1663    }
1664}
1665
1666/// The kclVersion that a program's `@settings` annotations declare, with the
1667/// source range of the declaring property, or `None` when the program does not
1668/// declare one. The last declaration wins, as in
1669/// [`MetaSettings::update_from_annotation`], so this searches from the end and
1670/// stops at the first match.
1671pub(crate) fn declared_kcl_version(program: &Node<Program>) -> Result<Option<(KclVersion, SourceRange)>, KclError> {
1672    let Some(property) = program
1673        .inner_attrs
1674        .iter()
1675        .rev()
1676        .filter(|annotation| annotation.name() == Some(annotations::SETTINGS))
1677        .find_map(|annotation| {
1678            annotation
1679                .properties
1680                .as_deref()
1681                .unwrap_or_default()
1682                .iter()
1683                .rev()
1684                .find(|property| &*property.inner.key.name == annotations::SETTINGS_VERSION)
1685        })
1686    else {
1687        return Ok(None);
1688    };
1689    let value = annotations::expect_kcl_version(&property.inner.value)?;
1690    let version = value.parse::<KclVersion>().map_err(|err| {
1691        KclError::new_semantic(KclErrorDetails::new(err.to_string(), vec![property.as_source_range()]))
1692    })?;
1693    Ok(Some((version, property.as_source_range())))
1694}
1695
1696impl GlobalState {
1697    fn new(settings: &ExecutorSettings, segment_ids_edited: AhashIndexSet<ObjectId>) -> Self {
1698        let mut global = GlobalState {
1699            machine_depth_high_water: 0,
1700            path_to_source_id: Default::default(),
1701            module_infos: Default::default(),
1702            never_type_ranges: Default::default(),
1703            artifacts: Default::default(),
1704            root_module_artifacts: Default::default(),
1705            mod_loader: Default::default(),
1706            issues: Default::default(),
1707            deprecation_version_override: None,
1708            entry_point_kcl_version: None,
1709            id_to_source: Default::default(),
1710            segment_ids_edited,
1711            drag_anchors: Vec::new(),
1712            sketch_mode: false,
1713            geometry_only: settings.geometry_only,
1714            std_not_yet_added: Default::default(),
1715            #[cfg(test)]
1716            hint_all_not_yet_added: false,
1717        };
1718
1719        let root_id = ModuleId::default();
1720        let root_path = settings.current_file.clone().unwrap_or_default();
1721        global.module_infos.insert(
1722            root_id,
1723            ModuleInfo {
1724                id: root_id,
1725                path: ModulePath::Local {
1726                    value: root_path.clone(),
1727                    original_import_path: None,
1728                },
1729                repr: ModuleRepr::Root,
1730            },
1731        );
1732        global.path_to_source_id.insert(
1733            ModulePath::Local {
1734                value: root_path,
1735                original_import_path: None,
1736            },
1737            root_id,
1738        );
1739        global
1740    }
1741
1742    pub(super) fn filenames(&self) -> IndexMap<ModuleId, ModulePath> {
1743        self.path_to_source_id.iter().map(|(k, v)| ((*v), k.clone())).collect()
1744    }
1745
1746    pub(super) fn get_source(&self, id: ModuleId) -> Option<&ModuleSource> {
1747        self.id_to_source.get(&id)
1748    }
1749}
1750
1751impl ArtifactState {
1752    pub fn cached_body_items(&self) -> usize {
1753        self.graph.item_count()
1754    }
1755
1756    pub(crate) fn clear(&mut self) {
1757        self.artifacts.clear();
1758        self.graph.clear();
1759    }
1760}
1761
1762impl ModuleArtifactState {
1763    pub fn legacy_angle_refactor_metadata(&self) -> Vec<LegacyAngleRefactorMeta> {
1764        self.refactor_metadata
1765            .iter()
1766            .filter_map(|metadata| match metadata {
1767                RefactorMetadata::LegacyAngle(metadata) => Some(*metadata),
1768                RefactorMetadata::EdgeRefactor(_) | RefactorMetadata::DirectTagFillet(_) => None,
1769            })
1770            .collect()
1771    }
1772
1773    pub(crate) fn clear(&mut self) {
1774        self.artifacts.clear();
1775        self.unprocessed_commands.clear();
1776        self.commands.clear();
1777        self.operations.clear();
1778        self.refactor_metadata.clear();
1779    }
1780
1781    pub(crate) fn restore_scene_objects(&mut self, scene_objects: &[Object]) {
1782        self.scene_objects = scene_objects.to_vec();
1783        self.object_id_generator = IncIdGenerator::new(self.scene_objects.len());
1784        self.source_range_to_object.clear();
1785        self.artifact_id_to_scene_object.clear();
1786
1787        for (expected_id, object) in self.scene_objects.iter().enumerate() {
1788            debug_assert_eq!(
1789                object.id.0, expected_id,
1790                "Restored cached scene object ID {} does not match its position {}",
1791                object.id.0, expected_id
1792            );
1793
1794            match &object.kind {
1795                ObjectKind::Wall(wall) => {
1796                    self.source_range_to_object.insert(wall.source.solid.range, object.id);
1797                }
1798                ObjectKind::Cap(cap) => {
1799                    self.source_range_to_object.insert(cap.source.solid.range, object.id);
1800                }
1801                _ => match &object.source {
1802                    crate::front::SourceRef::Simple { range, node_path: _ } => {
1803                        self.source_range_to_object.insert(*range, object.id);
1804                    }
1805                    crate::front::SourceRef::BackTrace { ranges } => {
1806                        // Don't map the entire backtrace, only the most specific
1807                        // range.
1808                        if let Some((range, _)) = ranges.first() {
1809                            self.source_range_to_object.insert(*range, object.id);
1810                        }
1811                    }
1812                },
1813            }
1814
1815            // Ignore placeholder artifacts.
1816            if object.artifact_id != ArtifactId::placeholder() {
1817                self.artifact_id_to_scene_object.insert(object.artifact_id, object.id);
1818            }
1819        }
1820    }
1821
1822    /// When self is a cached state, extend it with new state.
1823    pub(crate) fn extend(&mut self, other: ModuleArtifactState) {
1824        self.artifacts.extend(other.artifacts);
1825        self.unprocessed_commands.extend(other.unprocessed_commands);
1826        self.commands.extend(other.commands);
1827        self.operations.extend(other.operations);
1828        if other.scene_objects.len() > self.scene_objects.len() {
1829            self.scene_objects
1830                .extend(other.scene_objects[self.scene_objects.len()..].iter().cloned());
1831        }
1832        self.source_range_to_object.extend(other.source_range_to_object);
1833        self.artifact_id_to_scene_object
1834            .extend(other.artifact_id_to_scene_object);
1835        self.var_solutions.extend(other.var_solutions);
1836        self.refactor_metadata.extend(other.refactor_metadata);
1837    }
1838
1839    // Move unprocessed artifact commands so that we don't try to process them
1840    // again next time due to execution caching.  Returns a clone of the
1841    // commands that were moved.
1842    pub(crate) fn process_commands(&mut self) -> Vec<ArtifactCommand> {
1843        let unprocessed = std::mem::take(&mut self.unprocessed_commands);
1844        let new_module_commands = unprocessed.clone();
1845        self.commands.extend(unprocessed);
1846        new_module_commands
1847    }
1848
1849    pub(crate) fn scene_object_by_id(&self, id: ObjectId) -> Option<&Object> {
1850        debug_assert!(
1851            id.0 < self.scene_objects.len(),
1852            "Requested object ID {} but only have {} objects",
1853            id.0,
1854            self.scene_objects.len()
1855        );
1856        self.scene_objects.get(id.0)
1857    }
1858
1859    pub(crate) fn scene_object_by_id_mut(&mut self, id: ObjectId) -> Option<&mut Object> {
1860        debug_assert!(
1861            id.0 < self.scene_objects.len(),
1862            "Requested object ID {} but only have {} objects",
1863            id.0,
1864            self.scene_objects.len()
1865        );
1866        self.scene_objects.get_mut(id.0)
1867    }
1868}
1869
1870impl ModuleState {
1871    pub(super) fn new(
1872        path: ModulePath,
1873        memory: Arc<ProgramMemory>,
1874        module_id: Option<ModuleId>,
1875        sketch_mode: bool,
1876        freedom_analysis: bool,
1877    ) -> Self {
1878        let state_module_id = module_id.unwrap_or_default();
1879        ModuleState {
1880            module_id: state_module_id,
1881            id_generator: IdGenerator::new(module_id),
1882            stack: memory.new_stack(),
1883            call_stack_size: 0,
1884            machine_call_depth: 0,
1885            pipe_value: Default::default(),
1886            being_declared: Default::default(),
1887            sketch_block: Default::default(),
1888            stdlib_entry_source_range: Default::default(),
1889            module_exports: Default::default(),
1890            not_yet_added: Default::default(),
1891            explicit_length_units: false,
1892            path,
1893            settings: Default::default(),
1894            sketch_mode,
1895            freedom_analysis,
1896            artifacts: Default::default(),
1897            constraint_state: Default::default(),
1898            allowed_warnings: Vec::new(),
1899            denied_warnings: Vec::new(),
1900            consumed_solids: AHashMap::default(),
1901            consumed_solid_ids: AHashMap::default(),
1902            consumed_regions: AHashMap::default(),
1903            inside_stdlib: false,
1904        }
1905    }
1906
1907    pub(super) fn variables(&self, main_ref: EnvironmentRef) -> Result<IndexMap<String, KclValue>, KclError> {
1908        self.stack.find_all_in_env_owned(main_ref)
1909    }
1910}
1911
1912impl SketchBlockState {
1913    pub(crate) fn next_sketch_var_id(&self) -> SketchVarId {
1914        SketchVarId(self.sketch_vars.len())
1915    }
1916
1917    /// Given a solve outcome, return the solutions for the sketch variables and
1918    /// enough information to update them in the source.
1919    pub(crate) fn var_solutions(
1920        &self,
1921        solve_outcome: &Solved,
1922        solution_ty: NumericType,
1923        sketch_block_range: SourceRange,
1924    ) -> Result<Vec<(SourceRange, Option<NodePath>, Number)>, KclError> {
1925        self.sketch_vars
1926            .iter()
1927            .map(|v| {
1928                let Some(sketch_var) = v.as_sketch_var() else {
1929                    return Err(KclError::new_internal(KclErrorDetails::new(
1930                        "Expected sketch variable".to_owned(),
1931                        vec![sketch_block_range],
1932                    )));
1933                };
1934                let var_index = sketch_var.id.0;
1935                let solved_n = solve_outcome.final_values.get(var_index).ok_or_else(|| {
1936                    let message = format!("No solution for sketch variable with id {}", var_index);
1937                    debug_assert!(false, "{}", &message);
1938                    KclError::new_internal(KclErrorDetails::new(
1939                        message,
1940                        sketch_var.meta.iter().map(|m| m.source_range).collect(),
1941                    ))
1942                })?;
1943                let solved_value = Number {
1944                    value: *solved_n,
1945                    units: solution_ty.try_into().map_err(|_| {
1946                        KclError::new_internal(KclErrorDetails::new(
1947                            "Failed to convert numeric type to units".to_owned(),
1948                            vec![sketch_block_range],
1949                        ))
1950                    })?,
1951                };
1952                let Some(source_range) = sketch_var.meta.first().map(|m| m.source_range) else {
1953                    return Ok(None);
1954                };
1955                Ok(Some((source_range, sketch_var.node_path.clone(), solved_value)))
1956            })
1957            .filter_map(Result::transpose)
1958            .collect::<Result<Vec<_>, KclError>>()
1959    }
1960}
1961
1962#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, ts_rs::TS)]
1963#[ts(export)]
1964#[serde(rename_all = "camelCase")]
1965pub struct MetaSettings {
1966    pub default_length_units: UnitLength,
1967    pub default_angle_units: UnitAngle,
1968    pub experimental_features: annotations::WarningLevel,
1969    pub kcl_version: KclVersion,
1970}
1971
1972impl Default for MetaSettings {
1973    fn default() -> Self {
1974        MetaSettings {
1975            default_length_units: UnitLength::Millimeters,
1976            default_angle_units: UnitAngle::Degrees,
1977            experimental_features: annotations::WarningLevel::Deny,
1978            kcl_version: KclVersion::default(),
1979        }
1980    }
1981}
1982
1983impl MetaSettings {
1984    pub(crate) fn update_from_annotation(
1985        &mut self,
1986        annotation: &crate::parsing::ast::types::Node<Annotation>,
1987    ) -> Result<(bool, bool), KclError> {
1988        let properties = annotations::expect_properties(annotations::SETTINGS, annotation)?;
1989
1990        let mut updated_len = false;
1991        let mut updated_angle = false;
1992        for p in properties {
1993            match &*p.inner.key.name {
1994                annotations::SETTINGS_UNIT_LENGTH => {
1995                    let value = annotations::expect_ident(&p.inner.value)?;
1996                    let value = super::types::length_from_str(value, annotation.as_source_range())?;
1997                    self.default_length_units = value;
1998                    updated_len = true;
1999                }
2000                annotations::SETTINGS_UNIT_ANGLE => {
2001                    let value = annotations::expect_ident(&p.inner.value)?;
2002                    let value = super::types::angle_from_str(value, annotation.as_source_range())?;
2003                    self.default_angle_units = value;
2004                    updated_angle = true;
2005                }
2006                annotations::SETTINGS_VERSION => {
2007                    let value = annotations::expect_kcl_version(&p.inner.value)?;
2008                    self.kcl_version = value.parse()?;
2009                }
2010                annotations::SETTINGS_EXPERIMENTAL_FEATURES => {
2011                    let value = annotations::expect_ident(&p.inner.value)?;
2012                    let value = annotations::WarningLevel::from_str(value).map_err(|_| {
2013                        KclError::new_semantic(KclErrorDetails::new(
2014                            format!(
2015                                "Invalid value for {} settings property, expected one of: {}",
2016                                annotations::SETTINGS_EXPERIMENTAL_FEATURES,
2017                                annotations::WARN_LEVELS.join(", ")
2018                            ),
2019                            annotation.as_source_ranges(),
2020                        ))
2021                    })?;
2022                    self.experimental_features = value;
2023                }
2024                name => {
2025                    return Err(KclError::new_semantic(KclErrorDetails::new(
2026                        format!(
2027                            "Unexpected settings key: `{name}`; expected one of `{}`, `{}`",
2028                            annotations::SETTINGS_UNIT_LENGTH,
2029                            annotations::SETTINGS_UNIT_ANGLE
2030                        ),
2031                        vec![annotation.as_source_range()],
2032                    )));
2033                }
2034            }
2035        }
2036
2037        Ok((updated_len, updated_angle))
2038    }
2039}
2040
2041#[cfg(test)]
2042mod tests {
2043
2044    use uuid::Uuid;
2045
2046    use super::KclVersion;
2047    use super::ModuleArtifactState;
2048    use crate::NodePath;
2049    use crate::NodePathExt;
2050    use crate::SourceRange;
2051    use crate::execution::ArtifactId;
2052    use crate::front::Object;
2053    use crate::front::ObjectId;
2054    use crate::front::ObjectKind;
2055    use crate::front::Plane;
2056    use crate::front::SourceRef;
2057
2058    #[test]
2059    fn declared_kcl_version_finds_the_setting_and_its_range() {
2060        let parse = |code: &str| crate::parsing::top_level_parse(code).unwrap();
2061
2062        assert_eq!(super::declared_kcl_version(&parse("x = 1\n")).unwrap(), None);
2063        assert_eq!(
2064            super::declared_kcl_version(&parse("@settings(defaultLengthUnit = in)\nx = 1\n")).unwrap(),
2065            None
2066        );
2067
2068        let code = "@settings(defaultLengthUnit = in, kclVersion = 2.0)\nx = 1\n";
2069        let (version, range) = super::declared_kcl_version(&parse(code)).unwrap().unwrap();
2070        assert_eq!(version, KclVersion::V2);
2071        let start = code.find("kclVersion").unwrap();
2072        assert_eq!((range.start(), range.end()), (start, start + "kclVersion = 2.0".len()));
2073
2074        let (version, _) = super::declared_kcl_version(&parse("@settings(kclVersion = \"3.0-preview\")\n"))
2075            .unwrap()
2076            .unwrap();
2077        assert_eq!(version, KclVersion::V3Preview);
2078
2079        // The last declaration wins, whether it is in a later annotation or
2080        // later within the same annotation.
2081        let code = "@settings(kclVersion = 1.0)\n@settings(defaultLengthUnit = in)\n@settings(kclVersion = 2.0, kclVersion = \"3.0-preview\")\n";
2082        let (version, range) = super::declared_kcl_version(&parse(code)).unwrap().unwrap();
2083        assert_eq!(version, KclVersion::V3Preview);
2084        let start = code.rfind("kclVersion").unwrap();
2085        assert_eq!(
2086            (range.start(), range.end()),
2087            (start, start + "kclVersion = \"3.0-preview\"".len())
2088        );
2089
2090        // An unknown version is an error located at the setting.
2091        let code = "@settings(kclVersion = 9.0)\n";
2092        let error = super::declared_kcl_version(&parse(code)).unwrap_err();
2093        let start = code.find("kclVersion").unwrap();
2094        assert_eq!(
2095            error.source_ranges().first().map(|range| (range.start(), range.end())),
2096            Some((start, start + "kclVersion = 9.0".len()))
2097        );
2098    }
2099
2100    #[test]
2101    fn kcl_version_serializes_as_canonical_setting_value() {
2102        assert_eq!(serde_json::to_string(&KclVersion::V1).unwrap(), r#""1.0""#);
2103        assert_eq!(serde_json::to_string(&KclVersion::V2).unwrap(), r#""2.0""#);
2104        assert_eq!(
2105            serde_json::to_string(&KclVersion::V3Preview).unwrap(),
2106            r#""3.0-preview""#
2107        );
2108    }
2109
2110    #[test]
2111    fn restore_scene_objects_rebuilds_lookup_maps() {
2112        let plane_artifact_id = ArtifactId::new(Uuid::from_u128(1));
2113        let sketch_artifact_id = ArtifactId::new(Uuid::from_u128(2));
2114        let plane_range = SourceRange::from([1, 4, 0]);
2115        let plane_node_path = Some(NodePath::placeholder());
2116        let sketch_ranges = vec![
2117            (SourceRange::from([5, 9, 0]), None),
2118            (SourceRange::from([10, 12, 0]), None),
2119        ];
2120        let cached_objects = vec![
2121            Object {
2122                id: ObjectId(0),
2123                kind: ObjectKind::Plane(Plane::Object(ObjectId(0))),
2124                label: Default::default(),
2125                comments: Default::default(),
2126                artifact_id: plane_artifact_id,
2127                source: SourceRef::new(plane_range, plane_node_path),
2128            },
2129            Object {
2130                id: ObjectId(1),
2131                kind: ObjectKind::Nil,
2132                label: Default::default(),
2133                comments: Default::default(),
2134                artifact_id: sketch_artifact_id,
2135                source: SourceRef::BackTrace {
2136                    ranges: sketch_ranges.clone(),
2137                },
2138            },
2139            Object::placeholder(ObjectId(2), SourceRange::from([13, 14, 0]), None),
2140        ];
2141
2142        let mut artifacts = ModuleArtifactState::default();
2143        artifacts.restore_scene_objects(&cached_objects);
2144
2145        assert_eq!(artifacts.scene_objects, cached_objects);
2146        assert_eq!(
2147            artifacts.artifact_id_to_scene_object.get(&plane_artifact_id),
2148            Some(&ObjectId(0))
2149        );
2150        assert_eq!(
2151            artifacts.artifact_id_to_scene_object.get(&sketch_artifact_id),
2152            Some(&ObjectId(1))
2153        );
2154        assert_eq!(
2155            artifacts.artifact_id_to_scene_object.get(&ArtifactId::placeholder()),
2156            None
2157        );
2158        assert_eq!(artifacts.source_range_to_object.get(&plane_range), Some(&ObjectId(0)));
2159        assert_eq!(
2160            artifacts.source_range_to_object.get(&sketch_ranges[0].0),
2161            Some(&ObjectId(1))
2162        );
2163        // We don't map all the ranges in a backtrace.
2164        assert_eq!(artifacts.source_range_to_object.get(&sketch_ranges[1].0), None);
2165    }
2166}