1#[cfg(feature = "artifact-graph")]
2use std::collections::BTreeMap;
3use std::{str::FromStr, sync::Arc};
4
5use anyhow::Result;
6use indexmap::IndexMap;
7use kittycad_modeling_cmds::units::{UnitAngle, UnitLength};
8use serde::{Deserialize, Serialize};
9use uuid::Uuid;
10
11use crate::{
12 CompilationError, EngineManager, ExecutorContext, KclErrorWithOutputs, MockConfig, SourceRange,
13 collections::AhashIndexSet,
14 errors::{KclError, KclErrorDetails, Severity},
15 exec::DefaultPlanes,
16 execution::{
17 EnvironmentRef, ExecOutcome, ExecutorSettings, KclValue, SketchVarId, UnsolvedSegment, annotations,
18 cad_op::Operation,
19 id_generator::IdGenerator,
20 memory::{ProgramMemory, Stack},
21 types::NumericType,
22 },
23 front::ObjectId,
24 modules::{ModuleId, ModuleInfo, ModuleLoader, ModulePath, ModuleRepr, ModuleSource},
25 parsing::ast::types::{Annotation, NodeRef},
26};
27#[cfg(feature = "artifact-graph")]
28use crate::{
29 execution::{Artifact, ArtifactCommand, ArtifactGraph, ArtifactId, ProgramLookup},
30 front::{Number, Object},
31 id::IncIdGenerator,
32};
33
34#[derive(Debug, Clone)]
36pub struct ExecState {
37 pub(super) global: GlobalState,
38 pub(super) mod_local: ModuleState,
39}
40
41pub type ModuleInfoMap = IndexMap<ModuleId, ModuleInfo>;
42
43#[derive(Debug, Clone)]
44pub(super) struct GlobalState {
45 pub path_to_source_id: IndexMap<ModulePath, ModuleId>,
47 pub id_to_source: IndexMap<ModuleId, ModuleSource>,
49 pub module_infos: ModuleInfoMap,
51 pub mod_loader: ModuleLoader,
53 pub errors: Vec<CompilationError>,
55 pub artifacts: ArtifactState,
57 pub root_module_artifacts: ModuleArtifactState,
59 #[cfg(feature = "artifact-graph")]
61 pub segment_ids_edited: AhashIndexSet<ObjectId>,
62}
63
64#[cfg(feature = "artifact-graph")]
65#[derive(Debug, Clone, Default)]
66pub(super) struct ArtifactState {
67 pub artifacts: IndexMap<ArtifactId, Artifact>,
70 pub graph: ArtifactGraph,
72}
73
74#[cfg(not(feature = "artifact-graph"))]
75#[derive(Debug, Clone, Default)]
76pub(super) struct ArtifactState {}
77
78#[cfg(feature = "artifact-graph")]
80#[derive(Debug, Clone, Default, PartialEq, Serialize)]
81pub struct ModuleArtifactState {
82 pub artifacts: IndexMap<ArtifactId, Artifact>,
84 #[serde(skip)]
87 pub unprocessed_commands: Vec<ArtifactCommand>,
88 pub commands: Vec<ArtifactCommand>,
90 pub operations: Vec<Operation>,
93 pub object_id_generator: IncIdGenerator<usize>,
95 pub scene_objects: Vec<Object>,
97 pub source_range_to_object: BTreeMap<SourceRange, ObjectId>,
100 pub var_solutions: Vec<(SourceRange, Number)>,
102}
103
104#[cfg(not(feature = "artifact-graph"))]
105#[derive(Debug, Clone, Default, PartialEq, Serialize)]
106pub struct ModuleArtifactState {}
107
108#[derive(Debug, Clone)]
109pub(super) struct ModuleState {
110 pub id_generator: IdGenerator,
112 pub stack: Stack,
113 pub pipe_value: Option<KclValue>,
116 pub being_declared: Option<String>,
120 pub sketch_block: Option<SketchBlockState>,
122 pub inside_stdlib: bool,
125 pub stdlib_entry_source_range: Option<SourceRange>,
127 pub module_exports: Vec<String>,
129 pub settings: MetaSettings,
131 pub freedom_analysis: bool,
134 pub(super) explicit_length_units: bool,
135 pub(super) path: ModulePath,
136 pub artifacts: ModuleArtifactState,
138
139 pub(super) allowed_warnings: Vec<&'static str>,
140 pub(super) denied_warnings: Vec<&'static str>,
141}
142
143#[derive(Debug, Clone, Default)]
144pub(crate) struct SketchBlockState {
145 pub sketch_vars: Vec<KclValue>,
146 #[cfg(feature = "artifact-graph")]
147 pub sketch_constraints: Vec<ObjectId>,
148 pub solver_constraints: Vec<kcl_ezpz::Constraint>,
149 pub solver_optional_constraints: Vec<kcl_ezpz::Constraint>,
150 pub needed_by_engine: Vec<UnsolvedSegment>,
151}
152
153impl ExecState {
154 pub fn new(exec_context: &super::ExecutorContext) -> Self {
155 ExecState {
156 global: GlobalState::new(&exec_context.settings, Default::default()),
157 mod_local: ModuleState::new(ModulePath::Main, ProgramMemory::new(), Default::default(), 0, false),
158 }
159 }
160
161 pub fn new_sketch_mode(exec_context: &super::ExecutorContext, mock_config: &MockConfig) -> Self {
162 #[cfg(feature = "artifact-graph")]
163 let segment_ids_edited = mock_config.segment_ids_edited.clone();
164 #[cfg(not(feature = "artifact-graph"))]
165 let segment_ids_edited = Default::default();
166 ExecState {
167 global: GlobalState::new(&exec_context.settings, segment_ids_edited),
168 mod_local: ModuleState::new(
169 ModulePath::Main,
170 ProgramMemory::new(),
171 Default::default(),
172 0,
173 mock_config.freedom_analysis,
174 ),
175 }
176 }
177
178 pub(super) fn reset(&mut self, exec_context: &super::ExecutorContext) {
179 let global = GlobalState::new(&exec_context.settings, Default::default());
180
181 *self = ExecState {
182 global,
183 mod_local: ModuleState::new(
184 self.mod_local.path.clone(),
185 ProgramMemory::new(),
186 Default::default(),
187 0,
188 false,
189 ),
190 };
191 }
192
193 pub fn err(&mut self, e: CompilationError) {
195 self.global.errors.push(e);
196 }
197
198 pub fn warn(&mut self, mut e: CompilationError, name: &'static str) {
200 debug_assert!(annotations::WARN_VALUES.contains(&name));
201
202 if self.mod_local.allowed_warnings.contains(&name) {
203 return;
204 }
205
206 if self.mod_local.denied_warnings.contains(&name) {
207 e.severity = Severity::Error;
208 } else {
209 e.severity = Severity::Warning;
210 }
211
212 self.global.errors.push(e);
213 }
214
215 pub fn warn_experimental(&mut self, feature_name: &str, source_range: SourceRange) {
216 let Some(severity) = self.mod_local.settings.experimental_features.severity() else {
217 return;
218 };
219 let error = CompilationError {
220 source_range,
221 message: format!("Use of {feature_name} is experimental and may change or be removed."),
222 suggestion: None,
223 severity,
224 tag: crate::errors::Tag::None,
225 };
226
227 self.global.errors.push(error);
228 }
229
230 pub fn clear_units_warnings(&mut self, source_range: &SourceRange) {
231 self.global.errors = std::mem::take(&mut self.global.errors)
232 .into_iter()
233 .filter(|e| {
234 e.severity != Severity::Warning
235 || !source_range.contains_range(&e.source_range)
236 || e.tag != crate::errors::Tag::UnknownNumericUnits
237 })
238 .collect();
239 }
240
241 pub fn errors(&self) -> &[CompilationError] {
242 &self.global.errors
243 }
244
245 pub async fn into_exec_outcome(self, main_ref: EnvironmentRef, ctx: &ExecutorContext) -> ExecOutcome {
249 ExecOutcome {
252 variables: self.mod_local.variables(main_ref),
253 filenames: self.global.filenames(),
254 #[cfg(feature = "artifact-graph")]
255 operations: self.global.root_module_artifacts.operations,
256 #[cfg(feature = "artifact-graph")]
257 artifact_graph: self.global.artifacts.graph,
258 #[cfg(feature = "artifact-graph")]
259 scene_objects: self.global.root_module_artifacts.scene_objects,
260 #[cfg(feature = "artifact-graph")]
261 source_range_to_object: self.global.root_module_artifacts.source_range_to_object,
262 #[cfg(feature = "artifact-graph")]
263 var_solutions: self.global.root_module_artifacts.var_solutions,
264 errors: self.global.errors,
265 default_planes: ctx.engine.get_default_planes().read().await.clone(),
266 }
267 }
268
269 pub(crate) fn stack(&self) -> &Stack {
270 &self.mod_local.stack
271 }
272
273 pub(crate) fn mut_stack(&mut self) -> &mut Stack {
274 &mut self.mod_local.stack
275 }
276
277 #[cfg(not(feature = "artifact-graph"))]
278 pub fn next_object_id(&mut self) -> ObjectId {
279 ObjectId(0)
282 }
283
284 #[cfg(feature = "artifact-graph")]
285 pub fn next_object_id(&mut self) -> ObjectId {
286 ObjectId(self.mod_local.artifacts.object_id_generator.next_id())
287 }
288
289 #[cfg(feature = "artifact-graph")]
290 pub fn add_scene_object(&mut self, obj: Object, source_range: SourceRange) -> ObjectId {
291 let id = obj.id;
292 debug_assert!(id.0 == self.mod_local.artifacts.scene_objects.len());
293 self.mod_local.artifacts.scene_objects.push(obj);
294 self.mod_local.artifacts.source_range_to_object.insert(source_range, id);
295 id
296 }
297
298 #[cfg(feature = "artifact-graph")]
301 pub fn add_placeholder_scene_object(&mut self, id: ObjectId, source_range: SourceRange) -> ObjectId {
302 debug_assert!(id.0 == self.mod_local.artifacts.scene_objects.len());
303 self.mod_local
304 .artifacts
305 .scene_objects
306 .push(Object::placeholder(id, source_range));
307 self.mod_local.artifacts.source_range_to_object.insert(source_range, id);
308 id
309 }
310
311 #[cfg(feature = "artifact-graph")]
313 pub fn set_scene_object(&mut self, object: Object) {
314 let id = object.id;
315 self.mod_local.artifacts.scene_objects[id.0] = object;
316 }
317
318 #[cfg(feature = "artifact-graph")]
319 pub fn segment_ids_edited_contains(&self, object_id: &ObjectId) -> bool {
320 self.global.segment_ids_edited.contains(object_id)
321 }
322
323 pub(crate) fn sketch_block_mut(&mut self) -> Option<&mut SketchBlockState> {
324 self.mod_local.sketch_block.as_mut()
325 }
326
327 pub fn next_uuid(&mut self) -> Uuid {
328 self.mod_local.id_generator.next_uuid()
329 }
330
331 #[cfg(feature = "artifact-graph")]
332 pub fn next_artifact_id(&mut self) -> ArtifactId {
333 self.mod_local.id_generator.next_artifact_id()
334 }
335
336 pub fn id_generator(&mut self) -> &mut IdGenerator {
337 &mut self.mod_local.id_generator
338 }
339
340 #[cfg(feature = "artifact-graph")]
341 pub(crate) fn add_artifact(&mut self, artifact: Artifact) {
342 let id = artifact.id();
343 self.mod_local.artifacts.artifacts.insert(id, artifact);
344 }
345
346 pub(crate) fn push_op(&mut self, op: Operation) {
347 #[cfg(feature = "artifact-graph")]
348 self.mod_local.artifacts.operations.push(op);
349 #[cfg(not(feature = "artifact-graph"))]
350 drop(op);
351 }
352
353 #[cfg(feature = "artifact-graph")]
354 pub(crate) fn push_command(&mut self, command: ArtifactCommand) {
355 self.mod_local.artifacts.unprocessed_commands.push(command);
356 #[cfg(not(feature = "artifact-graph"))]
357 drop(command);
358 }
359
360 pub(super) fn next_module_id(&self) -> ModuleId {
361 ModuleId::from_usize(self.global.path_to_source_id.len())
362 }
363
364 pub(super) fn id_for_module(&self, path: &ModulePath) -> Option<ModuleId> {
365 self.global.path_to_source_id.get(path).cloned()
366 }
367
368 pub(super) fn add_path_to_source_id(&mut self, path: ModulePath, id: ModuleId) {
369 debug_assert!(!self.global.path_to_source_id.contains_key(&path));
370 self.global.path_to_source_id.insert(path, id);
371 }
372
373 pub(crate) fn add_root_module_contents(&mut self, program: &crate::Program) {
374 let root_id = ModuleId::default();
375 let path = self
377 .global
378 .path_to_source_id
379 .iter()
380 .find(|(_, v)| **v == root_id)
381 .unwrap()
382 .0
383 .clone();
384 self.add_id_to_source(
385 root_id,
386 ModuleSource {
387 path,
388 source: program.original_file_contents.to_string(),
389 },
390 );
391 }
392
393 pub(super) fn add_id_to_source(&mut self, id: ModuleId, source: ModuleSource) {
394 self.global.id_to_source.insert(id, source);
395 }
396
397 pub(super) fn add_module(&mut self, id: ModuleId, path: ModulePath, repr: ModuleRepr) {
398 debug_assert!(self.global.path_to_source_id.contains_key(&path));
399 let module_info = ModuleInfo { id, repr, path };
400 self.global.module_infos.insert(id, module_info);
401 }
402
403 pub fn get_module(&mut self, id: ModuleId) -> Option<&ModuleInfo> {
404 self.global.module_infos.get(&id)
405 }
406
407 #[cfg(all(test, feature = "artifact-graph"))]
408 pub(crate) fn modules(&self) -> &ModuleInfoMap {
409 &self.global.module_infos
410 }
411
412 #[cfg(all(test, feature = "artifact-graph"))]
413 pub(crate) fn root_module_artifact_state(&self) -> &ModuleArtifactState {
414 &self.global.root_module_artifacts
415 }
416
417 pub fn current_default_units(&self) -> NumericType {
418 NumericType::Default {
419 len: self.length_unit(),
420 angle: self.angle_unit(),
421 }
422 }
423
424 pub fn length_unit(&self) -> UnitLength {
425 self.mod_local.settings.default_length_units
426 }
427
428 pub fn angle_unit(&self) -> UnitAngle {
429 self.mod_local.settings.default_angle_units
430 }
431
432 pub(super) fn circular_import_error(&self, path: &ModulePath, source_range: SourceRange) -> KclError {
433 KclError::new_import_cycle(KclErrorDetails::new(
434 format!(
435 "circular import of modules is not allowed: {} -> {}",
436 self.global
437 .mod_loader
438 .import_stack
439 .iter()
440 .map(|p| p.to_string_lossy())
441 .collect::<Vec<_>>()
442 .join(" -> "),
443 path,
444 ),
445 vec![source_range],
446 ))
447 }
448
449 pub(crate) fn pipe_value(&self) -> Option<&KclValue> {
450 self.mod_local.pipe_value.as_ref()
451 }
452
453 pub(crate) fn error_with_outputs(
454 &self,
455 error: KclError,
456 main_ref: Option<EnvironmentRef>,
457 default_planes: Option<DefaultPlanes>,
458 ) -> KclErrorWithOutputs {
459 let module_id_to_module_path: IndexMap<ModuleId, ModulePath> = self
460 .global
461 .path_to_source_id
462 .iter()
463 .map(|(k, v)| ((*v), k.clone()))
464 .collect();
465
466 KclErrorWithOutputs::new(
467 error,
468 self.errors().to_vec(),
469 main_ref
470 .map(|main_ref| self.mod_local.variables(main_ref))
471 .unwrap_or_default(),
472 #[cfg(feature = "artifact-graph")]
473 self.global.root_module_artifacts.operations.clone(),
474 #[cfg(feature = "artifact-graph")]
475 Default::default(),
476 #[cfg(feature = "artifact-graph")]
477 self.global.artifacts.graph.clone(),
478 module_id_to_module_path,
479 self.global.id_to_source.clone(),
480 default_planes,
481 )
482 }
483
484 #[cfg(feature = "artifact-graph")]
485 pub(crate) fn build_program_lookup(
486 &self,
487 current: crate::parsing::ast::types::Node<crate::parsing::ast::types::Program>,
488 ) -> ProgramLookup {
489 ProgramLookup::new(current, self.global.module_infos.clone())
490 }
491
492 #[cfg(feature = "artifact-graph")]
493 pub(crate) async fn build_artifact_graph(
494 &mut self,
495 engine: &Arc<Box<dyn EngineManager>>,
496 program: NodeRef<'_, crate::parsing::ast::types::Program>,
497 ) -> Result<(), KclError> {
498 let mut new_commands = Vec::new();
499 let mut new_exec_artifacts = IndexMap::new();
500 for module in self.global.module_infos.values_mut() {
501 match &mut module.repr {
502 ModuleRepr::Kcl(_, Some(outcome)) => {
503 new_commands.extend(outcome.artifacts.process_commands());
504 new_exec_artifacts.extend(outcome.artifacts.artifacts.clone());
505 }
506 ModuleRepr::Foreign(_, Some((_, module_artifacts))) => {
507 new_commands.extend(module_artifacts.process_commands());
508 new_exec_artifacts.extend(module_artifacts.artifacts.clone());
509 }
510 ModuleRepr::Root | ModuleRepr::Kcl(_, None) | ModuleRepr::Foreign(_, None) | ModuleRepr::Dummy => {}
511 }
512 }
513 new_commands.extend(self.global.root_module_artifacts.process_commands());
516 new_exec_artifacts.extend(self.global.root_module_artifacts.artifacts.clone());
519 let new_responses = engine.take_responses().await;
520
521 self.global.artifacts.artifacts.extend(new_exec_artifacts);
524
525 let initial_graph = self.global.artifacts.graph.clone();
526
527 let programs = self.build_program_lookup(program.clone());
529 let graph_result = crate::execution::artifact::build_artifact_graph(
530 &new_commands,
531 &new_responses,
532 program,
533 &mut self.global.artifacts.artifacts,
534 initial_graph,
535 &programs,
536 );
537
538 let artifact_graph = graph_result?;
539 self.global.artifacts.graph = artifact_graph;
540
541 Ok(())
542 }
543
544 #[cfg(not(feature = "artifact-graph"))]
545 pub(crate) async fn build_artifact_graph(
546 &mut self,
547 _engine: &Arc<Box<dyn EngineManager>>,
548 _program: NodeRef<'_, crate::parsing::ast::types::Program>,
549 ) -> Result<(), KclError> {
550 Ok(())
551 }
552}
553
554impl GlobalState {
555 fn new(settings: &ExecutorSettings, segment_ids_edited: AhashIndexSet<ObjectId>) -> Self {
556 #[cfg(not(feature = "artifact-graph"))]
557 drop(segment_ids_edited);
558 let mut global = GlobalState {
559 path_to_source_id: Default::default(),
560 module_infos: Default::default(),
561 artifacts: Default::default(),
562 root_module_artifacts: Default::default(),
563 mod_loader: Default::default(),
564 errors: Default::default(),
565 id_to_source: Default::default(),
566 #[cfg(feature = "artifact-graph")]
567 segment_ids_edited,
568 };
569
570 let root_id = ModuleId::default();
571 let root_path = settings.current_file.clone().unwrap_or_default();
572 global.module_infos.insert(
573 root_id,
574 ModuleInfo {
575 id: root_id,
576 path: ModulePath::Local {
577 value: root_path.clone(),
578 original_import_path: None,
579 },
580 repr: ModuleRepr::Root,
581 },
582 );
583 global.path_to_source_id.insert(
584 ModulePath::Local {
585 value: root_path,
586 original_import_path: None,
587 },
588 root_id,
589 );
590 global
591 }
592
593 pub(super) fn filenames(&self) -> IndexMap<ModuleId, ModulePath> {
594 self.path_to_source_id.iter().map(|(k, v)| ((*v), k.clone())).collect()
595 }
596
597 pub(super) fn get_source(&self, id: ModuleId) -> Option<&ModuleSource> {
598 self.id_to_source.get(&id)
599 }
600}
601
602impl ArtifactState {
603 #[cfg(feature = "artifact-graph")]
604 pub fn cached_body_items(&self) -> usize {
605 self.graph.item_count
606 }
607
608 pub(crate) fn clear(&mut self) {
609 #[cfg(feature = "artifact-graph")]
610 {
611 self.artifacts.clear();
612 self.graph.clear();
613 }
614 }
615}
616
617impl ModuleArtifactState {
618 pub(crate) fn clear(&mut self) {
619 #[cfg(feature = "artifact-graph")]
620 {
621 self.artifacts.clear();
622 self.unprocessed_commands.clear();
623 self.commands.clear();
624 self.operations.clear();
625 }
626 }
627
628 #[cfg(not(feature = "artifact-graph"))]
629 pub(crate) fn extend(&mut self, _other: ModuleArtifactState) {}
630
631 #[cfg(feature = "artifact-graph")]
633 pub(crate) fn extend(&mut self, other: ModuleArtifactState) {
634 self.artifacts.extend(other.artifacts);
635 self.unprocessed_commands.extend(other.unprocessed_commands);
636 self.commands.extend(other.commands);
637 self.operations.extend(other.operations);
638 self.scene_objects.extend(other.scene_objects);
639 self.source_range_to_object.extend(other.source_range_to_object);
640 self.var_solutions.extend(other.var_solutions);
641 }
642
643 #[cfg(feature = "artifact-graph")]
647 pub(crate) fn process_commands(&mut self) -> Vec<ArtifactCommand> {
648 let unprocessed = std::mem::take(&mut self.unprocessed_commands);
649 let new_module_commands = unprocessed.clone();
650 self.commands.extend(unprocessed);
651 new_module_commands
652 }
653}
654
655impl ModuleState {
656 pub(super) fn new(
657 path: ModulePath,
658 memory: Arc<ProgramMemory>,
659 module_id: Option<ModuleId>,
660 next_object_id: usize,
661 freedom_analysis: bool,
662 ) -> Self {
663 #[cfg(not(feature = "artifact-graph"))]
664 let _ = next_object_id;
665 ModuleState {
666 id_generator: IdGenerator::new(module_id),
667 stack: memory.new_stack(),
668 pipe_value: Default::default(),
669 being_declared: Default::default(),
670 sketch_block: Default::default(),
671 stdlib_entry_source_range: Default::default(),
672 module_exports: Default::default(),
673 explicit_length_units: false,
674 path,
675 settings: Default::default(),
676 freedom_analysis,
677 #[cfg(not(feature = "artifact-graph"))]
678 artifacts: Default::default(),
679 #[cfg(feature = "artifact-graph")]
680 artifacts: ModuleArtifactState {
681 object_id_generator: IncIdGenerator::new(next_object_id),
682 ..Default::default()
683 },
684 allowed_warnings: Vec::new(),
685 denied_warnings: Vec::new(),
686 inside_stdlib: false,
687 }
688 }
689
690 pub(super) fn variables(&self, main_ref: EnvironmentRef) -> IndexMap<String, KclValue> {
691 self.stack
692 .find_all_in_env(main_ref)
693 .map(|(k, v)| (k.clone(), v.clone()))
694 .collect()
695 }
696}
697
698impl SketchBlockState {
699 pub(crate) fn next_sketch_var_id(&self) -> SketchVarId {
700 SketchVarId(self.sketch_vars.len())
701 }
702
703 #[cfg(feature = "artifact-graph")]
706 pub(crate) fn var_solutions(
707 &self,
708 solve_outcome: kcl_ezpz::SolveOutcome,
709 solution_ty: NumericType,
710 range: SourceRange,
711 ) -> Result<Vec<(SourceRange, Number)>, KclError> {
712 self.sketch_vars
713 .iter()
714 .map(|v| {
715 let Some(sketch_var) = v.as_sketch_var() else {
716 return Err(KclError::new_internal(KclErrorDetails::new(
717 "Expected sketch variable".to_owned(),
718 vec![range],
719 )));
720 };
721 let var_index = sketch_var.id.0;
722 let solved_n = solve_outcome.final_values.get(var_index).ok_or_else(|| {
723 let message = format!("No solution for sketch variable with id {}", var_index);
724 debug_assert!(false, "{}", &message);
725 KclError::new_internal(KclErrorDetails::new(
726 message,
727 sketch_var.meta.iter().map(|m| m.source_range).collect(),
728 ))
729 })?;
730 let solved_value = Number {
731 value: *solved_n,
732 units: solution_ty.try_into().map_err(|_| {
733 KclError::new_internal(KclErrorDetails::new(
734 "Failed to convert numeric type to units".to_owned(),
735 vec![range],
736 ))
737 })?,
738 };
739 let Some(source_range) = sketch_var.meta.first().map(|m| m.source_range) else {
740 return Ok(None);
741 };
742 Ok(Some((source_range, solved_value)))
743 })
744 .filter_map(Result::transpose)
745 .collect::<Result<Vec<_>, KclError>>()
746 }
747}
748
749#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, ts_rs::TS)]
750#[ts(export)]
751#[serde(rename_all = "camelCase")]
752pub struct MetaSettings {
753 pub default_length_units: UnitLength,
754 pub default_angle_units: UnitAngle,
755 pub experimental_features: annotations::WarningLevel,
756 pub kcl_version: String,
757}
758
759impl Default for MetaSettings {
760 fn default() -> Self {
761 MetaSettings {
762 default_length_units: UnitLength::Millimeters,
763 default_angle_units: UnitAngle::Degrees,
764 experimental_features: annotations::WarningLevel::Deny,
765 kcl_version: "1.0".to_owned(),
766 }
767 }
768}
769
770impl MetaSettings {
771 pub(crate) fn update_from_annotation(
772 &mut self,
773 annotation: &crate::parsing::ast::types::Node<Annotation>,
774 ) -> Result<(bool, bool), KclError> {
775 let properties = annotations::expect_properties(annotations::SETTINGS, annotation)?;
776
777 let mut updated_len = false;
778 let mut updated_angle = false;
779 for p in properties {
780 match &*p.inner.key.name {
781 annotations::SETTINGS_UNIT_LENGTH => {
782 let value = annotations::expect_ident(&p.inner.value)?;
783 let value = super::types::length_from_str(value, annotation.as_source_range())?;
784 self.default_length_units = value;
785 updated_len = true;
786 }
787 annotations::SETTINGS_UNIT_ANGLE => {
788 let value = annotations::expect_ident(&p.inner.value)?;
789 let value = super::types::angle_from_str(value, annotation.as_source_range())?;
790 self.default_angle_units = value;
791 updated_angle = true;
792 }
793 annotations::SETTINGS_VERSION => {
794 let value = annotations::expect_number(&p.inner.value)?;
795 self.kcl_version = value;
796 }
797 annotations::SETTINGS_EXPERIMENTAL_FEATURES => {
798 let value = annotations::expect_ident(&p.inner.value)?;
799 let value = annotations::WarningLevel::from_str(value).map_err(|_| {
800 KclError::new_semantic(KclErrorDetails::new(
801 format!(
802 "Invalid value for {} settings property, expected one of: {}",
803 annotations::SETTINGS_EXPERIMENTAL_FEATURES,
804 annotations::WARN_LEVELS.join(", ")
805 ),
806 annotation.as_source_ranges(),
807 ))
808 })?;
809 self.experimental_features = value;
810 }
811 name => {
812 return Err(KclError::new_semantic(KclErrorDetails::new(
813 format!(
814 "Unexpected settings key: `{name}`; expected one of `{}`, `{}`",
815 annotations::SETTINGS_UNIT_LENGTH,
816 annotations::SETTINGS_UNIT_ANGLE
817 ),
818 vec![annotation.as_source_range()],
819 )));
820 }
821 }
822 }
823
824 Ok((updated_len, updated_angle))
825 }
826}