1use std::num::NonZeroU32;
2
3use anyhow::Result;
4use kcmc::{
5 shared::BodyType,
6 units::{UnitAngle, UnitLength},
7};
8use kittycad_modeling_cmds as kcmc;
9use serde::Serialize;
10
11use super::fillet::EdgeReference;
12pub use crate::execution::fn_call::Args;
13use crate::{
14 CompilationError, MetaSettings, ModuleId, SourceRange,
15 errors::{KclError, KclErrorDetails},
16 execution::{
17 ExecState, ExtrudeSurface, Helix, KclObjectFields, KclValue, Metadata, Plane, PlaneInfo, Sketch, SketchSurface,
18 Solid, TagIdentifier, annotations,
19 kcl_value::FunctionSource,
20 types::{NumericSuffixTypeConvertError, NumericType, PrimitiveType, RuntimeType, UnitType},
21 },
22 front::Number,
23 parsing::ast::types::TagNode,
24 std::{
25 shapes::{PolygonType, SketchOrSurface},
26 sketch::FaceTag,
27 sweep::SweepPath,
28 },
29};
30
31const ERROR_STRING_SKETCH_TO_SOLID_HELPER: &str =
32 "You can convert a sketch (2D) into a Solid (3D) by calling a function like `extrude` or `revolve`";
33
34#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
35#[ts(export)]
36#[serde(rename_all = "camelCase")]
37pub struct TyF64 {
38 pub n: f64,
39 pub ty: NumericType,
40}
41
42impl TyF64 {
43 pub const fn new(n: f64, ty: NumericType) -> Self {
44 Self { n, ty }
45 }
46
47 pub fn from_number(n: Number, settings: &MetaSettings) -> Self {
48 Self {
49 n: n.value,
50 ty: NumericType::from_parsed(n.units, settings),
51 }
52 }
53
54 pub fn to_mm(&self) -> f64 {
55 self.to_length_units(UnitLength::Millimeters)
56 }
57
58 pub fn to_length_units(&self, units: UnitLength) -> f64 {
59 let len = match &self.ty {
60 NumericType::Default { len, .. } => *len,
61 NumericType::Known(UnitType::Length(len)) => *len,
62 t => unreachable!("expected length, found {t:?}"),
63 };
64
65 crate::execution::types::adjust_length(len, self.n, units).0
66 }
67
68 pub fn to_degrees(&self, exec_state: &mut ExecState, source_range: SourceRange) -> f64 {
69 let angle = match self.ty {
70 NumericType::Default { angle, .. } => {
71 if self.n != 0.0 {
72 exec_state.warn(
73 CompilationError::err(source_range, "Prefer to use explicit units for angles"),
74 annotations::WARN_ANGLE_UNITS,
75 );
76 }
77 angle
78 }
79 NumericType::Known(UnitType::Angle(angle)) => angle,
80 _ => unreachable!(),
81 };
82
83 crate::execution::types::adjust_angle(angle, self.n, UnitAngle::Degrees).0
84 }
85
86 pub fn to_radians(&self, exec_state: &mut ExecState, source_range: SourceRange) -> f64 {
87 let angle = match self.ty {
88 NumericType::Default { angle, .. } => {
89 if self.n != 0.0 {
90 exec_state.warn(
91 CompilationError::err(source_range, "Prefer to use explicit units for angles"),
92 annotations::WARN_ANGLE_UNITS,
93 );
94 }
95 angle
96 }
97 NumericType::Known(UnitType::Angle(angle)) => angle,
98 _ => unreachable!(),
99 };
100
101 crate::execution::types::adjust_angle(angle, self.n, UnitAngle::Radians).0
102 }
103 pub fn count(n: f64) -> Self {
104 Self {
105 n,
106 ty: NumericType::count(),
107 }
108 }
109
110 pub fn map_value(mut self, n: f64) -> Self {
111 self.n = n;
112 self
113 }
114
115 pub fn to_point2d(value: &[TyF64; 2]) -> Result<crate::front::Point2d<Number>, NumericSuffixTypeConvertError> {
118 Ok(crate::front::Point2d {
119 x: Number {
120 value: value[0].n,
121 units: value[0].ty.try_into()?,
122 },
123 y: Number {
124 value: value[1].n,
125 units: value[1].ty.try_into()?,
126 },
127 })
128 }
129}
130
131impl Args {
132 pub(crate) fn get_kw_arg_opt<T>(
133 &self,
134 label: &str,
135 ty: &RuntimeType,
136 exec_state: &mut ExecState,
137 ) -> Result<Option<T>, KclError>
138 where
139 T: for<'a> FromKclValue<'a>,
140 {
141 match self.labeled.get(label) {
142 None => return Ok(None),
143 Some(a) => {
144 if let KclValue::KclNone { .. } = &a.value {
145 return Ok(None);
146 }
147 }
148 }
149
150 self.get_kw_arg(label, ty, exec_state).map(Some)
151 }
152
153 pub(crate) fn get_kw_arg<T>(&self, label: &str, ty: &RuntimeType, exec_state: &mut ExecState) -> Result<T, KclError>
154 where
155 T: for<'a> FromKclValue<'a>,
156 {
157 let Some(arg) = self.labeled.get(label) else {
158 return Err(KclError::new_semantic(KclErrorDetails::new(
159 if let Some(ref fname) = self.fn_name {
160 format!("The `{fname}` function requires a keyword argument `{label}`")
161 } else {
162 format!("This function requires a keyword argument `{label}`")
163 },
164 vec![self.source_range],
165 )));
166 };
167
168 let arg = arg.value.coerce(ty, true, exec_state).map_err(|_| {
169 let actual_type = arg.value.principal_type();
170 let actual_type_name = actual_type
171 .as_ref()
172 .map(|t| t.to_string())
173 .unwrap_or_else(|| arg.value.human_friendly_type());
174 let msg_base = if let Some(ref fname) = self.fn_name {
175 format!("The `{fname}` function expected its `{label}` argument to be {} but it's actually of type {actual_type_name}", ty.human_friendly_type())
176 } else {
177 format!("This function expected its `{label}` argument to be {} but it's actually of type {actual_type_name}", ty.human_friendly_type())
178 };
179 let suggestion = match (ty, actual_type) {
180 (RuntimeType::Primitive(PrimitiveType::Solid), Some(RuntimeType::Primitive(PrimitiveType::Sketch))) => {
181 Some(ERROR_STRING_SKETCH_TO_SOLID_HELPER)
182 }
183 (RuntimeType::Array(t, _), Some(RuntimeType::Primitive(PrimitiveType::Sketch)))
184 if **t == RuntimeType::Primitive(PrimitiveType::Solid) =>
185 {
186 Some(ERROR_STRING_SKETCH_TO_SOLID_HELPER)
187 }
188 _ => None,
189 };
190 let mut message = match suggestion {
191 None => msg_base,
192 Some(sugg) => format!("{msg_base}. {sugg}"),
193 };
194 if message.contains("one or more Solids or ImportedGeometry but it's actually of type Sketch") {
195 message = format!("{message}. {ERROR_STRING_SKETCH_TO_SOLID_HELPER}");
196 }
197 KclError::new_semantic(KclErrorDetails::new(message, arg.source_ranges()))
198 })?;
199
200 T::from_kcl_val(&arg).ok_or_else(|| {
201 KclError::new_internal(KclErrorDetails::new(
202 format!("Mismatch between type coercion and value extraction (this isn't your fault).\nTo assist in bug-reporting, expected type: {ty:?}; actual value: {arg:?}"),
203 vec![self.source_range],
204 ))
205 })
206 }
207
208 pub(crate) fn kw_arg_edge_array_and_source(
211 &self,
212 label: &str,
213 ) -> Result<Vec<(EdgeReference, SourceRange)>, KclError> {
214 let Some(arg) = self.labeled.get(label) else {
215 let err = KclError::new_semantic(KclErrorDetails::new(
216 if let Some(ref fname) = self.fn_name {
217 format!("The `{fname}` function requires a keyword argument '{label}'")
218 } else {
219 format!("This function requires a keyword argument '{label}'")
220 },
221 vec![self.source_range],
222 ));
223 return Err(err);
224 };
225 arg.value
226 .clone()
227 .into_array()
228 .iter()
229 .map(|item| {
230 let source = SourceRange::from(item);
231 let val = FromKclValue::from_kcl_val(item).ok_or_else(|| {
232 KclError::new_semantic(KclErrorDetails::new(
233 format!("Expected an Edge but found {}", arg.value.human_friendly_type()),
234 arg.source_ranges(),
235 ))
236 })?;
237 Ok((val, source))
238 })
239 .collect::<Result<Vec<_>, _>>()
240 }
241
242 pub(crate) fn get_unlabeled_kw_arg_array_and_type(
243 &self,
244 label: &str,
245 exec_state: &mut ExecState,
246 ) -> Result<(Vec<KclValue>, RuntimeType), KclError> {
247 let value = self.get_unlabeled_kw_arg(label, &RuntimeType::any_array(), exec_state)?;
248 Ok(match value {
249 KclValue::HomArray { value, ty } => (value, ty),
250 KclValue::Tuple { value, .. } => (value, RuntimeType::any()),
251 val => (vec![val], RuntimeType::any()),
252 })
253 }
254
255 pub(crate) fn get_unlabeled_kw_arg<T>(
258 &self,
259 label: &str,
260 ty: &RuntimeType,
261 exec_state: &mut ExecState,
262 ) -> Result<T, KclError>
263 where
264 T: for<'a> FromKclValue<'a>,
265 {
266 let arg = self
267 .unlabeled_kw_arg_unconverted()
268 .ok_or(KclError::new_semantic(KclErrorDetails::new(
269 if let Some(ref fname) = self.fn_name {
270 format!(
271 "The `{fname}` function requires a value for the special unlabeled first parameter, '{label}'"
272 )
273 } else {
274 format!("This function requires a value for the special unlabeled first parameter, '{label}'")
275 },
276 vec![self.source_range],
277 )))?;
278
279 let arg = arg.value.coerce(ty, true, exec_state).map_err(|_| {
280 let actual_type = arg.value.principal_type();
281 let actual_type_name = actual_type
282 .as_ref()
283 .map(|t| t.to_string())
284 .unwrap_or_else(|| arg.value.human_friendly_type());
285 let msg_base = if let Some(ref fname) = self.fn_name {
286 format!(
287 "The `{fname}` function expected the input argument to be {} but it's actually of type {actual_type_name}",
288 ty.human_friendly_type(),
289 )
290 } else {
291 format!(
292 "This function expected the input argument to be {} but it's actually of type {actual_type_name}",
293 ty.human_friendly_type(),
294 )
295 };
296 let suggestion = match (ty, actual_type) {
297 (RuntimeType::Primitive(PrimitiveType::Solid), Some(RuntimeType::Primitive(PrimitiveType::Sketch))) => {
298 Some(ERROR_STRING_SKETCH_TO_SOLID_HELPER)
299 }
300 (RuntimeType::Array(ty, _), Some(RuntimeType::Primitive(PrimitiveType::Sketch)))
301 if **ty == RuntimeType::Primitive(PrimitiveType::Solid) =>
302 {
303 Some(ERROR_STRING_SKETCH_TO_SOLID_HELPER)
304 }
305 _ => None,
306 };
307 let mut message = match suggestion {
308 None => msg_base,
309 Some(sugg) => format!("{msg_base}. {sugg}"),
310 };
311
312 if message.contains("one or more Solids or ImportedGeometry but it's actually of type Sketch") {
313 message = format!("{message}. {ERROR_STRING_SKETCH_TO_SOLID_HELPER}");
314 }
315 KclError::new_semantic(KclErrorDetails::new(message, arg.source_ranges()))
316 })?;
317
318 T::from_kcl_val(&arg).ok_or_else(|| {
319 KclError::new_internal(KclErrorDetails::new(
320 format!("Mismatch between type coercion and value extraction (this isn't your fault).\nTo assist in bug-reporting, expected type: {ty:?}; actual value: {arg:?}"),
321 vec![self.source_range],
322 ))
323 })
324 }
325
326 fn get_tag_info_from_memory<'a, 'e>(
328 &'a self,
329 exec_state: &'e mut ExecState,
330 tag: &'a TagIdentifier,
331 ) -> Result<&'e crate::execution::TagEngineInfo, KclError> {
332 if let (epoch, KclValue::TagIdentifier(t)) =
333 exec_state.stack().get_from_call_stack(&tag.value, self.source_range)?
334 {
335 let info = t.get_info(epoch).ok_or_else(|| {
336 KclError::new_type(KclErrorDetails::new(
337 format!("Tag `{}` does not have engine info", tag.value),
338 vec![self.source_range],
339 ))
340 })?;
341 Ok(info)
342 } else {
343 Err(KclError::new_type(KclErrorDetails::new(
344 format!("Tag `{}` does not exist", tag.value),
345 vec![self.source_range],
346 )))
347 }
348 }
349
350 pub(crate) fn get_tag_engine_info<'a, 'e>(
352 &'a self,
353 exec_state: &'e mut ExecState,
354 tag: &'a TagIdentifier,
355 ) -> Result<&'a crate::execution::TagEngineInfo, KclError>
356 where
357 'e: 'a,
358 {
359 if let Some(info) = tag.get_cur_info() {
360 return Ok(info);
361 }
362
363 self.get_tag_info_from_memory(exec_state, tag)
364 }
365
366 fn get_tag_engine_info_check_surface<'a, 'e>(
368 &'a self,
369 exec_state: &'e mut ExecState,
370 tag: &'a TagIdentifier,
371 ) -> Result<&'a crate::execution::TagEngineInfo, KclError>
372 where
373 'e: 'a,
374 {
375 if let Some(info) = tag.get_cur_info()
376 && info.surface.is_some()
377 {
378 return Ok(info);
379 }
380
381 self.get_tag_info_from_memory(exec_state, tag)
382 }
383
384 pub(crate) fn make_kcl_val_from_point(&self, p: [f64; 2], ty: NumericType) -> Result<KclValue, KclError> {
385 let meta = Metadata {
386 source_range: self.source_range,
387 };
388 let x = KclValue::Number {
389 value: p[0],
390 meta: vec![meta],
391 ty,
392 };
393 let y = KclValue::Number {
394 value: p[1],
395 meta: vec![meta],
396 ty,
397 };
398 let ty = RuntimeType::Primitive(PrimitiveType::Number(ty));
399
400 Ok(KclValue::HomArray { value: vec![x, y], ty })
401 }
402
403 pub(super) fn make_user_val_from_f64_with_type(&self, f: TyF64) -> KclValue {
404 KclValue::from_number_with_type(
405 f.n,
406 f.ty,
407 vec![Metadata {
408 source_range: self.source_range,
409 }],
410 )
411 }
412
413 pub(crate) async fn get_adjacent_face_to_tag(
415 &self,
416 exec_state: &mut ExecState,
417 tag: &TagIdentifier,
418 must_be_planar: bool,
419 ) -> Result<uuid::Uuid, KclError> {
420 if tag.value.is_empty() {
421 return Err(KclError::new_type(KclErrorDetails::new(
422 "Expected a non-empty tag for the face".to_string(),
423 vec![self.source_range],
424 )));
425 }
426
427 let engine_info = self.get_tag_engine_info_check_surface(exec_state, tag)?;
428
429 let surface = engine_info.surface.as_ref().ok_or_else(|| {
430 KclError::new_type(KclErrorDetails::new(
431 format!("Tag `{}` does not have a surface", tag.value),
432 vec![self.source_range],
433 ))
434 })?;
435
436 if let Some(face_from_surface) = match surface {
437 ExtrudeSurface::ExtrudePlane(extrude_plane) => {
438 if let Some(plane_tag) = &extrude_plane.tag {
439 if plane_tag.name == tag.value {
440 Some(Ok(extrude_plane.face_id))
441 } else {
442 None
443 }
444 } else {
445 None
446 }
447 }
448 ExtrudeSurface::ExtrudeArc(_) if must_be_planar => Some(Err(KclError::new_type(KclErrorDetails::new(
450 format!("Tag `{}` is a non-planar surface", tag.value),
451 vec![self.source_range],
452 )))),
453 ExtrudeSurface::ExtrudeArc(extrude_arc) => {
454 if let Some(arc_tag) = &extrude_arc.tag {
455 if arc_tag.name == tag.value {
456 Some(Ok(extrude_arc.face_id))
457 } else {
458 None
459 }
460 } else {
461 None
462 }
463 }
464 ExtrudeSurface::Chamfer(chamfer) => {
465 if let Some(chamfer_tag) = &chamfer.tag {
466 if chamfer_tag.name == tag.value {
467 Some(Ok(chamfer.face_id))
468 } else {
469 None
470 }
471 } else {
472 None
473 }
474 }
475 ExtrudeSurface::Fillet(_) if must_be_planar => Some(Err(KclError::new_type(KclErrorDetails::new(
477 format!("Tag `{}` is a non-planar surface", tag.value),
478 vec![self.source_range],
479 )))),
480 ExtrudeSurface::Fillet(fillet) => {
481 if let Some(fillet_tag) = &fillet.tag {
482 if fillet_tag.name == tag.value {
483 Some(Ok(fillet.face_id))
484 } else {
485 None
486 }
487 } else {
488 None
489 }
490 }
491 } {
492 return face_from_surface;
493 }
494
495 Err(KclError::new_type(KclErrorDetails::new(
497 format!("Expected a face with the tag `{}`", tag.value),
498 vec![self.source_range],
499 )))
500 }
501}
502
503pub trait FromKclValue<'a>: Sized {
505 fn from_kcl_val(arg: &'a KclValue) -> Option<Self>;
507}
508
509impl<'a> FromKclValue<'a> for TagNode {
510 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
511 arg.get_tag_declarator().ok()
512 }
513}
514
515impl<'a> FromKclValue<'a> for TagIdentifier {
516 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
517 arg.get_tag_identifier().ok()
518 }
519}
520
521impl<'a> FromKclValue<'a> for Vec<TagIdentifier> {
522 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
523 let tags = arg
524 .clone()
525 .into_array()
526 .iter()
527 .map(|v| v.get_tag_identifier().unwrap())
528 .collect();
529 Some(tags)
530 }
531}
532
533impl<'a> FromKclValue<'a> for Vec<KclValue> {
534 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
535 Some(arg.clone().into_array())
536 }
537}
538
539impl<'a> FromKclValue<'a> for KclValue {
540 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
541 Some(arg.clone())
542 }
543}
544
545macro_rules! let_field_of {
546 ($obj:ident, $field:ident?) => {
548 let $field = $obj.get(stringify!($field)).and_then(FromKclValue::from_kcl_val);
549 };
550 ($obj:ident, $field:ident? $key:literal) => {
552 let $field = $obj.get($key).and_then(FromKclValue::from_kcl_val);
553 };
554 ($obj:ident, $field:ident $key:literal) => {
556 let $field = $obj.get($key).and_then(FromKclValue::from_kcl_val)?;
557 };
558 ($obj:ident, $field:ident $(, $annotation:ty)?) => {
560 let $field $(: $annotation)? = $obj.get(stringify!($field)).and_then(FromKclValue::from_kcl_val)?;
561 };
562}
563
564impl<'a> FromKclValue<'a> for crate::execution::Plane {
565 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
566 arg.as_plane().cloned()
567 }
568}
569
570impl<'a> FromKclValue<'a> for crate::execution::PlaneType {
571 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
572 let plane_type = match arg.as_str()? {
573 "XY" | "xy" => Self::XY,
574 "XZ" | "xz" => Self::XZ,
575 "YZ" | "yz" => Self::YZ,
576 "Custom" => Self::Custom,
577 _ => return None,
578 };
579 Some(plane_type)
580 }
581}
582
583impl<'a> FromKclValue<'a> for BodyType {
584 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
585 let body_type = match arg.as_str()? {
586 "solid" => Self::Solid,
587 "surface" => Self::Surface,
588 _ => return None,
589 };
590 Some(body_type)
591 }
592}
593
594impl<'a> FromKclValue<'a> for kittycad_modeling_cmds::units::UnitLength {
595 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
596 let s = arg.as_str()?;
597 s.parse().ok()
598 }
599}
600
601impl<'a> FromKclValue<'a> for kittycad_modeling_cmds::coord::System {
602 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
603 let obj = arg.as_object()?;
604 let_field_of!(obj, forward);
605 let_field_of!(obj, up);
606 Some(Self { forward, up })
607 }
608}
609
610impl<'a> FromKclValue<'a> for kittycad_modeling_cmds::coord::AxisDirectionPair {
611 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
612 let obj = arg.as_object()?;
613 let_field_of!(obj, axis);
614 let_field_of!(obj, direction);
615 Some(Self { axis, direction })
616 }
617}
618
619impl<'a> FromKclValue<'a> for kittycad_modeling_cmds::coord::Axis {
620 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
621 let s = arg.as_str()?;
622 match s {
623 "y" => Some(Self::Y),
624 "z" => Some(Self::Z),
625 _ => None,
626 }
627 }
628}
629
630impl<'a> FromKclValue<'a> for PolygonType {
631 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
632 let s = arg.as_str()?;
633 match s {
634 "inscribed" => Some(Self::Inscribed),
635 _ => Some(Self::Circumscribed),
636 }
637 }
638}
639
640impl<'a> FromKclValue<'a> for kittycad_modeling_cmds::coord::Direction {
641 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
642 let s = arg.as_str()?;
643 match s {
644 "positive" => Some(Self::Positive),
645 "negative" => Some(Self::Negative),
646 _ => None,
647 }
648 }
649}
650
651impl<'a> FromKclValue<'a> for crate::execution::Geometry {
652 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
653 match arg {
654 KclValue::Sketch { value } => Some(Self::Sketch(*value.to_owned())),
655 KclValue::Solid { value } => Some(Self::Solid(*value.to_owned())),
656 _ => None,
657 }
658 }
659}
660
661impl<'a> FromKclValue<'a> for crate::execution::GeometryWithImportedGeometry {
662 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
663 match arg {
664 KclValue::Sketch { value } => Some(Self::Sketch(*value.to_owned())),
665 KclValue::Solid { value } => Some(Self::Solid(*value.to_owned())),
666 KclValue::ImportedGeometry(value) => Some(Self::ImportedGeometry(Box::new(value.clone()))),
667 _ => None,
668 }
669 }
670}
671
672impl<'a> FromKclValue<'a> for FaceTag {
673 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
674 let case1 = || match arg.as_str() {
675 Some("start" | "START") => Some(Self::StartOrEnd(super::sketch::StartOrEnd::Start)),
676 Some("end" | "END") => Some(Self::StartOrEnd(super::sketch::StartOrEnd::End)),
677 _ => None,
678 };
679 let case2 = || {
680 let tag = TagIdentifier::from_kcl_val(arg)?;
681 Some(Self::Tag(Box::new(tag)))
682 };
683 case1().or_else(case2)
684 }
685}
686
687impl<'a> FromKclValue<'a> for super::sketch::TangentialArcData {
688 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
689 let obj = arg.as_object()?;
690 let_field_of!(obj, radius);
691 let_field_of!(obj, offset);
692 Some(Self::RadiusAndOffset { radius, offset })
693 }
694}
695
696impl<'a> FromKclValue<'a> for crate::execution::Point3d {
697 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
698 if let Some(obj) = arg.as_object() {
700 let_field_of!(obj, x, TyF64);
701 let_field_of!(obj, y, TyF64);
702 let_field_of!(obj, z, TyF64);
703 let (a, ty) = NumericType::combine_eq_array(&[x, y, z]);
705 return Some(Self {
706 x: a[0],
707 y: a[1],
708 z: a[2],
709 units: ty.as_length(),
710 });
711 }
712 let [x, y, z]: [TyF64; 3] = FromKclValue::from_kcl_val(arg)?;
714 let (a, ty) = NumericType::combine_eq_array(&[x, y, z]);
715 Some(Self {
716 x: a[0],
717 y: a[1],
718 z: a[2],
719 units: ty.as_length(),
720 })
721 }
722}
723
724impl<'a> FromKclValue<'a> for super::sketch::PlaneData {
725 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
726 if let KclValue::Plane { value } = arg {
728 return Some(Self::Plane(PlaneInfo {
729 origin: value.info.origin,
730 x_axis: value.info.x_axis,
731 y_axis: value.info.y_axis,
732 z_axis: value.info.z_axis,
733 }));
734 }
735 if let Some(s) = arg.as_str() {
737 return match s {
738 "XY" | "xy" => Some(Self::XY),
739 "-XY" | "-xy" => Some(Self::NegXY),
740 "XZ" | "xz" => Some(Self::XZ),
741 "-XZ" | "-xz" => Some(Self::NegXZ),
742 "YZ" | "yz" => Some(Self::YZ),
743 "-YZ" | "-yz" => Some(Self::NegYZ),
744 _ => None,
745 };
746 }
747 let obj = arg.as_object()?;
749 let_field_of!(obj, plane, &KclObjectFields);
750 let origin = plane.get("origin").and_then(FromKclValue::from_kcl_val)?;
751 let x_axis: crate::execution::Point3d = plane.get("xAxis").and_then(FromKclValue::from_kcl_val)?;
752 let y_axis = plane.get("yAxis").and_then(FromKclValue::from_kcl_val)?;
753 let z_axis = x_axis.axes_cross_product(&y_axis);
754 Some(Self::Plane(PlaneInfo {
755 origin,
756 x_axis,
757 y_axis,
758 z_axis,
759 }))
760 }
761}
762
763impl<'a> FromKclValue<'a> for crate::execution::ExtrudePlane {
764 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
765 let obj = arg.as_object()?;
766 let_field_of!(obj, face_id "faceId");
767 let tag = FromKclValue::from_kcl_val(obj.get("tag")?);
768 let_field_of!(obj, geo_meta "geoMeta");
769 Some(Self { face_id, tag, geo_meta })
770 }
771}
772
773impl<'a> FromKclValue<'a> for crate::execution::ExtrudeArc {
774 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
775 let obj = arg.as_object()?;
776 let_field_of!(obj, face_id "faceId");
777 let tag = FromKclValue::from_kcl_val(obj.get("tag")?);
778 let_field_of!(obj, geo_meta "geoMeta");
779 Some(Self { face_id, tag, geo_meta })
780 }
781}
782
783impl<'a> FromKclValue<'a> for crate::execution::GeoMeta {
784 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
785 let obj = arg.as_object()?;
786 let_field_of!(obj, id);
787 let_field_of!(obj, source_range "sourceRange");
788 Some(Self {
789 id,
790 metadata: Metadata { source_range },
791 })
792 }
793}
794
795impl<'a> FromKclValue<'a> for crate::execution::ChamferSurface {
796 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
797 let obj = arg.as_object()?;
798 let_field_of!(obj, face_id "faceId");
799 let tag = FromKclValue::from_kcl_val(obj.get("tag")?);
800 let_field_of!(obj, geo_meta "geoMeta");
801 Some(Self { face_id, tag, geo_meta })
802 }
803}
804
805impl<'a> FromKclValue<'a> for crate::execution::FilletSurface {
806 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
807 let obj = arg.as_object()?;
808 let_field_of!(obj, face_id "faceId");
809 let tag = FromKclValue::from_kcl_val(obj.get("tag")?);
810 let_field_of!(obj, geo_meta "geoMeta");
811 Some(Self { face_id, tag, geo_meta })
812 }
813}
814
815impl<'a> FromKclValue<'a> for ExtrudeSurface {
816 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
817 let case1 = crate::execution::ExtrudePlane::from_kcl_val;
818 let case2 = crate::execution::ExtrudeArc::from_kcl_val;
819 let case3 = crate::execution::ChamferSurface::from_kcl_val;
820 let case4 = crate::execution::FilletSurface::from_kcl_val;
821 case1(arg)
822 .map(Self::ExtrudePlane)
823 .or_else(|| case2(arg).map(Self::ExtrudeArc))
824 .or_else(|| case3(arg).map(Self::Chamfer))
825 .or_else(|| case4(arg).map(Self::Fillet))
826 }
827}
828
829impl<'a> FromKclValue<'a> for crate::execution::EdgeCut {
830 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
831 let obj = arg.as_object()?;
832 let_field_of!(obj, typ "type");
833 let tag = Box::new(obj.get("tag").and_then(FromKclValue::from_kcl_val));
834 let_field_of!(obj, edge_id "edgeId");
835 let_field_of!(obj, id);
836 match typ {
837 "fillet" => {
838 let_field_of!(obj, radius);
839 Some(Self::Fillet {
840 edge_id,
841 tag,
842 id,
843 radius,
844 })
845 }
846 "chamfer" => {
847 let_field_of!(obj, length);
848 Some(Self::Chamfer {
849 id,
850 length,
851 edge_id,
852 tag,
853 })
854 }
855 _ => None,
856 }
857 }
858}
859
860macro_rules! impl_from_kcl_for_vec {
861 ($typ:path) => {
862 impl<'a> FromKclValue<'a> for Vec<$typ> {
863 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
864 arg.clone()
865 .into_array()
866 .iter()
867 .map(|value| FromKclValue::from_kcl_val(value))
868 .collect::<Option<_>>()
869 }
870 }
871 };
872}
873
874impl_from_kcl_for_vec!(FaceTag);
875impl_from_kcl_for_vec!(crate::execution::EdgeCut);
876impl_from_kcl_for_vec!(crate::execution::Metadata);
877impl_from_kcl_for_vec!(super::fillet::EdgeReference);
878impl_from_kcl_for_vec!(ExtrudeSurface);
879impl_from_kcl_for_vec!(TyF64);
880impl_from_kcl_for_vec!(Solid);
881impl_from_kcl_for_vec!(Sketch);
882
883impl<'a> FromKclValue<'a> for SourceRange {
884 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
885 let value = match arg {
886 KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => value,
887 _ => {
888 return None;
889 }
890 };
891 let [v0, v1, v2] = value.as_slice() else {
892 return None;
893 };
894 Some(SourceRange::new(
895 v0.as_usize()?,
896 v1.as_usize()?,
897 ModuleId::from_usize(v2.as_usize()?),
898 ))
899 }
900}
901
902impl<'a> FromKclValue<'a> for crate::execution::Metadata {
903 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
904 FromKclValue::from_kcl_val(arg).map(|sr| Self { source_range: sr })
905 }
906}
907
908impl<'a> FromKclValue<'a> for crate::execution::Solid {
909 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
910 arg.as_solid().cloned()
911 }
912}
913
914impl<'a> FromKclValue<'a> for crate::execution::SolidOrSketchOrImportedGeometry {
915 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
916 match arg {
917 KclValue::Solid { value } => Some(Self::SolidSet(vec![(**value).clone()])),
918 KclValue::Sketch { value } => Some(Self::SketchSet(vec![(**value).clone()])),
919 KclValue::HomArray { value, .. } => {
920 let mut solids = vec![];
921 let mut sketches = vec![];
922 for item in value {
923 match item {
924 KclValue::Solid { value } => solids.push((**value).clone()),
925 KclValue::Sketch { value } => sketches.push((**value).clone()),
926 _ => return None,
927 }
928 }
929 if !solids.is_empty() {
930 Some(Self::SolidSet(solids))
931 } else {
932 Some(Self::SketchSet(sketches))
933 }
934 }
935 KclValue::ImportedGeometry(value) => Some(Self::ImportedGeometry(Box::new(value.clone()))),
936 _ => None,
937 }
938 }
939}
940
941impl<'a> FromKclValue<'a> for crate::execution::SolidOrImportedGeometry {
942 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
943 match arg {
944 KclValue::Solid { value } => Some(Self::SolidSet(vec![(**value).clone()])),
945 KclValue::HomArray { value, .. } => {
946 let mut solids = vec![];
947 for item in value {
948 match item {
949 KclValue::Solid { value } => solids.push((**value).clone()),
950 _ => return None,
951 }
952 }
953 Some(Self::SolidSet(solids))
954 }
955 KclValue::ImportedGeometry(value) => Some(Self::ImportedGeometry(Box::new(value.clone()))),
956 _ => None,
957 }
958 }
959}
960
961impl<'a> FromKclValue<'a> for super::sketch::SketchData {
962 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
963 let case1 = crate::execution::Plane::from_kcl_val;
965 let case2 = super::sketch::PlaneData::from_kcl_val;
966 let case3 = crate::execution::Solid::from_kcl_val;
967 let case4 = <Vec<Solid>>::from_kcl_val;
968 case1(arg)
969 .map(Box::new)
970 .map(Self::Plane)
971 .or_else(|| case2(arg).map(Self::PlaneOrientation))
972 .or_else(|| case3(arg).map(Box::new).map(Self::Solid))
973 .or_else(|| case4(arg).map(|v| Box::new(v[0].clone())).map(Self::Solid))
974 }
975}
976
977impl<'a> FromKclValue<'a> for super::fillet::EdgeReference {
978 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
979 let id = arg.as_uuid().map(Self::Uuid);
980 let tag = || TagIdentifier::from_kcl_val(arg).map(Box::new).map(Self::Tag);
981 id.or_else(tag)
982 }
983}
984
985impl<'a> FromKclValue<'a> for super::axis_or_reference::Axis2dOrEdgeReference {
986 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
987 let case1 = |arg: &KclValue| {
988 let obj = arg.as_object()?;
989 let_field_of!(obj, direction);
990 let_field_of!(obj, origin);
991 Some(Self::Axis { direction, origin })
992 };
993 let case2 = super::fillet::EdgeReference::from_kcl_val;
994 case1(arg).or_else(|| case2(arg).map(Self::Edge))
995 }
996}
997
998impl<'a> FromKclValue<'a> for super::axis_or_reference::Axis3dOrEdgeReference {
999 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1000 let case1 = |arg: &KclValue| {
1001 let obj = arg.as_object()?;
1002 let_field_of!(obj, direction);
1003 let_field_of!(obj, origin);
1004 Some(Self::Axis { direction, origin })
1005 };
1006 let case2 = super::fillet::EdgeReference::from_kcl_val;
1007 case1(arg).or_else(|| case2(arg).map(Self::Edge))
1008 }
1009}
1010
1011impl<'a> FromKclValue<'a> for super::axis_or_reference::Axis2dOrPoint2d {
1012 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1013 let case1 = |arg: &KclValue| {
1014 let obj = arg.as_object()?;
1015 let_field_of!(obj, direction);
1016 let_field_of!(obj, origin);
1017 Some(Self::Axis { direction, origin })
1018 };
1019 let case2 = <[TyF64; 2]>::from_kcl_val;
1020 case1(arg).or_else(|| case2(arg).map(Self::Point))
1021 }
1022}
1023
1024impl<'a> FromKclValue<'a> for super::axis_or_reference::Axis3dOrPoint3d {
1025 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1026 let case1 = |arg: &KclValue| {
1027 let obj = arg.as_object()?;
1028 let_field_of!(obj, direction);
1029 let_field_of!(obj, origin);
1030 Some(Self::Axis { direction, origin })
1031 };
1032 let case2 = <[TyF64; 3]>::from_kcl_val;
1033 case1(arg).or_else(|| case2(arg).map(Self::Point))
1034 }
1035}
1036
1037impl<'a> FromKclValue<'a> for super::axis_or_reference::Point3dAxis3dOrGeometryReference {
1038 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1039 let case1 = |arg: &KclValue| {
1040 let obj = arg.as_object()?;
1041 let_field_of!(obj, direction);
1042 let_field_of!(obj, origin);
1043 Some(Self::Axis { direction, origin })
1044 };
1045 let case2 = <[TyF64; 3]>::from_kcl_val;
1046 let case3 = super::fillet::EdgeReference::from_kcl_val;
1047 let case4 = FaceTag::from_kcl_val;
1048 let case5 = Box::<Solid>::from_kcl_val;
1049 let case6 = TagIdentifier::from_kcl_val;
1050 let case7 = Box::<Plane>::from_kcl_val;
1051 let case8 = Box::<Sketch>::from_kcl_val;
1052
1053 case1(arg)
1054 .or_else(|| case2(arg).map(Self::Point))
1055 .or_else(|| case3(arg).map(Self::Edge))
1056 .or_else(|| case4(arg).map(Self::Face))
1057 .or_else(|| case5(arg).map(Self::Solid))
1058 .or_else(|| case6(arg).map(Self::TaggedEdgeOrFace))
1059 .or_else(|| case7(arg).map(Self::Plane))
1060 .or_else(|| case8(arg).map(Self::Sketch))
1061 }
1062}
1063
1064impl<'a> FromKclValue<'a> for i64 {
1065 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1066 match arg {
1067 KclValue::Number { value, .. } => crate::try_f64_to_i64(*value),
1068 _ => None,
1069 }
1070 }
1071}
1072
1073impl<'a> FromKclValue<'a> for &'a str {
1074 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1075 let KclValue::String { value, meta: _ } = arg else {
1076 return None;
1077 };
1078 Some(value)
1079 }
1080}
1081
1082impl<'a> FromKclValue<'a> for &'a KclObjectFields {
1083 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1084 let KclValue::Object { value, .. } = arg else {
1085 return None;
1086 };
1087 Some(value)
1088 }
1089}
1090
1091impl<'a> FromKclValue<'a> for uuid::Uuid {
1092 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1093 let KclValue::Uuid { value, meta: _ } = arg else {
1094 return None;
1095 };
1096 Some(*value)
1097 }
1098}
1099
1100impl<'a> FromKclValue<'a> for u32 {
1101 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1102 match arg {
1103 KclValue::Number { value, .. } => crate::try_f64_to_u32(*value),
1104 _ => None,
1105 }
1106 }
1107}
1108
1109impl<'a> FromKclValue<'a> for NonZeroU32 {
1110 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1111 u32::from_kcl_val(arg).and_then(|x| x.try_into().ok())
1112 }
1113}
1114
1115impl<'a> FromKclValue<'a> for u64 {
1116 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1117 match arg {
1118 KclValue::Number { value, .. } => crate::try_f64_to_u64(*value),
1119 _ => None,
1120 }
1121 }
1122}
1123
1124impl<'a> FromKclValue<'a> for TyF64 {
1125 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1126 match arg {
1127 KclValue::Number { value, ty, .. } => Some(TyF64::new(*value, *ty)),
1128 _ => None,
1129 }
1130 }
1131}
1132
1133impl<'a> FromKclValue<'a> for [TyF64; 2] {
1134 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1135 match arg {
1136 KclValue::Tuple { value, meta: _ } | KclValue::HomArray { value, .. } => {
1137 let [v0, v1] = value.as_slice() else {
1138 return None;
1139 };
1140 let array = [v0.as_ty_f64()?, v1.as_ty_f64()?];
1141 Some(array)
1142 }
1143 _ => None,
1144 }
1145 }
1146}
1147
1148impl<'a> FromKclValue<'a> for [TyF64; 3] {
1149 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1150 match arg {
1151 KclValue::Tuple { value, meta: _ } | KclValue::HomArray { value, .. } => {
1152 let [v0, v1, v2] = value.as_slice() else {
1153 return None;
1154 };
1155 let array = [v0.as_ty_f64()?, v1.as_ty_f64()?, v2.as_ty_f64()?];
1156 Some(array)
1157 }
1158 _ => None,
1159 }
1160 }
1161}
1162
1163impl<'a> FromKclValue<'a> for [TyF64; 6] {
1164 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1165 match arg {
1166 KclValue::Tuple { value, meta: _ } | KclValue::HomArray { value, .. } => {
1167 let [v0, v1, v2, v3, v4, v5] = value.as_slice() else {
1168 return None;
1169 };
1170 let array = [
1171 v0.as_ty_f64()?,
1172 v1.as_ty_f64()?,
1173 v2.as_ty_f64()?,
1174 v3.as_ty_f64()?,
1175 v4.as_ty_f64()?,
1176 v5.as_ty_f64()?,
1177 ];
1178 Some(array)
1179 }
1180 _ => None,
1181 }
1182 }
1183}
1184
1185impl<'a> FromKclValue<'a> for Sketch {
1186 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1187 let KclValue::Sketch { value } = arg else {
1188 return None;
1189 };
1190 Some(value.as_ref().to_owned())
1191 }
1192}
1193
1194impl<'a> FromKclValue<'a> for Helix {
1195 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1196 let KclValue::Helix { value } = arg else {
1197 return None;
1198 };
1199 Some(value.as_ref().to_owned())
1200 }
1201}
1202
1203impl<'a> FromKclValue<'a> for SweepPath {
1204 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1205 let case1 = Sketch::from_kcl_val;
1206 let case2 = <Vec<Sketch>>::from_kcl_val;
1207 let case3 = Helix::from_kcl_val;
1208 case1(arg)
1209 .map(Self::Sketch)
1210 .or_else(|| case2(arg).map(|arg0: Vec<Sketch>| Self::Sketch(arg0[0].clone())))
1211 .or_else(|| case3(arg).map(|arg0: Helix| Self::Helix(Box::new(arg0))))
1212 }
1213}
1214impl<'a> FromKclValue<'a> for String {
1215 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1216 let KclValue::String { value, meta: _ } = arg else {
1217 return None;
1218 };
1219 Some(value.to_owned())
1220 }
1221}
1222impl<'a> FromKclValue<'a> for crate::parsing::ast::types::KclNone {
1223 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1224 let KclValue::KclNone { value, meta: _ } = arg else {
1225 return None;
1226 };
1227 Some(value.to_owned())
1228 }
1229}
1230impl<'a> FromKclValue<'a> for bool {
1231 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1232 let KclValue::Bool { value, meta: _ } = arg else {
1233 return None;
1234 };
1235 Some(*value)
1236 }
1237}
1238
1239impl<'a> FromKclValue<'a> for Box<Solid> {
1240 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1241 let KclValue::Solid { value } = arg else {
1242 return None;
1243 };
1244 Some(value.to_owned())
1245 }
1246}
1247
1248impl<'a> FromKclValue<'a> for Box<Plane> {
1249 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1250 let KclValue::Plane { value } = arg else {
1251 return None;
1252 };
1253 Some(value.to_owned())
1254 }
1255}
1256
1257impl<'a> FromKclValue<'a> for Box<Sketch> {
1258 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1259 let KclValue::Sketch { value } = arg else {
1260 return None;
1261 };
1262 Some(value.to_owned())
1263 }
1264}
1265
1266impl<'a> FromKclValue<'a> for FunctionSource {
1267 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1268 arg.as_function().cloned()
1269 }
1270}
1271
1272impl<'a> FromKclValue<'a> for SketchOrSurface {
1273 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1274 match arg {
1275 KclValue::Sketch { value: sg } => Some(Self::Sketch(sg.to_owned())),
1276 KclValue::Plane { value } => Some(Self::SketchSurface(SketchSurface::Plane(value.clone()))),
1277 KclValue::Face { value } => Some(Self::SketchSurface(SketchSurface::Face(value.clone()))),
1278 _ => None,
1279 }
1280 }
1281}
1282impl<'a> FromKclValue<'a> for SketchSurface {
1283 fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
1284 match arg {
1285 KclValue::Plane { value } => Some(Self::Plane(value.clone())),
1286 KclValue::Face { value } => Some(Self::Face(value.clone())),
1287 _ => None,
1288 }
1289 }
1290}
1291
1292impl From<Args> for Metadata {
1293 fn from(value: Args) -> Self {
1294 Self {
1295 source_range: value.source_range,
1296 }
1297 }
1298}
1299
1300impl From<Args> for Vec<Metadata> {
1301 fn from(value: Args) -> Self {
1302 vec![Metadata {
1303 source_range: value.source_range,
1304 }]
1305 }
1306}