1use std::collections::HashMap;
2use std::sync::Arc;
3
4use anyhow::Result;
5use indexmap::IndexMap;
6use kcl_api::UnitLength;
7use serde::Serialize;
8use serde::Serializer;
9
10use crate::CompilationIssue;
11use crate::KclError;
12use crate::ModuleId;
13use crate::SourceRange;
14use crate::errors::KclErrorDetails;
15use crate::execution::AbstractSegment;
16use crate::execution::BoundedEdge;
17use crate::execution::CameraView;
18use crate::execution::EnvironmentRef;
19use crate::execution::ExecState;
20use crate::execution::ExecutorContext;
21use crate::execution::Face;
22use crate::execution::GdtAnnotation;
23use crate::execution::Geometry;
24use crate::execution::GeometryWithImportedGeometry;
25use crate::execution::Helix;
26use crate::execution::ImportedGeometry;
27use crate::execution::Metadata;
28use crate::execution::NamedViewValue;
29use crate::execution::Plane;
30use crate::execution::Segment;
31use crate::execution::SegmentRepr;
32use crate::execution::Sketch;
33use crate::execution::SketchConstraint;
34use crate::execution::SketchVar;
35use crate::execution::SketchVarId;
36use crate::execution::Solid;
37use crate::execution::TagIdentifier;
38use crate::execution::UnsolvedExpr;
39use crate::execution::annotations::FnAttrs;
40use crate::execution::annotations::SETTINGS;
41use crate::execution::annotations::SETTINGS_UNIT_LENGTH;
42use crate::execution::annotations::VersionConstraint;
43use crate::execution::annotations::{self};
44use crate::execution::types::NumericType;
45use crate::execution::types::NumericTypeExt;
46use crate::execution::types::PrimitiveType;
47use crate::execution::types::RuntimeType;
48use crate::parsing::ast::types::BoxNode;
49use crate::parsing::ast::types::DefaultParamVal;
50use crate::parsing::ast::types::FunctionExpression;
51use crate::parsing::ast::types::KclNone;
52use crate::parsing::ast::types::Literal;
53use crate::parsing::ast::types::LiteralValue;
54use crate::parsing::ast::types::Node;
55use crate::parsing::ast::types::NumericLiteral;
56use crate::parsing::ast::types::TagDeclarator;
57use crate::parsing::ast::types::TagNode;
58use crate::parsing::ast::types::Type;
59use crate::std::StdFnProps;
60use crate::std::args::TyF64;
61
62pub type KclObjectFields = HashMap<String, KclValue>;
63
64#[derive(Debug, Clone, Default, PartialEq, Serialize)]
65pub enum KclObjectKind {
66 #[default]
67 Default,
68 SketchTags {
69 #[serde(default, skip_serializing_if = "Vec::is_empty")]
70 deprecated_solid_tag_names: Vec<String>,
71 },
72}
73
74impl KclObjectKind {
75 pub(crate) fn is_default(&self) -> bool {
76 match self {
77 KclObjectKind::Default => true,
78 KclObjectKind::SketchTags { .. } => false,
79 }
80 }
81
82 pub(crate) fn deprecated_solid_tag_names(&self) -> &[String] {
83 match self {
84 Self::Default => &[],
85 Self::SketchTags {
86 deprecated_solid_tag_names,
87 } => deprecated_solid_tag_names,
88 }
89 }
90}
91
92#[derive(Debug, Clone, Serialize, PartialEq)]
94#[serde(tag = "type")]
95pub enum KclValue {
96 Uuid {
97 value: ::uuid::Uuid,
98 #[serde(skip)]
99 meta: Vec<Metadata>,
100 },
101 Bool {
102 value: bool,
103 #[serde(skip)]
104 meta: Vec<Metadata>,
105 },
106 Number {
107 value: f64,
108 ty: NumericType,
109 #[serde(skip)]
110 meta: Vec<Metadata>,
111 },
112 String {
113 value: String,
114 #[serde(skip)]
115 meta: Vec<Metadata>,
116 },
117 Enum {
118 value: Box<EnumValue>,
119 },
120 SketchVar {
121 value: Box<SketchVar>,
122 },
123 SketchConstraint {
124 value: Box<SketchConstraint>,
125 },
126 Tuple {
127 value: Vec<KclValue>,
128 #[serde(skip)]
129 meta: Vec<Metadata>,
130 },
131 HomArray {
133 value: Vec<KclValue>,
134 #[serde(skip)]
136 ty: RuntimeType,
137 },
138 Object {
139 value: KclObjectFields,
140 constrainable: bool,
141 #[serde(default, skip_serializing_if = "KclObjectKind::is_default")]
142 object_kind: KclObjectKind,
143 #[serde(skip)]
144 meta: Vec<Metadata>,
145 },
146 TagIdentifier(Box<TagIdentifier>),
147 TagDeclarator(BoxNode<TagDeclarator>),
148 GdtAnnotation {
149 value: Box<GdtAnnotation>,
150 },
151 Plane {
152 value: Box<Plane>,
153 },
154 Face {
155 value: Box<Face>,
156 },
157 BoundedEdge {
158 value: BoundedEdge,
159 meta: Vec<Metadata>,
160 },
161 Segment {
162 value: Box<AbstractSegment>,
163 },
164 Sketch {
165 value: Box<Sketch>,
166 },
167 Solid {
168 value: Box<Solid>,
169 },
170 Helix {
171 value: Box<Helix>,
172 },
173 CameraView {
174 value: Box<CameraView>,
175 },
176 NamedView {
177 value: Box<NamedViewValue>,
178 },
179 ImportedGeometry(ImportedGeometry),
180 Function {
181 #[serde(serialize_with = "function_value_stub")]
182 value: Box<FunctionSource>,
183 #[serde(skip)]
184 meta: Vec<Metadata>,
185 },
186 Module {
187 value: ModuleId,
188 #[serde(skip)]
189 meta: Vec<Metadata>,
190 },
191 Type {
192 #[serde(skip)]
193 value: TypeDef,
194 experimental: bool,
195 #[serde(skip)]
196 meta: Vec<Metadata>,
197 },
198 KclNone {
199 value: KclNone,
200 #[serde(skip)]
201 meta: Vec<Metadata>,
202 },
203}
204
205fn function_value_stub<S>(_value: &FunctionSource, serializer: S) -> Result<S::Ok, S::Error>
206where
207 S: serde::Serializer,
208{
209 serializer.serialize_unit()
210}
211
212#[derive(Debug, Clone, PartialEq)]
213pub struct NamedParam {
214 pub experimental: bool,
215 pub added_in: Option<VersionConstraint>,
218 pub deprecated: bool,
220 pub deprecated_since: Option<VersionConstraint>,
222 pub removed_in: Option<VersionConstraint>,
225 pub default_value: Option<DefaultParamVal>,
226 pub ty: Option<Type>,
227 pub resolved_ty: Option<RuntimeType>,
232}
233
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
240pub(crate) enum ParamUnavailable<'a> {
241 NotYetAdded(&'a VersionConstraint),
244 Removed(&'a VersionConstraint),
247}
248
249impl NamedParam {
250 pub(crate) fn unavailable_reason(&self, exec_state: &ExecState) -> Option<ParamUnavailable<'_>> {
254 let version = exec_state.kcl_version().as_str();
255 if let Some(added) = &self.added_in
256 && !crate::execution::annotations::version_ge(version, added)
257 {
258 return Some(ParamUnavailable::NotYetAdded(added));
259 }
260 if let Some(removed) = &self.removed_in
261 && crate::execution::annotations::version_ge(version, removed)
262 {
263 return Some(ParamUnavailable::Removed(removed));
264 }
265 None
266 }
267
268 pub(crate) fn is_available(&self, exec_state: &ExecState) -> bool {
271 self.unavailable_reason(exec_state).is_none()
272 }
273}
274
275#[derive(Debug, Clone, PartialEq)]
276pub struct FunctionSource {
277 pub input_arg: Option<(String, Option<Type>)>,
278 pub resolved_input_ty: Option<RuntimeType>,
283 pub named_args: IndexMap<String, NamedParam>,
284 pub return_type: Option<Node<Type>>,
285 pub resolved_return_ty: Option<RuntimeType>,
289 pub deprecated: bool,
290 pub deprecated_since: Option<VersionConstraint>,
294 pub experimental: bool,
295 pub include_in_feature_tree: bool,
296 pub std_props: Option<StdFnProps>,
297 pub body: FunctionBody,
298 pub ast: BoxNode<FunctionExpression>,
299}
300
301pub struct KclFunctionSourceParams {
302 pub std_props: Option<StdFnProps>,
303 pub experimental: bool,
304 pub include_in_feature_tree: bool,
305}
306
307impl FunctionSource {
308 pub fn rust(func: crate::std::StdFn, ast: BoxNode<FunctionExpression>, props: StdFnProps, attrs: FnAttrs) -> Self {
309 let (input_arg, named_args) = Self::args_from_ast(&ast);
310
311 FunctionSource {
312 input_arg,
313 resolved_input_ty: None,
314 named_args,
315 return_type: ast.return_type.clone(),
316 resolved_return_ty: None,
317 deprecated: attrs.deprecated,
318 deprecated_since: attrs.deprecated_since,
319 experimental: attrs.experimental,
320 include_in_feature_tree: attrs.include_in_feature_tree,
321 std_props: Some(props),
322 body: FunctionBody::Rust(func),
323 ast,
324 }
325 }
326
327 pub fn kcl(ast: BoxNode<FunctionExpression>, memory: EnvironmentRef, params: KclFunctionSourceParams) -> Self {
328 let KclFunctionSourceParams {
329 std_props,
330 experimental,
331 include_in_feature_tree,
332 } = params;
333 let (input_arg, named_args) = Self::args_from_ast(&ast);
334 FunctionSource {
335 input_arg,
336 resolved_input_ty: None,
337 named_args,
338 return_type: ast.return_type.clone(),
339 resolved_return_ty: None,
340 deprecated: false,
341 deprecated_since: None,
342 experimental,
343 include_in_feature_tree,
344 std_props,
345 body: FunctionBody::Kcl(memory),
346 ast,
347 }
348 }
349
350 #[expect(clippy::type_complexity)]
351 fn args_from_ast(ast: &FunctionExpression) -> (Option<(String, Option<Type>)>, IndexMap<String, NamedParam>) {
352 let mut input_arg = None;
353 let mut named_args = IndexMap::new();
354 for p in &ast.params {
355 if !p.labeled {
356 input_arg = Some((
357 p.identifier.name.clone(),
358 p.param_type.as_ref().map(|t| t.inner.clone()),
359 ));
360 continue;
361 }
362
363 named_args.insert(
364 p.identifier.name.clone(),
365 NamedParam {
366 experimental: p.experimental,
367 added_in: p.added_in.clone(),
368 deprecated: p.deprecated,
369 deprecated_since: p.deprecated_since.clone(),
370 removed_in: p.removed_in.clone(),
371 default_value: p.default_value.clone(),
372 ty: p.param_type.as_ref().map(|t| t.inner.clone()),
373 resolved_ty: None,
374 },
375 );
376 }
377
378 (input_arg, named_args)
379 }
380
381 #[doc(hidden)]
382 pub fn is_std(&self) -> bool {
383 self.std_props.is_some()
384 }
385
386 pub(crate) fn active_named_arg<'a>(&'a self, label: &str, exec_state: &ExecState) -> Option<&'a NamedParam> {
391 self.named_args
392 .get(label)
393 .filter(|param| param.is_available(exec_state))
394 }
395
396 pub(crate) fn active_named_args<'a>(
400 &'a self,
401 exec_state: &'a ExecState,
402 ) -> impl Iterator<Item = (&'a String, &'a NamedParam)> + 'a {
403 self.named_args
404 .iter()
405 .filter(move |(_, param)| param.is_available(exec_state))
406 }
407
408 pub(crate) async fn resolve_signature_types(
419 &mut self,
420 exec_state: &mut ExecState,
421 ctx: &ExecutorContext,
422 ) -> Result<(), KclError> {
423 for param in &self.ast.params {
424 let Some(ty) = ¶m.param_type else {
425 continue;
426 };
427 let resolved =
428 RuntimeType::from_parsed(ty.inner.clone(), exec_state, ctx, ty.as_source_range(), false, false).await?;
429 if param.labeled {
430 if let Some(named) = self.named_args.get_mut(¶m.identifier.name) {
431 named.resolved_ty = Some(resolved);
432 }
433 } else {
434 self.resolved_input_ty = Some(resolved);
435 }
436 }
437
438 if let Some(ret_ty) = &self.return_type {
439 self.resolved_return_ty = Some(
440 RuntimeType::from_parsed(
441 ret_ty.inner.clone(),
442 exec_state,
443 ctx,
444 ret_ty.as_source_range(),
445 false,
446 false,
447 )
448 .await?,
449 );
450 }
451
452 Ok(())
453 }
454}
455
456#[derive(Debug, Clone, PartialEq)]
457#[allow(unpredictable_function_pointer_comparisons)]
460pub enum FunctionBody {
461 Rust(crate::std::StdFn),
462 Kcl(EnvironmentRef),
463}
464
465#[derive(Debug, Clone, PartialEq)]
466pub enum TypeDef {
467 RustRepr(PrimitiveType, StdFnProps),
468 Alias(RuntimeType),
469 Enum(Arc<EnumTypeDef>),
473}
474
475impl TypeDef {
476 pub(super) fn into_runtime_type(self) -> RuntimeType {
480 match self {
481 Self::RustRepr(ty, _) => RuntimeType::Primitive(ty),
482 Self::Alias(ty) => ty,
483 Self::Enum(def) => RuntimeType::Enum(def.id().clone()),
484 }
485 }
486}
487
488#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
496pub struct EnumTypeId {
497 module_id: ModuleId,
498 declared_name: String,
499}
500
501impl EnumTypeId {
502 pub fn new(module_id: ModuleId, declared_name: impl Into<String>) -> Self {
503 Self {
504 module_id,
505 declared_name: declared_name.into(),
506 }
507 }
508
509 pub fn module_id(&self) -> ModuleId {
510 self.module_id
511 }
512
513 pub fn declared_name(&self) -> &str {
516 &self.declared_name
517 }
518}
519
520#[derive(Debug, Clone, PartialEq)]
522pub struct EnumTypeDef {
523 id: EnumTypeId,
524 variants: Vec<String>,
525}
526
527#[derive(Debug, Clone, PartialEq)]
535pub struct DuplicateVariant {
536 pub name: String,
538 pub first_index: usize,
540 pub duplicate_index: usize,
542}
543
544impl EnumTypeDef {
545 pub fn new(id: EnumTypeId, variants: Vec<String>) -> Result<Self, DuplicateVariant> {
552 for (duplicate_index, variant) in variants.iter().enumerate() {
553 if let Some(first_index) = variants[..duplicate_index].iter().position(|v| v == variant) {
554 return Err(DuplicateVariant {
555 name: variant.clone(),
556 first_index,
557 duplicate_index,
558 });
559 }
560 }
561
562 Ok(Self { id, variants })
563 }
564
565 pub fn id(&self) -> &EnumTypeId {
566 &self.id
567 }
568
569 pub fn variants(&self) -> &[String] {
570 &self.variants
571 }
572
573 pub fn has_variant(&self, name: &str) -> bool {
574 self.variants.iter().any(|v| v == name)
575 }
576}
577
578#[derive(Debug, Clone, Serialize)]
589pub struct EnumValue {
590 #[serde(rename = "enum_id", serialize_with = "serialize_enum_def_id")]
594 def: Arc<EnumTypeDef>,
595 variant: String,
596 #[serde(skip)]
597 meta: Vec<Metadata>,
598}
599
600fn serialize_enum_def_id<S: Serializer>(def: &Arc<EnumTypeDef>, serializer: S) -> Result<S::Ok, S::Error> {
601 def.id().serialize(serializer)
602}
603
604impl PartialEq for EnumValue {
609 fn eq(&self, other: &Self) -> bool {
610 self.def.id() == other.def.id() && self.variant == other.variant
611 }
612}
613
614impl EnumValue {
615 pub fn new(def: Arc<EnumTypeDef>, variant: impl Into<String>, meta: Vec<Metadata>) -> Self {
616 Self {
617 def,
618 variant: variant.into(),
619 meta,
620 }
621 }
622
623 pub fn enum_id(&self) -> &EnumTypeId {
624 self.def.id()
625 }
626
627 pub fn variant(&self) -> &str {
628 &self.variant
629 }
630
631 pub fn meta(&self) -> &[Metadata] {
632 &self.meta
633 }
634
635 pub fn declared_string_repr(&self) -> String {
643 self.variant.clone()
644 }
645
646 pub fn qualified_name(&self) -> String {
648 format!("{}::{}", self.def.id().declared_name(), self.variant)
649 }
650}
651
652impl From<Vec<GdtAnnotation>> for KclValue {
653 fn from(mut values: Vec<GdtAnnotation>) -> Self {
654 if values.len() == 1 {
655 let value = values.pop().expect("Just checked len == 1");
656 KclValue::GdtAnnotation { value: Box::new(value) }
657 } else {
658 KclValue::HomArray {
659 value: values
660 .into_iter()
661 .map(|s| KclValue::GdtAnnotation { value: Box::new(s) })
662 .collect(),
663 ty: RuntimeType::Primitive(PrimitiveType::GdtAnnotation),
664 }
665 }
666 }
667}
668
669impl From<Vec<Sketch>> for KclValue {
670 fn from(mut eg: Vec<Sketch>) -> Self {
671 if eg.len() == 1
672 && let Some(s) = eg.pop()
673 {
674 KclValue::Sketch { value: Box::new(s) }
675 } else {
676 KclValue::HomArray {
677 value: eg
678 .into_iter()
679 .map(|s| KclValue::Sketch { value: Box::new(s) })
680 .collect(),
681 ty: RuntimeType::Primitive(PrimitiveType::Sketch),
682 }
683 }
684 }
685}
686
687impl From<Vec<Solid>> for KclValue {
688 fn from(mut eg: Vec<Solid>) -> Self {
689 if eg.len() == 1
690 && let Some(s) = eg.pop()
691 {
692 KclValue::Solid { value: Box::new(s) }
693 } else {
694 KclValue::HomArray {
695 value: eg.into_iter().map(|s| KclValue::Solid { value: Box::new(s) }).collect(),
696 ty: RuntimeType::Primitive(PrimitiveType::Solid),
697 }
698 }
699 }
700}
701
702impl From<KclValue> for Vec<SourceRange> {
703 fn from(item: KclValue) -> Self {
704 match item {
705 KclValue::TagDeclarator(t) => vec![SourceRange::new(t.start, t.end, t.module_id)],
706 KclValue::TagIdentifier(t) => to_vec_sr(&t.meta),
707 KclValue::GdtAnnotation { value } => to_vec_sr(&value.meta),
708 KclValue::Solid { value } => to_vec_sr(&value.meta),
709 KclValue::Sketch { value } => to_vec_sr(&value.meta),
710 KclValue::Helix { value } => to_vec_sr(&value.meta),
711 KclValue::CameraView { value } => to_vec_sr(value.meta()),
712 KclValue::NamedView { value } => to_vec_sr(value.meta()),
713 KclValue::ImportedGeometry(i) => to_vec_sr(&i.meta),
714 KclValue::Function { meta, .. } => to_vec_sr(&meta),
715 KclValue::Plane { value } => to_vec_sr(&value.meta),
716 KclValue::Face { value } => to_vec_sr(&value.meta),
717 KclValue::Segment { value } => to_vec_sr(&value.meta),
718 KclValue::Bool { meta, .. } => to_vec_sr(&meta),
719 KclValue::Number { meta, .. } => to_vec_sr(&meta),
720 KclValue::String { meta, .. } => to_vec_sr(&meta),
721 KclValue::Enum { value } => to_vec_sr(value.meta()),
722 KclValue::SketchVar { value, .. } => to_vec_sr(&value.meta),
723 KclValue::SketchConstraint { value, .. } => to_vec_sr(&value.meta),
724 KclValue::Tuple { meta, .. } => to_vec_sr(&meta),
725 KclValue::HomArray { value, .. } => value.iter().flat_map(Into::<Vec<SourceRange>>::into).collect(),
726 KclValue::Object { meta, .. } => to_vec_sr(&meta),
727 KclValue::Module { meta, .. } => to_vec_sr(&meta),
728 KclValue::Uuid { meta, .. } => to_vec_sr(&meta),
729 KclValue::Type { meta, .. } => to_vec_sr(&meta),
730 KclValue::KclNone { meta, .. } => to_vec_sr(&meta),
731 KclValue::BoundedEdge { meta, .. } => to_vec_sr(&meta),
732 }
733 }
734}
735
736fn to_vec_sr(meta: &[Metadata]) -> Vec<SourceRange> {
737 meta.iter().map(|m| m.source_range).collect()
738}
739
740impl From<&KclValue> for Vec<SourceRange> {
741 fn from(item: &KclValue) -> Self {
742 match item {
743 KclValue::TagDeclarator(t) => vec![SourceRange::new(t.start, t.end, t.module_id)],
744 KclValue::TagIdentifier(t) => to_vec_sr(&t.meta),
745 KclValue::GdtAnnotation { value } => to_vec_sr(&value.meta),
746 KclValue::Solid { value } => to_vec_sr(&value.meta),
747 KclValue::Sketch { value } => to_vec_sr(&value.meta),
748 KclValue::Helix { value } => to_vec_sr(&value.meta),
749 KclValue::CameraView { value } => to_vec_sr(value.meta()),
750 KclValue::NamedView { value } => to_vec_sr(value.meta()),
751 KclValue::ImportedGeometry(i) => to_vec_sr(&i.meta),
752 KclValue::Function { meta, .. } => to_vec_sr(meta),
753 KclValue::Plane { value } => to_vec_sr(&value.meta),
754 KclValue::Face { value } => to_vec_sr(&value.meta),
755 KclValue::Segment { value } => to_vec_sr(&value.meta),
756 KclValue::Bool { meta, .. } => to_vec_sr(meta),
757 KclValue::Number { meta, .. } => to_vec_sr(meta),
758 KclValue::String { meta, .. } => to_vec_sr(meta),
759 KclValue::Enum { value } => to_vec_sr(value.meta()),
760 KclValue::SketchVar { value, .. } => to_vec_sr(&value.meta),
761 KclValue::SketchConstraint { value, .. } => to_vec_sr(&value.meta),
762 KclValue::Uuid { meta, .. } => to_vec_sr(meta),
763 KclValue::Tuple { meta, .. } => to_vec_sr(meta),
764 KclValue::HomArray { value, .. } => value.iter().flat_map(Into::<Vec<SourceRange>>::into).collect(),
765 KclValue::Object { meta, .. } => to_vec_sr(meta),
766 KclValue::Module { meta, .. } => to_vec_sr(meta),
767 KclValue::KclNone { meta, .. } => to_vec_sr(meta),
768 KclValue::Type { meta, .. } => to_vec_sr(meta),
769 KclValue::BoundedEdge { meta, .. } => to_vec_sr(meta),
770 }
771 }
772}
773
774impl From<&KclValue> for SourceRange {
775 fn from(item: &KclValue) -> Self {
776 let v: Vec<_> = item.into();
777 v.into_iter().next().unwrap_or_default()
778 }
779}
780
781impl KclValue {
782 pub(crate) fn metadata(&self) -> Vec<Metadata> {
783 match self {
784 KclValue::Uuid { value: _, meta } => meta.clone(),
785 KclValue::Bool { value: _, meta } => meta.clone(),
786 KclValue::Number { meta, .. } => meta.clone(),
787 KclValue::String { value: _, meta } => meta.clone(),
788 KclValue::Enum { value } => value.meta().to_vec(),
789 KclValue::SketchVar { value, .. } => value.meta.clone(),
790 KclValue::SketchConstraint { value, .. } => value.meta.clone(),
791 KclValue::Tuple { value: _, meta } => meta.clone(),
792 KclValue::HomArray { value, .. } => value.iter().flat_map(|v| v.metadata()).collect(),
793 KclValue::Object { meta, .. } => meta.clone(),
794 KclValue::TagIdentifier(x) => x.meta.clone(),
795 KclValue::TagDeclarator(x) => vec![x.metadata()],
796 KclValue::GdtAnnotation { value } => value.meta.clone(),
797 KclValue::Plane { value } => value.meta.clone(),
798 KclValue::Face { value } => value.meta.clone(),
799 KclValue::Segment { value } => value.meta.clone(),
800 KclValue::Sketch { value } => value.meta.clone(),
801 KclValue::Solid { value } => value.meta.clone(),
802 KclValue::Helix { value } => value.meta.clone(),
803 KclValue::CameraView { value } => value.meta().to_vec(),
804 KclValue::NamedView { value } => value.meta().to_vec(),
805 KclValue::ImportedGeometry(x) => x.meta.clone(),
806 KclValue::Function { meta, .. } => meta.clone(),
807 KclValue::Module { meta, .. } => meta.clone(),
808 KclValue::KclNone { meta, .. } => meta.clone(),
809 KclValue::Type { meta, .. } => meta.clone(),
810 KclValue::BoundedEdge { meta, .. } => meta.clone(),
811 }
812 }
813
814 #[allow(unused)]
815 pub(crate) fn none() -> Self {
816 Self::KclNone {
817 value: Default::default(),
818 meta: Default::default(),
819 }
820 }
821
822 pub(crate) fn show_variable_in_feature_tree(&self) -> bool {
826 match self {
827 KclValue::Uuid { .. } => false,
828 KclValue::Bool { .. } | KclValue::Number { .. } | KclValue::String { .. } | KclValue::Enum { .. } => true,
829 KclValue::SketchVar { .. }
830 | KclValue::SketchConstraint { .. }
831 | KclValue::Tuple { .. }
832 | KclValue::HomArray { .. }
833 | KclValue::Object { .. }
834 | KclValue::TagIdentifier(_)
835 | KclValue::TagDeclarator(_)
836 | KclValue::GdtAnnotation { .. }
837 | KclValue::Plane { .. }
838 | KclValue::Face { .. }
839 | KclValue::Segment { .. }
840 | KclValue::Sketch { .. }
841 | KclValue::Solid { .. }
842 | KclValue::Helix { .. }
843 | KclValue::CameraView { .. }
844 | KclValue::NamedView { .. }
845 | KclValue::ImportedGeometry(_)
846 | KclValue::Function { .. }
847 | KclValue::Module { .. }
848 | KclValue::Type { .. }
849 | KclValue::BoundedEdge { .. }
850 | KclValue::KclNone { .. } => false,
851 }
852 }
853
854 pub(crate) fn human_friendly_type(&self) -> String {
857 match self {
858 KclValue::Uuid { .. } => "a unique ID (uuid)".to_owned(),
859 KclValue::TagDeclarator(_) => "a tag declarator".to_owned(),
860 KclValue::TagIdentifier(_) => "a tag identifier".to_owned(),
861 KclValue::GdtAnnotation { .. } => "an annotation".to_owned(),
862 KclValue::Solid { .. } => "a solid".to_owned(),
863 KclValue::Sketch { .. } => "a sketch".to_owned(),
864 KclValue::Helix { .. } => "a helix".to_owned(),
865 KclValue::CameraView { .. } => "a camera view".to_owned(),
866 KclValue::NamedView { .. } => "a named view".to_owned(),
867 KclValue::ImportedGeometry(_) => "an imported geometry".to_owned(),
868 KclValue::Function { .. } => "a function".to_owned(),
869 KclValue::Plane { .. } => "a plane".to_owned(),
870 KclValue::Face { .. } => "a face".to_owned(),
871 KclValue::Segment { .. } => "a segment".to_owned(),
872 KclValue::Bool { .. } => "a boolean (`true` or `false`)".to_owned(),
873 KclValue::Number {
874 ty: NumericType::Unknown,
875 ..
876 } => "a number with unknown units".to_owned(),
877 KclValue::Number {
878 ty: NumericType::Known(units),
879 ..
880 } => format!("a number ({units})"),
881 KclValue::Number { .. } => "a number".to_owned(),
882 KclValue::String { .. } => "a string".to_owned(),
883 KclValue::Enum { value } => format!("a value of enum `{}`", value.enum_id().declared_name()),
884 KclValue::SketchVar { .. } => "a sketch variable".to_owned(),
885 KclValue::SketchConstraint { .. } => "a sketch constraint".to_owned(),
886 KclValue::Object { .. } => "an object".to_owned(),
887 KclValue::Module { .. } => "a module".to_owned(),
888 KclValue::Type { .. } => "a type".to_owned(),
889 KclValue::KclNone { .. } => "none".to_owned(),
890 KclValue::BoundedEdge { .. } => "a bounded edge".to_owned(),
891 KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
892 if value.is_empty() {
893 "an empty array".to_owned()
894 } else {
895 const MAX: usize = 3;
897
898 let len = value.len();
899 let element_tys = value
900 .iter()
901 .take(MAX)
902 .map(|elem| elem.principal_type_string())
903 .collect::<Vec<_>>()
904 .join(", ");
905 let mut result = format!("an array of {element_tys}");
906 if len > MAX {
907 result.push_str(&format!(", ... with {len} values"));
908 }
909 if len == 1 {
910 result.push_str(" with 1 value");
911 }
912 result
913 }
914 }
915 }
916 }
917
918 pub(crate) fn from_sketch_var_literal(
919 literal: &Node<NumericLiteral>,
920 id: SketchVarId,
921 node_path: Option<crate::NodePath>,
922 exec_state: &ExecState,
923 ) -> Self {
924 let meta = vec![literal.metadata()];
925 let ty = NumericType::from_parsed(literal.suffix, &exec_state.mod_local.settings);
926 KclValue::SketchVar {
927 value: Box::new(SketchVar {
928 id,
929 initial_value: literal.value,
930 node_path,
931 meta,
932 ty,
933 }),
934 }
935 }
936
937 pub(crate) fn from_literal(literal: Node<Literal>, exec_state: &mut ExecState) -> Self {
938 let meta = vec![literal.metadata()];
939 match literal.inner.value {
940 LiteralValue::Number { value, suffix } => {
941 let ty = NumericType::from_parsed(suffix, &exec_state.mod_local.settings);
942 if let NumericType::Default { len, .. } = &ty
943 && !exec_state.mod_local.explicit_length_units
944 && *len != UnitLength::Millimeters
945 {
946 exec_state.warn(
947 CompilationIssue::err(
948 literal.as_source_range(),
949 "Project-wide units are deprecated. Prefer to use per-file default units.",
950 )
951 .with_suggestion(
952 "Fix by adding per-file settings",
953 format!("@{SETTINGS}({SETTINGS_UNIT_LENGTH} = {len})\n"),
954 Some(SourceRange::new(0, 0, literal.module_id)),
956 crate::errors::Tag::Deprecated,
957 ),
958 annotations::WARN_DEPRECATED,
959 );
960 }
961 KclValue::Number { value, meta, ty }
962 }
963 LiteralValue::String(value) => KclValue::String { value, meta },
964 LiteralValue::Bool(value) => KclValue::Bool { value, meta },
965 }
966 }
967
968 pub(crate) fn from_default_param(param: DefaultParamVal, exec_state: &mut ExecState) -> Self {
969 match param {
970 DefaultParamVal::Literal(lit) => Self::from_literal(lit, exec_state),
971 DefaultParamVal::KclNone(value) => KclValue::KclNone {
972 value,
973 meta: Default::default(),
974 },
975 }
976 }
977
978 pub(crate) fn map_env_ref(&self, old_env: EnvironmentRef, new_env: EnvironmentRef) -> Self {
979 let mut result = self.clone();
980 if let KclValue::Function { ref mut value, .. } = result
981 && let FunctionSource {
982 body: FunctionBody::Kcl(memory),
983 ..
984 } = &mut **value
985 {
986 memory.replace_env(old_env, new_env);
987 }
988
989 result
990 }
991
992 pub(crate) fn map_env_ref_and_epoch(&self, old_env: EnvironmentRef, new_env: EnvironmentRef) -> Self {
993 let mut result = self.clone();
994 if let KclValue::Function { ref mut value, .. } = result
995 && let FunctionSource {
996 body: FunctionBody::Kcl(memory),
997 ..
998 } = &mut **value
999 {
1000 memory.replace_env_and_epoch(old_env, new_env);
1001 }
1002
1003 result
1004 }
1005
1006 pub const fn from_number_with_type(f: f64, ty: NumericType, meta: Vec<Metadata>) -> Self {
1007 Self::Number { value: f, meta, ty }
1008 }
1009
1010 pub fn from_point2d(p: [f64; 2], ty: NumericType, meta: Vec<Metadata>) -> Self {
1012 let [x, y] = p;
1013 Self::Tuple {
1014 value: vec![
1015 Self::Number {
1016 value: x,
1017 meta: meta.clone(),
1018 ty,
1019 },
1020 Self::Number {
1021 value: y,
1022 meta: meta.clone(),
1023 ty,
1024 },
1025 ],
1026 meta,
1027 }
1028 }
1029
1030 pub fn from_imported_geometries(geometries: Vec<ImportedGeometry>) -> Self {
1031 geometries
1032 .into_iter()
1033 .map(|geometry| GeometryWithImportedGeometry::ImportedGeometry(Box::new(geometry)))
1034 .collect::<Vec<_>>()
1035 .into()
1036 }
1037
1038 pub fn from_point3d(p: [f64; 3], ty: NumericType, meta: Vec<Metadata>) -> Self {
1040 let [x, y, z] = p;
1041 Self::Tuple {
1042 value: vec![
1043 Self::Number {
1044 value: x,
1045 meta: meta.clone(),
1046 ty,
1047 },
1048 Self::Number {
1049 value: y,
1050 meta: meta.clone(),
1051 ty,
1052 },
1053 Self::Number {
1054 value: z,
1055 meta: meta.clone(),
1056 ty,
1057 },
1058 ],
1059 meta,
1060 }
1061 }
1062
1063 pub(crate) fn array_from_point2d(p: [f64; 2], ty: NumericType, meta: Vec<Metadata>) -> Self {
1065 let [x, y] = p;
1066 Self::HomArray {
1067 value: vec![
1068 Self::Number {
1069 value: x,
1070 meta: meta.clone(),
1071 ty,
1072 },
1073 Self::Number { value: y, meta, ty },
1074 ],
1075 ty: ty.into(),
1076 }
1077 }
1078
1079 pub fn array_from_point3d(p: [f64; 3], ty: NumericType, meta: Vec<Metadata>) -> Self {
1081 let [x, y, z] = p;
1082 Self::HomArray {
1083 value: vec![
1084 Self::Number {
1085 value: x,
1086 meta: meta.clone(),
1087 ty,
1088 },
1089 Self::Number {
1090 value: y,
1091 meta: meta.clone(),
1092 ty,
1093 },
1094 Self::Number { value: z, meta, ty },
1095 ],
1096 ty: ty.into(),
1097 }
1098 }
1099
1100 pub(crate) fn from_unsolved_expr(expr: UnsolvedExpr, meta: Vec<Metadata>) -> Self {
1101 match expr {
1102 UnsolvedExpr::Known(v) => crate::execution::KclValue::Number {
1103 value: v.n,
1104 ty: v.ty,
1105 meta,
1106 },
1107 UnsolvedExpr::Unknown(var_id) => crate::execution::KclValue::SketchVar {
1111 value: Box::new(SketchVar {
1112 id: var_id,
1113 initial_value: Default::default(),
1114 ty: Default::default(),
1116 node_path: None,
1117 meta,
1118 }),
1119 },
1120 }
1121 }
1122
1123 pub(crate) fn as_usize(&self) -> Option<usize> {
1124 match self {
1125 KclValue::Number { value, .. } => crate::try_f64_to_usize(*value),
1126 _ => None,
1127 }
1128 }
1129
1130 pub fn as_int(&self) -> Option<i64> {
1131 match self {
1132 KclValue::Number { value, .. } => crate::try_f64_to_i64(*value),
1133 _ => None,
1134 }
1135 }
1136
1137 pub fn as_int_with_ty(&self) -> Option<(i64, NumericType)> {
1138 match self {
1139 KclValue::Number { value, ty, .. } => crate::try_f64_to_i64(*value).map(|i| (i, *ty)),
1140 _ => None,
1141 }
1142 }
1143
1144 pub fn as_object(&self) -> Option<&KclObjectFields> {
1145 match self {
1146 KclValue::Object { value, .. } => Some(value),
1147 _ => None,
1148 }
1149 }
1150
1151 pub fn into_object(self) -> Option<KclObjectFields> {
1152 match self {
1153 KclValue::Object { value, .. } => Some(value),
1154 _ => None,
1155 }
1156 }
1157
1158 pub fn as_unsolved_expr(&self) -> Option<UnsolvedExpr> {
1159 match self {
1160 KclValue::Number { value, ty, .. } => Some(UnsolvedExpr::Known(TyF64::new(*value, *ty))),
1161 KclValue::SketchVar { value, .. } => Some(UnsolvedExpr::Unknown(value.id)),
1162 _ => None,
1163 }
1164 }
1165
1166 pub fn to_sketch_expr(&self) -> Option<crate::front::Expr> {
1167 match self {
1168 KclValue::Number { value, ty, .. } => Some(crate::front::Expr::Number(crate::front::Number {
1169 value: *value,
1170 units: (*ty).try_into().ok()?,
1171 })),
1172 KclValue::SketchVar { value, .. } => Some(crate::front::Expr::Var(crate::front::Number {
1173 value: value.initial_value,
1174 units: value.ty.try_into().ok()?,
1175 })),
1176 _ => None,
1177 }
1178 }
1179
1180 pub fn as_str(&self) -> Option<&str> {
1181 match self {
1182 KclValue::String { value, .. } => Some(value),
1183 _ => None,
1184 }
1185 }
1186
1187 pub fn into_array(self) -> Vec<KclValue> {
1188 match self {
1189 KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => value,
1190 _ => vec![self],
1191 }
1192 }
1193
1194 pub fn as_slice(&self) -> Option<&[KclValue]> {
1195 match self {
1196 KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => Some(value),
1197 _ => None,
1198 }
1199 }
1200
1201 pub fn as_point2d(&self) -> Option<[TyF64; 2]> {
1202 let value = match self {
1203 KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => value,
1204 _ => return None,
1205 };
1206
1207 let [x, y] = value.as_slice() else {
1208 return None;
1209 };
1210 let x = x.as_ty_f64()?;
1211 let y = y.as_ty_f64()?;
1212 Some([x, y])
1213 }
1214
1215 pub fn as_point3d(&self) -> Option<[TyF64; 3]> {
1216 let value = match self {
1217 KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => value,
1218 _ => return None,
1219 };
1220
1221 let [x, y, z] = value.as_slice() else {
1222 return None;
1223 };
1224 let x = x.as_ty_f64()?;
1225 let y = y.as_ty_f64()?;
1226 let z = z.as_ty_f64()?;
1227 Some([x, y, z])
1228 }
1229
1230 pub fn as_uuid(&self) -> Option<uuid::Uuid> {
1231 match self {
1232 KclValue::Uuid { value, .. } => Some(*value),
1233 _ => None,
1234 }
1235 }
1236
1237 pub fn as_plane(&self) -> Option<&Plane> {
1238 match self {
1239 KclValue::Plane { value, .. } => Some(value),
1240 _ => None,
1241 }
1242 }
1243
1244 pub fn as_solid(&self) -> Option<&Solid> {
1245 match self {
1246 KclValue::Solid { value, .. } => Some(value),
1247 _ => None,
1248 }
1249 }
1250
1251 pub fn as_sketch(&self) -> Option<&Sketch> {
1252 match self {
1253 KclValue::Sketch { value, .. } => Some(value),
1254 _ => None,
1255 }
1256 }
1257
1258 pub fn as_mut_sketch(&mut self) -> Option<&mut Sketch> {
1259 match self {
1260 KclValue::Sketch { value } => Some(value),
1261 _ => None,
1262 }
1263 }
1264
1265 pub fn as_sketch_var(&self) -> Option<&SketchVar> {
1266 match self {
1267 KclValue::SketchVar { value, .. } => Some(value),
1268 _ => None,
1269 }
1270 }
1271
1272 pub fn as_segment(&self) -> Option<&Segment> {
1274 match self {
1275 KclValue::Segment { value, .. } => match &value.repr {
1276 SegmentRepr::Solved { segment } => Some(segment),
1277 _ => None,
1278 },
1279 _ => None,
1280 }
1281 }
1282
1283 pub fn into_segment(self) -> Option<Segment> {
1285 match self {
1286 KclValue::Segment { value, .. } => match value.repr {
1287 SegmentRepr::Solved { segment } => Some(*segment),
1288 _ => None,
1289 },
1290 _ => None,
1291 }
1292 }
1293
1294 pub fn as_mut_tag(&mut self) -> Option<&mut TagIdentifier> {
1295 match self {
1296 KclValue::TagIdentifier(value) => Some(value),
1297 _ => None,
1298 }
1299 }
1300
1301 #[cfg(test)]
1302 pub fn as_f64(&self) -> Option<f64> {
1303 match self {
1304 KclValue::Number { value, .. } => Some(*value),
1305 _ => None,
1306 }
1307 }
1308
1309 pub fn as_ty_f64(&self) -> Option<TyF64> {
1310 match self {
1311 KclValue::Number { value, ty, .. } => Some(TyF64::new(*value, *ty)),
1312 _ => None,
1313 }
1314 }
1315
1316 pub fn as_bool(&self) -> Option<bool> {
1317 match self {
1318 KclValue::Bool { value, .. } => Some(*value),
1319 _ => None,
1320 }
1321 }
1322
1323 pub fn as_function(&self) -> Option<&FunctionSource> {
1325 match self {
1326 KclValue::Function { value, .. } => Some(value),
1327 _ => None,
1328 }
1329 }
1330
1331 pub fn get_tag_identifier(&self) -> Result<TagIdentifier, KclError> {
1333 match self {
1334 KclValue::TagIdentifier(t) => Ok(*t.clone()),
1335 _ => Err(KclError::new_semantic(KclErrorDetails::new(
1336 format!("Not a tag identifier: {self:?}"),
1337 self.clone().into(),
1338 ))),
1339 }
1340 }
1341
1342 pub fn get_tag_declarator(&self) -> Result<TagNode, KclError> {
1344 match self {
1345 KclValue::TagDeclarator(t) => Ok((**t).clone()),
1346 _ => Err(KclError::new_semantic(KclErrorDetails::new(
1347 format!("Not a tag declarator: {self:?}"),
1348 self.clone().into(),
1349 ))),
1350 }
1351 }
1352
1353 pub fn get_bool(&self) -> Result<bool, KclError> {
1355 self.as_bool().ok_or_else(|| {
1356 KclError::new_type(KclErrorDetails::new(
1357 format!("Expected bool, found {}", self.human_friendly_type()),
1358 self.into(),
1359 ))
1360 })
1361 }
1362
1363 pub fn is_unknown_number(&self) -> bool {
1364 match self {
1365 KclValue::Number { ty, .. } => !ty.is_fully_specified(),
1366 _ => false,
1367 }
1368 }
1369
1370 pub fn value_str(&self) -> Option<String> {
1371 match self {
1372 KclValue::Bool { value, .. } => Some(format!("{value}")),
1373 KclValue::Number { value, .. } => Some(format!("{value}")),
1375 KclValue::String { value, .. } => Some(format!("'{value}'")),
1376 KclValue::Enum { value } => Some(value.qualified_name()),
1377 KclValue::SketchVar { value, .. } => Some(format!("var {}", value.initial_value)),
1379 KclValue::Uuid { value, .. } => Some(format!("{value}")),
1380 KclValue::TagDeclarator(tag) => Some(format!("${}", tag.name)),
1381 KclValue::TagIdentifier(tag) => Some(format!("${}", tag.value)),
1382 KclValue::Tuple { .. } => Some("[...]".to_owned()),
1384 KclValue::HomArray { .. } => Some("[...]".to_owned()),
1385 KclValue::Object { .. } => Some("{ ... }".to_owned()),
1386 KclValue::Module { .. }
1387 | KclValue::GdtAnnotation { .. }
1388 | KclValue::SketchConstraint { .. }
1389 | KclValue::Solid { .. }
1390 | KclValue::Sketch { .. }
1391 | KclValue::Helix { .. }
1392 | KclValue::CameraView { .. }
1393 | KclValue::NamedView { .. }
1394 | KclValue::ImportedGeometry(_)
1395 | KclValue::Function { .. }
1396 | KclValue::Plane { .. }
1397 | KclValue::Face { .. }
1398 | KclValue::Segment { .. }
1399 | KclValue::KclNone { .. }
1400 | KclValue::BoundedEdge { .. }
1401 | KclValue::Type { .. } => None,
1402 }
1403 }
1404}
1405
1406impl From<Geometry> for KclValue {
1407 fn from(value: Geometry) -> Self {
1408 match value {
1409 Geometry::Sketch(x) => Self::Sketch { value: Box::new(x) },
1410 Geometry::Solid(x) => Self::Solid { value: Box::new(x) },
1411 }
1412 }
1413}
1414
1415impl From<GeometryWithImportedGeometry> for KclValue {
1416 fn from(value: GeometryWithImportedGeometry) -> Self {
1417 match value {
1418 GeometryWithImportedGeometry::Sketch(x) => Self::Sketch { value: Box::new(x) },
1419 GeometryWithImportedGeometry::Solid(x) => Self::Solid { value: Box::new(x) },
1420 GeometryWithImportedGeometry::ImportedGeometry(x) => Self::ImportedGeometry(*x),
1421 }
1422 }
1423}
1424
1425impl From<Vec<GeometryWithImportedGeometry>> for KclValue {
1426 fn from(mut values: Vec<GeometryWithImportedGeometry>) -> Self {
1427 if values.len() == 1
1428 && let Some(v) = values.pop()
1429 {
1430 KclValue::from(v)
1431 } else {
1432 KclValue::HomArray {
1433 value: values.into_iter().map(KclValue::from).collect(),
1434 ty: RuntimeType::Union(vec![
1435 RuntimeType::Primitive(PrimitiveType::Sketch),
1436 RuntimeType::Primitive(PrimitiveType::Solid),
1437 RuntimeType::Primitive(PrimitiveType::ImportedGeometry),
1438 ]),
1439 }
1440 }
1441 }
1442}
1443
1444#[cfg(test)]
1445mod tests {
1446 use super::*;
1447 use crate::exec::UnitType;
1448
1449 #[test]
1450 fn tag_declaration_bindings_do_not_overwrite_each_other() {
1451 use kcl_api::TagDeclaratorView;
1452 use ts_rs::TS;
1453
1454 for ast_first in [true, false] {
1457 let output = tempfile::tempdir().unwrap();
1458 let config = ts_rs::Config::default().with_out_dir(output.path());
1459 if ast_first {
1460 TagDeclarator::export_all(&config).unwrap();
1461 kcl_api::BasePathView::export_all(&config).unwrap();
1462 } else {
1463 kcl_api::BasePathView::export_all(&config).unwrap();
1464 TagDeclarator::export_all(&config).unwrap();
1465 }
1466
1467 for (path, expected) in [
1468 (
1469 TagDeclarator::output_path().unwrap(),
1470 TagDeclarator::export_to_string(&config).unwrap(),
1471 ),
1472 (
1473 TagDeclaratorView::output_path().unwrap(),
1474 TagDeclaratorView::export_to_string(&config).unwrap(),
1475 ),
1476 ] {
1477 assert_eq!(std::fs::read_to_string(output.path().join(path)).unwrap(), expected);
1478 }
1479 }
1480 }
1481
1482 #[test]
1483 fn test_human_friendly_type() {
1484 let len = KclValue::Number {
1485 value: 1.0,
1486 ty: NumericType::Known(UnitType::GenericLength),
1487 meta: vec![],
1488 };
1489 assert_eq!(len.human_friendly_type(), "a number (Length)".to_string());
1490
1491 let unknown = KclValue::Number {
1492 value: 1.0,
1493 ty: NumericType::Unknown,
1494 meta: vec![],
1495 };
1496 assert_eq!(unknown.human_friendly_type(), "a number with unknown units".to_string());
1497
1498 let mm = KclValue::Number {
1499 value: 1.0,
1500 ty: NumericType::Known(UnitType::Length(UnitLength::Millimeters)),
1501 meta: vec![],
1502 };
1503 assert_eq!(mm.human_friendly_type(), "a number (mm)".to_string());
1504
1505 let array1_mm = KclValue::HomArray {
1506 value: vec![mm.clone()],
1507 ty: RuntimeType::any(),
1508 };
1509 assert_eq!(
1510 array1_mm.human_friendly_type(),
1511 "an array of `number(mm)` with 1 value".to_string()
1512 );
1513
1514 let array2_mm = KclValue::HomArray {
1515 value: vec![mm.clone(), mm.clone()],
1516 ty: RuntimeType::any(),
1517 };
1518 assert_eq!(
1519 array2_mm.human_friendly_type(),
1520 "an array of `number(mm)`, `number(mm)`".to_string()
1521 );
1522
1523 let array3_mm = KclValue::HomArray {
1524 value: vec![mm.clone(), mm.clone(), mm.clone()],
1525 ty: RuntimeType::any(),
1526 };
1527 assert_eq!(
1528 array3_mm.human_friendly_type(),
1529 "an array of `number(mm)`, `number(mm)`, `number(mm)`".to_string()
1530 );
1531
1532 let inches = KclValue::Number {
1533 value: 1.0,
1534 ty: NumericType::Known(UnitType::Length(UnitLength::Inches)),
1535 meta: vec![],
1536 };
1537 let array4 = KclValue::HomArray {
1538 value: vec![mm.clone(), mm.clone(), inches, mm],
1539 ty: RuntimeType::any(),
1540 };
1541 assert_eq!(
1542 array4.human_friendly_type(),
1543 "an array of `number(mm)`, `number(mm)`, `number(in)`, ... with 4 values".to_string()
1544 );
1545
1546 let empty_array = KclValue::HomArray {
1547 value: vec![],
1548 ty: RuntimeType::any(),
1549 };
1550 assert_eq!(empty_array.human_friendly_type(), "an empty array".to_string());
1551
1552 let array_nested = KclValue::HomArray {
1553 value: vec![array2_mm],
1554 ty: RuntimeType::any(),
1555 };
1556 assert_eq!(
1557 array_nested.human_friendly_type(),
1558 "an array of `[any; 2]` with 1 value".to_string()
1559 );
1560 }
1561
1562 fn color_def() -> Arc<EnumTypeDef> {
1563 Arc::new(
1564 EnumTypeDef::new(
1565 EnumTypeId::new(ModuleId::default(), "Color"),
1566 vec!["Red".to_owned(), "Green".to_owned()],
1567 )
1568 .unwrap(),
1569 )
1570 }
1571
1572 fn color_red() -> KclValue {
1573 KclValue::Enum {
1574 value: Box::new(EnumValue::new(color_def(), "Red", vec![])),
1575 }
1576 }
1577
1578 #[test]
1579 fn enum_values_describe_themselves_by_name_and_variant() {
1580 let red = color_red();
1581
1582 assert_eq!(red.human_friendly_type(), "a value of enum `Color`");
1583 assert_eq!(red.value_str(), Some("Color::Red".to_owned()));
1585 assert!(red.show_variable_in_feature_tree());
1586 }
1587
1588 #[test]
1592 fn enum_values_are_exposed_by_nominal_identity() {
1593 let view = crate::execution::KclValueView::from(color_red());
1594 assert_eq!(
1595 view,
1596 crate::execution::KclValueView::Enum {
1597 enum_name: "Color".to_owned(),
1598 variant: "Red".to_owned(),
1599 }
1600 );
1601
1602 let op = crate::execution::cad_op::op_from_kcl_value(&color_red());
1603 assert_eq!(
1604 op,
1605 kcl_api::OpKclValue::Enum {
1606 enum_name: "Color".to_owned(),
1607 variant: "Red".to_owned(),
1608 }
1609 );
1610 }
1611
1612 #[test]
1617 fn enum_values_serialize_as_identity_and_variant() {
1618 assert_eq!(
1619 serde_json::to_value(color_red()).unwrap(),
1620 serde_json::json!({
1621 "type": "Enum",
1622 "value": {
1623 "enum_id": { "module_id": 0, "declared_name": "Color" },
1624 "variant": "Red",
1625 },
1626 })
1627 );
1628 }
1629
1630 #[test]
1631 fn enum_declarations_carry_their_variants() {
1632 let def = EnumTypeDef::new(
1633 EnumTypeId::new(ModuleId::default(), "Color"),
1634 vec!["Red".to_owned(), "Green".to_owned()],
1635 )
1636 .unwrap();
1637
1638 assert_eq!(def.variants(), ["Red", "Green"]);
1639 assert!(def.has_variant("Red"));
1640 assert!(!def.has_variant("Blue"));
1641 assert_ne!(
1644 def.id(),
1645 EnumTypeDef::new(
1646 EnumTypeId::new(ModuleId::from_usize(1), "Color"),
1647 vec!["Red".to_owned(), "Green".to_owned()],
1648 )
1649 .unwrap()
1650 .id()
1651 );
1652 }
1653
1654 #[test]
1655 fn enum_rejects_duplicate_variant() {
1656 let err = EnumTypeDef::new(
1657 EnumTypeId::new(ModuleId::default(), "Color"),
1658 vec!["Red".to_owned(), "Green".to_owned(), "Red".to_owned()],
1659 )
1660 .unwrap_err();
1661
1662 assert_eq!(
1663 err,
1664 DuplicateVariant {
1665 name: "Red".to_owned(),
1666 first_index: 0,
1667 duplicate_index: 2,
1668 }
1669 );
1670 }
1671
1672 #[test]
1673 fn enum_reports_earliest_duplicate() {
1674 let err = EnumTypeDef::new(
1677 EnumTypeId::new(ModuleId::default(), "Color"),
1678 vec![
1679 "Red".to_owned(),
1680 "Green".to_owned(),
1681 "Blue".to_owned(),
1682 "Green".to_owned(),
1683 "Red".to_owned(),
1684 ],
1685 )
1686 .unwrap_err();
1687
1688 assert_eq!(err.name, "Green");
1689 assert_eq!(err.first_index, 1);
1690 assert_eq!(err.duplicate_index, 3);
1691 }
1692}