Skip to main content

kcl_lib/execution/
kcl_value.rs

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/// Any KCL value.
93#[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    // An array where all values have a shared type (not necessarily the same principal type).
132    HomArray {
133        value: Vec<KclValue>,
134        // The type of values, not the array type.
135        #[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    /// Constraint marking the KCL version in which this parameter was added.
216    /// See [`NamedParam::unavailable_reason`].
217    pub added_in: Option<VersionConstraint>,
218    /// If true, this parameter is deprecated regardless of the KCL version.
219    pub deprecated: bool,
220    /// Constraint marking the KCL version at or after which this parameter is deprecated.
221    pub deprecated_since: Option<VersionConstraint>,
222    /// Constraint marking the KCL version at or after which this parameter is
223    /// removed. See [`NamedParam::unavailable_reason`].
224    pub removed_in: Option<VersionConstraint>,
225    pub default_value: Option<DefaultParamVal>,
226    pub ty: Option<Type>,
227    /// The `RuntimeType` that `ty` resolved to when the function declaration
228    /// executed, so the resolution happened in the scope where the signature
229    /// is written. `None` when `ty` is `None`. Populated by
230    /// [`FunctionSource::resolve_signature_types`].
231    pub resolved_ty: Option<RuntimeType>,
232}
233
234/// Why a parameter that the callee declares cannot be passed on the KCL
235/// version governing the current execution. Such a parameter behaves as if
236/// the function never declared it: passing it is an error, and the function
237/// body sees the parameter's default value, which the parser guarantees
238/// exists.
239#[derive(Debug, Clone, Copy, PartialEq, Eq)]
240pub(crate) enum ParamUnavailable<'a> {
241    /// The parameter was added in this KCL version, and the executing version
242    /// is before it.
243    NotYetAdded(&'a VersionConstraint),
244    /// The parameter was removed in this KCL version, and the executing
245    /// version is at or after it.
246    Removed(&'a VersionConstraint),
247}
248
249impl NamedParam {
250    /// Why this parameter cannot be passed on the KCL version governing the
251    /// current execution, or `None` if it can. A pre-release version such as
252    /// "3.0-preview" counts as the release it precedes.
253    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    /// Whether a caller may pass this parameter on the KCL version governing
269    /// the current execution. See [`NamedParam::unavailable_reason`].
270    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    /// The `RuntimeType` that the input (unlabeled) argument's type resolved
279    /// to when the function declaration executed. `None` when the input
280    /// argument has no type annotation. Populated by
281    /// [`FunctionSource::resolve_signature_types`].
282    pub resolved_input_ty: Option<RuntimeType>,
283    pub named_args: IndexMap<String, NamedParam>,
284    pub return_type: Option<Node<Type>>,
285    /// The `RuntimeType` that `return_type` resolved to when the function
286    /// declaration executed. `None` when `return_type` is `None`. Populated
287    /// by [`FunctionSource::resolve_signature_types`].
288    pub resolved_return_ty: Option<RuntimeType>,
289    pub deprecated: bool,
290    /// Constraint on the KCL version at which this function is deprecated, e.g.
291    /// "2.0". When the active `kclVersion` is at or after this, calls trigger a
292    /// deprecation warning.
293    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    /// Look up a labeled parameter by name, treating parameters that are
387    /// unavailable on the executing KCL version (see
388    /// [`NamedParam::unavailable_reason`]) as if the function never declared
389    /// them.
390    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    /// The labeled parameters a caller may pass on the executing KCL version,
397    /// in declaration order. Parameters unavailable on that version are
398    /// excluded.
399    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    /// Resolve every parameter type and the return type of this function's
409    /// signature into a `RuntimeType`, looking type names up in the current
410    /// environment.
411    ///
412    /// This must run while the function declaration executes, so that a type
413    /// name in a signature resolves in the scope where the signature is
414    /// written. Argument and return-value coercion consume the stored results
415    /// and perform no name resolution of their own. A name that does not
416    /// resolve is an error at the declaration, and an experimental type warns
417    /// here, once, rather than at every call.
418    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) = &param.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(&param.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// If you try to compare two `crate::std::StdFn` the results will be meaningless and arbitrary,
458// because they're just function pointers.
459#[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    /// Shared rather than owned so that every value of the enum points at the
470    /// one declaration object, and so that reading the type out of memory,
471    /// which clones the `KclValue`, does not copy the variant list.
472    Enum(Arc<EnumTypeDef>),
473}
474
475impl TypeDef {
476    /// Converts a stored type definition into the type used for runtime checks.
477    /// Enum definitions reduce to their nominal identity, so callers that need
478    /// constructor metadata must retain the `Enum` definition instead.
479    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/// The nominal identity of an enum.
489///
490/// Two enums are the same type only if they come from the same `type`
491/// declaration, so identity is the declaring module plus the name written at
492/// the declaration site. Importing under an alias renames the binding, not the
493/// type, so it leaves identity untouched. Two enums declaring identical variant
494/// names are still distinct types.
495#[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    /// The name at the declaration site, which is what users see in
514    /// diagnostics even when the enum was imported under another name.
515    pub fn declared_name(&self) -> &str {
516        &self.declared_name
517    }
518}
519
520/// A declared enum: its identity plus its variants in declaration order.
521#[derive(Debug, Clone, PartialEq)]
522pub struct EnumTypeDef {
523    id: EnumTypeId,
524    variants: Vec<String>,
525}
526
527/// Two variants of one enum declared under the same name, e.g.
528/// `type Color { | Red | Red }`.
529///
530/// Carries indices into the variant list rather than source ranges so that
531/// `EnumTypeDef` stays independent of the AST and of diagnostic types. The
532/// caller holds the declaration, so it can turn an index back into the range it
533/// needs for the error it reports.
534#[derive(Debug, Clone, PartialEq)]
535pub struct DuplicateVariant {
536    /// The name declared twice.
537    pub name: String,
538    /// Where the name was first declared.
539    pub first_index: usize,
540    /// Where it was declared again. Always greater than `first_index`.
541    pub duplicate_index: usize,
542}
543
544impl EnumTypeDef {
545    /// Variant names must be unique, so this is the only way to build an
546    /// `EnumTypeDef` and it rejects a repeat rather than dropping it. Silently
547    /// collapsing duplicates would deny the user a diagnostic naming the variant
548    /// they typed twice.
549    ///
550    /// Reports the earliest repeat when a declaration contains several.
551    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/// A value of an enum type, i.e. one of its variants.
579///
580/// V1 variants are nullary, so the variant name is the entire value. The value
581/// holds its declaration rather than only the declaration's identity, which is
582/// what lets a variant be projected to its declared representation: that
583/// representation is per-variant declaration data, and a value cannot find its
584/// declaration by name, because an import alias renames the binding and a value
585/// can reach a module that never imported the type at all. The declaration is
586/// reachable, not part of the value: identity and equality read the declaration's
587/// id and the variant name, never a representation.
588#[derive(Debug, Clone, Serialize)]
589pub struct EnumValue {
590    /// Serialized as `enum_id` so that the exposed shape stays the nominal
591    /// identity plus the variant, and no declaration data leaks into snapshots
592    /// or the memory pane.
593    #[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
604/// Two values are equal when they name the same variant of the same declaration.
605/// Written out rather than derived because the declaration handle is a route to
606/// the declaration and not part of the value: comparing it would, once variants
607/// carry representations, let a representation decide equality.
608impl 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    /// The string this variant projects to under `enumValue: string`.
636    ///
637    /// The declared representation of the variant, which in V1 is always the
638    /// variant name because no variant can declare a `@repr` yet. This is the
639    /// single place that answers the question, so when `@repr` lands it reads the
640    /// declaration here rather than adding a second notion of representation at
641    /// the projection site.
642    pub fn declared_string_repr(&self) -> String {
643        self.variant.clone()
644    }
645
646    /// How the value is written in KCL and shown to users, e.g. `Color::Red`.
647    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    /// Returns true if we should generate an [`crate::execution::Operation`] to
823    /// display in the Feature Tree for variable declarations initialized with
824    /// this value.
825    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    /// Human readable type name used in error messages.  Should not be relied
855    /// on for program logic.
856    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                    // A max of 3 is good because it's common to use 3D points.
896                    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                            // Insert at the start of the file.
955                            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    /// Put the point into a KCL value.
1011    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    /// Put the point into a KCL value.
1039    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    /// Put the point into a KCL point.
1064    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    /// Put the point into a KCL point.
1080    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            // The original sketch var (if any) lives in `sketch_vars` and carries
1108            // its own node_path; this synthesized wrapper isn't pushed there, so
1109            // its node_path doesn't drive var-solution writeback.
1110            UnsolvedExpr::Unknown(var_id) => crate::execution::KclValue::SketchVar {
1111                value: Box::new(SketchVar {
1112                    id: var_id,
1113                    initial_value: Default::default(),
1114                    // TODO: Should this be the solver units?
1115                    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    /// A solved segment.
1273    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    /// A solved segment.
1284    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    /// If this value is of type function, return it.
1324    pub fn as_function(&self) -> Option<&FunctionSource> {
1325        match self {
1326            KclValue::Function { value, .. } => Some(value),
1327            _ => None,
1328        }
1329    }
1330
1331    /// Get a tag identifier from a memory item.
1332    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    /// Get a tag declarator from a memory item.
1343    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    /// If this KCL value is a bool, retrieve it.
1354    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            // TODO: Show units.
1374            KclValue::Number { value, .. } => Some(format!("{value}")),
1375            KclValue::String { value, .. } => Some(format!("'{value}'")),
1376            KclValue::Enum { value } => Some(value.qualified_name()),
1377            // TODO: Show units.
1378            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            // TODO better Array and Object stringification
1383            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        // View dependencies and AST exports share one output directory in CI.
1455        // Both definitions must survive regardless of which exporter runs last.
1456        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        // Feature-tree and variable display use the qualified form.
1584        assert_eq!(red.value_str(), Some("Color::Red".to_owned()));
1585        assert!(red.show_variable_in_feature_tree());
1586    }
1587
1588    /// The externally visible form of an enum value is its nominal identity,
1589    /// never a representation of the variant. Pinning both view types keeps a
1590    /// future `@repr` from leaking out of these surfaces by accident.
1591    #[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    /// Serialization is the third such surface, and the one that reaches
1613    /// `program_memory.snap`. A value holds its whole declaration, so this pins
1614    /// that only the identity and the variant are written out: the declaration
1615    /// will carry `@repr` values, and those must not appear here.
1616    #[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        // Identity is the declaration, not the variant set: an enum declaring
1642        // the same variants elsewhere is a different type.
1643        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        // `Green` repeats at index 3 and `Red` at index 4. The caller reports one
1675        // duplicate, so it must be the one the user reads first.
1676        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}