Skip to main content

kcl_lib/std/
extrude.rs

1//! Functions related to extruding.
2
3use std::collections::HashMap;
4
5use anyhow::Result;
6use indexmap::IndexMap;
7use kcmc::ModelingCmd;
8use kcmc::each_cmd as mcmd;
9use kcmc::length_unit::LengthUnit;
10use kcmc::ok_response::OkModelingCmdResponse;
11use kcmc::output::ExtrusionFaceInfo;
12use kcmc::shared::ExtrudeReference;
13use kcmc::shared::ExtrusionFaceCapType;
14use kcmc::shared::Opposite;
15use kcmc::shared::Point3d as KPoint3d; // Point3d is already defined in this pkg, to impl ts_rs traits.
16use kcmc::websocket::ModelingCmdReq;
17use kcmc::websocket::OkWebSocketResponseData;
18use kittycad_modeling_cmds::shared::Angle;
19use kittycad_modeling_cmds::shared::BodyType;
20use kittycad_modeling_cmds::shared::DirectionType;
21use kittycad_modeling_cmds::shared::EntityReference;
22use kittycad_modeling_cmds::shared::ExtrudeMethod;
23use kittycad_modeling_cmds::shared::Point2d;
24use kittycad_modeling_cmds::{self as kcmc};
25use uuid::Uuid;
26
27use super::DEFAULT_TOLERANCE_MM;
28use super::args::FromKclValue;
29use super::args::TyF64;
30use super::utils::point_to_mm;
31use crate::errors::KclError;
32use crate::errors::KclErrorDetails;
33use crate::execution::ArtifactId;
34use crate::execution::CreatorEdge;
35use crate::execution::CreatorFace;
36use crate::execution::ExecState;
37use crate::execution::ExecutorContext;
38use crate::execution::Extrudable;
39use crate::execution::ExtrudePlane;
40use crate::execution::ExtrudeSurface;
41use crate::execution::GeoMeta;
42use crate::execution::Geometry;
43use crate::execution::KclValue;
44use crate::execution::Metadata;
45use crate::execution::ModelingCmdMeta;
46use crate::execution::Path;
47use crate::execution::ProfileClosed;
48use crate::execution::Segment;
49use crate::execution::SegmentKind;
50use crate::execution::Sketch;
51use crate::execution::SketchSurface;
52use crate::execution::Solid;
53use crate::execution::SolidCreator;
54use crate::execution::TagEngineInfo;
55use crate::execution::TagIdentifier;
56use crate::execution::annotations;
57use crate::execution::types::ArrayLen;
58use crate::execution::types::PrimitiveType;
59use crate::execution::types::RuntimeType;
60use crate::parsing::ast::types::TagDeclarator;
61use crate::parsing::ast::types::TagNode;
62use crate::std::Args;
63use crate::std::axis_or_reference::Point3dAxis3dOrGeometryReference;
64use crate::std::axis_or_reference::Point3dOrEdgeReference;
65use crate::std::edge::{self};
66use crate::std::solver::create_segments_in_engine;
67
68fn must_be_lengths_err(source_range: crate::SourceRange) -> KclError {
69    KclError::new_type(KclErrorDetails::new(
70        "The components of `direction` must be lengths, e.g. `[0, 0, 1]` or `[1mm, 0mm, 1in]`".to_owned(),
71        vec![source_range],
72    ))
73}
74
75/// Extrudes by a given amount.
76pub async fn extrude(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
77    let sketch_values: Vec<KclValue> = args.get_unlabeled_kw_arg(
78        "sketches",
79        &RuntimeType::Array(
80            Box::new(RuntimeType::Primitive(PrimitiveType::Any)),
81            ArrayLen::Minimum(1),
82        ),
83        exec_state,
84    )?;
85
86    let length: Option<TyF64> = args.get_kw_arg_opt("length", &RuntimeType::length(), exec_state)?;
87    let to_raw = args.get_kw_arg_opt(
88        "to",
89        &RuntimeType::Union(vec![
90            RuntimeType::point3d(),
91            RuntimeType::Primitive(PrimitiveType::Axis3d),
92            RuntimeType::Primitive(PrimitiveType::Edge),
93            RuntimeType::plane(),
94            RuntimeType::Primitive(PrimitiveType::Face),
95            RuntimeType::sketch(),
96            RuntimeType::Primitive(PrimitiveType::Solid),
97            RuntimeType::tagged_edge(),
98            RuntimeType::tagged_face(),
99            RuntimeType::Primitive(PrimitiveType::Any),
100        ]),
101        exec_state,
102    )?;
103    let to = match to_raw {
104        None => None,
105        Some(v) => {
106            let inner = if let KclValue::Object { value: ref obj, .. } = v {
107                if edge::is_edge_specifier_object(&v) {
108                    Point3dAxis3dOrGeometryReference::EdgeToReference(edge::parse_edge_specifier_object(obj, &args)?)
109                } else {
110                    Point3dAxis3dOrGeometryReference::from_kcl_val(&v).ok_or_else(|| {
111                        KclError::new_type(KclErrorDetails::new(
112                            "Invalid value for `to`".to_owned(),
113                            vec![args.source_range],
114                        ))
115                    })?
116                }
117            } else {
118                Point3dAxis3dOrGeometryReference::from_kcl_val(&v).ok_or_else(|| {
119                    KclError::new_type(KclErrorDetails::new(
120                        "Invalid value for `to`".to_owned(),
121                        vec![args.source_range],
122                    ))
123                })?
124            };
125            Some(inner)
126        }
127    };
128    let symmetric = args.get_kw_arg_opt("symmetric", &RuntimeType::bool(), exec_state)?;
129    let bidirectional_length: Option<TyF64> =
130        args.get_kw_arg_opt("bidirectionalLength", &RuntimeType::length(), exec_state)?;
131    let direction_raw = args.get_kw_arg_opt("direction", &RuntimeType::any(), exec_state)?;
132    let direction = match direction_raw {
133        None => None,
134        Some(v) => {
135            let inner = if edge::is_edge_specifier_object(&v) {
136                Point3dOrEdgeReference::EdgeSpecifier(edge::parse_edge_specifier_value(&v, &args)?)
137            } else {
138                Point3dOrEdgeReference::from_kcl_val(&v).ok_or_else(|| {
139                    KclError::new_type(KclErrorDetails::new(
140                        "Invalid value for `direction`".to_owned(),
141                        vec![args.source_range],
142                    ))
143                })?
144            };
145            if let Point3dOrEdgeReference::Point(point) = &inner
146                && !point.iter().all(|component| component.is_length_compatible())
147            {
148                return Err(must_be_lengths_err(args.source_range));
149            }
150            Some(inner)
151        }
152    };
153    let tag_start = args.get_kw_arg_opt("tagStart", &RuntimeType::tag_decl(), exec_state)?;
154    let tag_end = args.get_kw_arg_opt("tagEnd", &RuntimeType::tag_decl(), exec_state)?;
155    let draft_angle: Option<TyF64> = args.get_kw_arg_opt("draftAngle", &RuntimeType::degrees(), exec_state)?;
156    let twist_angle: Option<TyF64> = args.get_kw_arg_opt("twistAngle", &RuntimeType::degrees(), exec_state)?;
157    let twist_angle_step: Option<TyF64> = args.get_kw_arg_opt("twistAngleStep", &RuntimeType::degrees(), exec_state)?;
158    let twist_center: Option<[TyF64; 2]> = args.get_kw_arg_opt("twistCenter", &RuntimeType::point2d(), exec_state)?;
159    let tolerance: Option<TyF64> = args.get_kw_arg_opt("tolerance", &RuntimeType::length(), exec_state)?;
160    let method: Option<String> = args.get_kw_arg_opt("method", &RuntimeType::string(), exec_state)?;
161    let hide_seams: Option<bool> = args.get_kw_arg_opt("hideSeams", &RuntimeType::bool(), exec_state)?;
162    let body_type: Option<BodyType> = args.get_kw_arg_opt("bodyType", &RuntimeType::string(), exec_state)?;
163    let target_argument_source_range = args
164        .unlabeled_kw_arg_unconverted()
165        .map(|arg| arg.source_range)
166        .unwrap_or(args.source_range);
167    let direct_target_edges = sketch_values
168        .iter()
169        .filter_map(|value| {
170            let KclValue::TagIdentifier(tag) = value else {
171                return None;
172            };
173            Some(tag.clone())
174        })
175        .collect::<Vec<_>>();
176    let extruding_sketch_segments = sketch_values.iter().all(|value| value.clone().into_segment().is_some());
177    let sketches = coerce_extrude_targets(
178        sketch_values,
179        body_type.unwrap_or_default(),
180        tag_start.as_ref(),
181        tag_end.as_ref(),
182        exec_state,
183        &args.ctx,
184        args.source_range,
185    )
186    .await?;
187
188    if let [tag] = direct_target_edges.as_slice() {
189        edge::record_refactor_meta_for_direct_tag(exec_state, tag, target_argument_source_range, &args).await?;
190    }
191
192    let result = inner_extrude(
193        sketches,
194        length,
195        to,
196        symmetric,
197        direction,
198        bidirectional_length,
199        tag_start,
200        tag_end,
201        draft_angle,
202        twist_angle,
203        twist_angle_step,
204        twist_center,
205        tolerance,
206        method,
207        hide_seams,
208        body_type,
209        extruding_sketch_segments,
210        exec_state,
211        args,
212    )
213    .await?;
214
215    Ok(result.into())
216}
217
218pub async fn coerce_extrude_targets(
219    sketch_values: Vec<KclValue>,
220    body_type: BodyType,
221    tag_start: Option<&TagNode>,
222    tag_end: Option<&TagNode>,
223    exec_state: &mut ExecState,
224    ctx: &ExecutorContext,
225    source_range: crate::SourceRange,
226) -> Result<Vec<Extrudable>, KclError> {
227    let mut extrudables = Vec::new();
228    let mut segments = Vec::new();
229
230    for value in sketch_values {
231        if let Some(segment) = value.clone().into_segment() {
232            segments.push(segment);
233            continue;
234        }
235
236        if edge::is_edge_specifier_object(&value) {
237            extrudables.push(Extrudable::EdgeSpecifier(edge::parse_edge_specifier_value_at(
238                &value,
239                source_range,
240            )?));
241            continue;
242        }
243
244        let Some(extrudable) = Extrudable::from_kcl_val(&value) else {
245            return Err(KclError::new_type(KclErrorDetails::new(
246                "Expected sketches, faces, tagged faces, or solved sketch segments for extrusion.".to_owned(),
247                vec![source_range],
248            )));
249        };
250        extrudables.push(extrudable);
251    }
252
253    if !segments.is_empty() && !extrudables.is_empty() {
254        return Err(KclError::new_semantic(KclErrorDetails::new(
255            "Cannot extrude sketch segments together with sketches or faces in the same call. Use separate `extrude()` calls.".to_owned(),
256            vec![source_range],
257        )));
258    }
259
260    if !segments.is_empty() {
261        if !matches!(body_type, BodyType::Surface) {
262            let kind_of_extrude = match body_type {
263                BodyType::Solid => "solid extrude",
264                BodyType::Surface => "surface extrude",
265                _ => "non-surface extrude",
266            };
267            return Err(KclError::new_semantic(KclErrorDetails::new(
268                format!(
269                    "You're trying to perform a {kind_of_extrude} on an edge, but edges can only be extruded with surface extrudes. To do a solid extrude, select a closed sketch region instead. To extrude these edges, do a surface extrude by using `bodyType = SURFACE` instead."
270                ),
271                vec![source_range],
272            )));
273        }
274
275        if tag_start.is_some() || tag_end.is_some() {
276            return Err(KclError::new_semantic(KclErrorDetails::new(
277                "`tagStart` and `tagEnd` are not supported when extruding sketch segments. Segment surface extrudes do not create start or end caps."
278                    .to_owned(),
279                vec![source_range],
280            )));
281        }
282
283        let synthetic_sketch = build_segment_surface_sketch(segments, exec_state, ctx, source_range).await?;
284        return Ok(vec![Extrudable::from(synthetic_sketch)]);
285    }
286
287    // Edges behave like sketch segments: they can only be surface-extruded, they
288    // don't create caps, and they can't be mixed with sketches or faces. Enforce
289    // the same rules so these cases fail loudly instead of silently producing a
290    // surface (or silently ignoring `tagStart`/`tagEnd`).
291    let has_edge = extrudables.iter().any(|e| {
292        matches!(
293            e,
294            Extrudable::Edge(_) | Extrudable::EdgeTag(_) | Extrudable::EdgeSpecifier(_)
295        )
296    });
297    if has_edge {
298        let has_non_edge = extrudables.iter().any(|e| {
299            !matches!(
300                e,
301                Extrudable::Edge(_) | Extrudable::EdgeTag(_) | Extrudable::EdgeSpecifier(_)
302            )
303        });
304        if has_non_edge {
305            return Err(KclError::new_semantic(KclErrorDetails::new(
306                "Cannot extrude edges together with sketches or faces in the same call. Use separate `extrude()` calls.".to_owned(),
307                vec![source_range],
308            )));
309        }
310
311        if !matches!(body_type, BodyType::Surface) {
312            let kind_of_extrude = match body_type {
313                BodyType::Solid => "solid extrude",
314                BodyType::Surface => "surface extrude",
315                _ => "non-surface extrude",
316            };
317            return Err(KclError::new_semantic(KclErrorDetails::new(
318                format!(
319                    "You're trying to perform a {kind_of_extrude} on an edge, but edges can only be extruded with surface extrudes. To do a solid extrude, select a closed sketch region instead. To extrude these edges, do a surface extrude by using `bodyType = SURFACE` instead."
320                ),
321                vec![source_range],
322            )));
323        }
324
325        if tag_start.is_some() || tag_end.is_some() {
326            return Err(KclError::new_semantic(KclErrorDetails::new(
327                "`tagStart` and `tagEnd` are not supported when extruding edges. Edge surface extrudes do not create start or end caps."
328                    .to_owned(),
329                vec![source_range],
330            )));
331        }
332    }
333
334    Ok(extrudables)
335}
336
337pub(crate) async fn build_segment_surface_sketch(
338    mut segments: Vec<Segment>,
339    exec_state: &mut ExecState,
340    ctx: &ExecutorContext,
341    source_range: crate::SourceRange,
342) -> Result<Sketch, KclError> {
343    let Some(first_segment) = segments.first() else {
344        return Err(KclError::new_semantic(KclErrorDetails::new(
345            "Expected at least one sketch segment.".to_owned(),
346            vec![source_range],
347        )));
348    };
349
350    let sketch_id = first_segment.sketch_id;
351    let sketch_surface = first_segment.surface.clone();
352    for segment in &segments {
353        if segment.sketch_id != sketch_id {
354            return Err(KclError::new_semantic(KclErrorDetails::new(
355                "All sketch segments passed to this operation must come from the same sketch.".to_owned(),
356                vec![source_range],
357            )));
358        }
359
360        if segment.surface != sketch_surface {
361            return Err(KclError::new_semantic(KclErrorDetails::new(
362                "All sketch segments passed to this operation must lie on the same sketch surface.".to_owned(),
363                vec![source_range],
364            )));
365        }
366
367        if matches!(segment.kind, SegmentKind::Point { .. }) {
368            return Err(KclError::new_semantic(KclErrorDetails::new(
369                "Point segments cannot be used here. Select line, arc, or circle segments instead.".to_owned(),
370                vec![source_range],
371            )));
372        }
373
374        if segment.is_construction() {
375            return Err(KclError::new_semantic(KclErrorDetails::new(
376                "Construction segments cannot be used here. Select non-construction sketch segments instead."
377                    .to_owned(),
378                vec![source_range],
379            )));
380        }
381    }
382
383    let synthetic_sketch_id = exec_state.next_uuid();
384    let segment_tags = IndexMap::from_iter(segments.iter().filter_map(|segment| {
385        segment
386            .tag
387            .as_ref()
388            .map(|tag| (segment.object_id, TagDeclarator::new(&tag.value)))
389    }));
390
391    for segment in &mut segments {
392        segment.id = exec_state.next_uuid();
393        segment.sketch_id = synthetic_sketch_id;
394        segment.sketch = None;
395    }
396
397    create_segments_in_engine(
398        &sketch_surface,
399        synthetic_sketch_id,
400        &mut segments,
401        &segment_tags,
402        ctx,
403        exec_state,
404        source_range,
405    )
406    .await?
407    .ok_or_else(|| {
408        KclError::new_semantic(KclErrorDetails::new(
409            "Expected at least one usable sketch segment.".to_owned(),
410            vec![source_range],
411        ))
412    })
413}
414
415#[allow(clippy::too_many_arguments)]
416async fn inner_extrude(
417    extrudables: Vec<Extrudable>,
418    length: Option<TyF64>,
419    to: Option<Point3dAxis3dOrGeometryReference>,
420    symmetric: Option<bool>,
421    direction: Option<Point3dOrEdgeReference>,
422    bidirectional_length: Option<TyF64>,
423    tag_start: Option<TagNode>,
424    tag_end: Option<TagNode>,
425    draft_angle: Option<TyF64>,
426    twist_angle: Option<TyF64>,
427    twist_angle_step: Option<TyF64>,
428    twist_center: Option<[TyF64; 2]>,
429    tolerance: Option<TyF64>,
430    method: Option<String>,
431    hide_seams: Option<bool>,
432    body_type: Option<BodyType>,
433    extruding_sketch_segments: bool,
434    exec_state: &mut ExecState,
435    args: Args,
436) -> Result<Vec<Solid>, KclError> {
437    let body_type = body_type.unwrap_or_default();
438
439    if matches!(body_type, BodyType::Solid) && extrudables.iter().any(|sk| matches!(sk.is_closed(), ProfileClosed::No))
440    {
441        return Err(KclError::new_semantic(KclErrorDetails::new(
442            "Cannot solid extrude an open profile. Either close the profile, or use a surface extrude.".to_owned(),
443            vec![args.source_range],
444        )));
445    }
446
447    if draft_angle.is_some() && twist_angle.is_some() {
448        return Err(KclError::new_semantic(KclErrorDetails::new(
449            "Zoo currently does not support adding both draft angle and twist angle to an extrude simultaneously"
450                .to_owned(),
451            vec![args.source_range],
452        )));
453    }
454
455    if direction.is_some() && twist_angle.is_some() {
456        return Err(KclError::new_semantic(KclErrorDetails::new(
457            "Zoo currently does not support adding both direction and twist angle to an extrude simultaneously"
458                .to_owned(),
459            vec![args.source_range],
460        )));
461    }
462
463    // Extrude the element(s).
464    let mut solids = Vec::new();
465    let tolerance = LengthUnit(
466        tolerance
467            .as_ref()
468            .map(|t| t.unwrap_to_mm())
469            .unwrap_or(DEFAULT_TOLERANCE_MM),
470    );
471
472    let extrude_method = match method.as_deref() {
473        Some("new" | "NEW") => ExtrudeMethod::New,
474        Some("merge" | "MERGE") => ExtrudeMethod::Merge,
475        None => ExtrudeMethod::default(),
476        Some(other) => {
477            return Err(KclError::new_semantic(KclErrorDetails::new(
478                format!("Unknown merge method {other}, try using `MERGE` or `NEW`"),
479                vec![args.source_range],
480            )));
481        }
482    };
483
484    if matches!(method.as_deref(), Some("merge" | "MERGE")) {
485        let parentless_sketches = extrudables
486            .iter()
487            .filter(|extrudable| {
488                matches!(extrudable, Extrudable::Sketch(sketch) if matches!(sketch.on, SketchSurface::Plane(_)))
489            })
490            .count();
491        if parentless_sketches > 0 {
492            let message = if parentless_sketches == 1 {
493                "This plane-based sketch has no parent body for `method = MERGE`, so it will create a separate body. Sketch on an existing face or use `union` if one body is intended."
494                    .to_owned()
495            } else {
496                format!(
497                    "{parentless_sketches} plane-based sketches have no parent body for `method = MERGE`, so each will create a separate body. Sketch on an existing face or use `union` if one body is intended."
498                )
499            };
500            exec_state.warn(
501                crate::CompilationIssue {
502                    source_range: args
503                        .labeled
504                        .get("method")
505                        .map_or(args.source_range, |arg| arg.source_range),
506                    message,
507                    suggestion: None,
508                    severity: crate::errors::Severity::Warning,
509                    tag: crate::errors::Tag::Unnecessary,
510                },
511                annotations::WARN_PARENTLESS_MERGE,
512            );
513        }
514    }
515
516    if symmetric.unwrap_or(false) && bidirectional_length.is_some() {
517        return Err(KclError::new_semantic(KclErrorDetails::new(
518            "You cannot give both `symmetric` and `bidirectional` params, you have to choose one or the other"
519                .to_owned(),
520            vec![args.source_range],
521        )));
522    }
523
524    if (length.is_some() || twist_angle.is_some()) && to.is_some() {
525        return Err(KclError::new_semantic(KclErrorDetails::new(
526            "You cannot give `length` or `twist` params with the `to` param, you have to choose one or the other"
527                .to_owned(),
528            vec![args.source_range],
529        )));
530    }
531
532    let bidirection = bidirectional_length.map(|l| LengthUnit(l.unwrap_to_mm()));
533
534    let opposite = match (symmetric, bidirection) {
535        (Some(true), _) => Opposite::Symmetric,
536        (None, None) => Opposite::None,
537        (Some(false), None) => Opposite::None,
538        (None, Some(length)) => Opposite::Other(length),
539        (Some(false), Some(length)) => Opposite::Other(length),
540    };
541
542    if let Some(Point3dOrEdgeReference::Edge(direction_edge)) = &direction {
543        let edge_id = direction_edge.get_engine_id(exec_state, &args)?;
544        let source_range = args
545            .labeled
546            .get("direction")
547            .map(|arg| arg.source_range)
548            .unwrap_or(args.source_range);
549        edge::record_refactor_meta_for_direct_edge(exec_state, edge_id, source_range, &args).await?;
550    }
551
552    for extrudable in &extrudables {
553        let is_edge = match extrudable {
554            Extrudable::Sketch(..) => false,
555            Extrudable::FaceTag(_) => false,
556            Extrudable::Face(_) => false,
557            Extrudable::EdgeTag(_) => true,
558            Extrudable::Edge(_) => true,
559            Extrudable::EdgeSpecifier(_) => true,
560        };
561        let extrude_cmd_id = exec_state.next_uuid();
562        let (sketch_or_face_id, target_reference) = match extrudable {
563            Extrudable::EdgeSpecifier(spec) => (
564                None,
565                Some(edge::resolve_edge_specifier_with_face_tags(spec, None, exec_state, &args).await?),
566            ),
567            _ => (Some(extrudable.id_to_extrude(exec_state, &args, false).await?), None),
568        };
569        if to.is_some() && sketch_or_face_id.is_none() {
570            return Err(KclError::new_semantic(KclErrorDetails::new(
571                "Edge specifiers cannot be extruded to a reference".to_owned(),
572                vec![args.source_range],
573            )));
574        }
575        let concrete_target = || {
576            sketch_or_face_id.ok_or_else(|| {
577                KclError::new_semantic(KclErrorDetails::new(
578                    "This extrusion requires a concrete target UUID".to_owned(),
579                    vec![args.source_range],
580                ))
581            })
582        };
583        let cmd = match (
584            &twist_angle,
585            &twist_angle_step,
586            &twist_center,
587            length.clone(),
588            &to,
589            &direction,
590        ) {
591            (Some(angle), angle_step, center, Some(length), None, None) => {
592                let center = center.clone().map(point_to_mm).map(Point2d::from).unwrap_or_default();
593                let total_rotation_angle = Angle::from_degrees(angle.unwrap_to_degrees(exec_state, args.source_range));
594                let angle_step_size = Angle::from_degrees(
595                    angle_step
596                        .clone()
597                        .map(|a| a.unwrap_to_degrees(exec_state, args.source_range))
598                        .unwrap_or(15.0),
599                );
600                ModelingCmd::from(
601                    mcmd::TwistExtrude::builder()
602                        .target(
603                            sketch_or_face_id
604                                .ok_or_else(|| {
605                                    KclError::new_semantic(KclErrorDetails::new(
606                                        "Edge specifiers cannot be used with twist extrusion".to_owned(),
607                                        vec![args.source_range],
608                                    ))
609                                })?
610                                .into(),
611                        )
612                        .distance(LengthUnit(length.unwrap_to_mm()))
613                        .center_2d(center)
614                        .total_rotation_angle(total_rotation_angle)
615                        .angle_step_size(angle_step_size)
616                        .tolerance(tolerance)
617                        .body_type(body_type)
618                        .build(),
619                )
620            }
621            (None, None, None, Some(length), None, None) => ModelingCmd::from(
622                mcmd::Extrude::builder()
623                    .maybe_target(sketch_or_face_id.map(Into::into))
624                    .maybe_target_reference(target_reference.clone())
625                    .distance(LengthUnit(length.unwrap_to_mm()))
626                    .opposite(opposite.clone())
627                    .maybe_draft_angle(
628                        draft_angle
629                            .clone()
630                            .map(|a| Angle::from_degrees(a.unwrap_to_degrees(exec_state, args.source_range))),
631                    )
632                    .extrude_method(extrude_method)
633                    .body_type(body_type)
634                    .maybe_merge_coplanar_faces(hide_seams)
635                    .build(),
636            ),
637            (None, None, None, Some(length), None, Some(dir)) => {
638                let direction3d = match dir {
639                    Point3dOrEdgeReference::Point(p) => {
640                        // Only the direction matters, so use the file's unit: a direction that
641                        // doesn't mix units is sent with the same numbers as it was written.
642                        let units = exec_state.length_unit();
643                        Some(DirectionType::Axis {
644                            direction: KPoint3d {
645                                x: p[0]
646                                    .to_length_units(units)
647                                    .ok_or(must_be_lengths_err(args.source_range))?,
648                                y: p[1]
649                                    .to_length_units(units)
650                                    .ok_or(must_be_lengths_err(args.source_range))?,
651                                z: p[2]
652                                    .to_length_units(units)
653                                    .ok_or(must_be_lengths_err(args.source_range))?,
654                            },
655                        })
656                    }
657                    Point3dOrEdgeReference::Edge(edge) => {
658                        let edge_id = match edge {
659                            crate::std::fillet::EdgeReference::Uuid(uuid) => *uuid,
660                            crate::std::fillet::EdgeReference::Tag(tag) => match tag.get_cur_info() {
661                                Some(info) => info.id,
662                                None => {
663                                    return Err(KclError::new_semantic(KclErrorDetails::new(
664                                        "Failed to get current info for tag".to_string(),
665                                        vec![args.source_range],
666                                    )));
667                                }
668                            },
669                        };
670                        Some(DirectionType::Edge { id: edge_id })
671                    }
672                    Point3dOrEdgeReference::EdgeSpecifier(_) => None,
673                };
674                let direction_reference = match dir {
675                    Point3dOrEdgeReference::EdgeSpecifier(spec) => {
676                        Some(edge::resolve_edge_specifier_with_face_tags(spec, None, exec_state, &args).await?)
677                    }
678                    _ => None,
679                };
680                ModelingCmd::from(
681                    mcmd::Extrude::builder()
682                        .maybe_target(sketch_or_face_id.map(Into::into))
683                        .maybe_target_reference(target_reference.clone())
684                        .distance(LengthUnit(length.unwrap_to_mm()))
685                        .opposite(opposite.clone())
686                        .maybe_draft_angle(
687                            draft_angle
688                                .clone()
689                                .map(|a| Angle::from_degrees(a.unwrap_to_degrees(exec_state, args.source_range))),
690                        )
691                        .extrude_method(extrude_method)
692                        .body_type(body_type)
693                        .maybe_merge_coplanar_faces(hide_seams)
694                        .maybe_direction(direction3d)
695                        .maybe_direction_reference(direction_reference)
696                        .build(),
697                )
698            }
699            (None, None, None, None, Some(to), None) => match to {
700                Point3dAxis3dOrGeometryReference::Point(point) => ModelingCmd::from(
701                    mcmd::ExtrudeToReference::builder()
702                        .target(concrete_target()?.into())
703                        .reference(ExtrudeReference::Point {
704                            point: KPoint3d {
705                                x: LengthUnit(point[0].unwrap_to_mm()),
706                                y: LengthUnit(point[1].unwrap_to_mm()),
707                                z: LengthUnit(point[2].unwrap_to_mm()),
708                            },
709                        })
710                        .extrude_method(extrude_method)
711                        .body_type(body_type)
712                        .build(),
713                ),
714                Point3dAxis3dOrGeometryReference::Axis { direction, origin } => ModelingCmd::from(
715                    mcmd::ExtrudeToReference::builder()
716                        .target(concrete_target()?.into())
717                        .reference(ExtrudeReference::Axis {
718                            axis: KPoint3d {
719                                x: direction[0].unwrap_to_mm(),
720                                y: direction[1].unwrap_to_mm(),
721                                z: direction[2].unwrap_to_mm(),
722                            },
723                            point: KPoint3d {
724                                x: LengthUnit(origin[0].unwrap_to_mm()),
725                                y: LengthUnit(origin[1].unwrap_to_mm()),
726                                z: LengthUnit(origin[2].unwrap_to_mm()),
727                            },
728                        })
729                        .extrude_method(extrude_method)
730                        .body_type(body_type)
731                        .build(),
732                ),
733                Point3dAxis3dOrGeometryReference::Plane(plane) => {
734                    let plane_id = if plane.is_uninitialized() {
735                        if plane.info.origin.units.is_none() {
736                            return Err(KclError::new_semantic(KclErrorDetails::new(
737                                "Origin of plane has unknown units".to_string(),
738                                vec![args.source_range],
739                            )));
740                        }
741                        let sketch_plane = crate::std::sketch::make_sketch_plane_from_orientation(
742                            plane.clone().info.into_plane_data(),
743                            exec_state,
744                            &args,
745                        )
746                        .await?;
747                        sketch_plane.id
748                    } else {
749                        plane.id
750                    };
751                    ModelingCmd::from(
752                        mcmd::ExtrudeToReference::builder()
753                            .target(concrete_target()?.into())
754                            .reference(ExtrudeReference::EntityReference {
755                                entity_id: Some(plane_id),
756                                entity_reference: None,
757                            })
758                            .extrude_method(extrude_method)
759                            .body_type(body_type)
760                            .build(),
761                    )
762                }
763                Point3dAxis3dOrGeometryReference::Edge(edge_ref) => {
764                    let edge_id = edge_ref.get_engine_id(exec_state, &args)?;
765                    ModelingCmd::from(
766                        mcmd::ExtrudeToReference::builder()
767                            .target(concrete_target()?.into())
768                            .reference(ExtrudeReference::EntityReference {
769                                entity_id: Some(edge_id),
770                                entity_reference: None,
771                            })
772                            .extrude_method(extrude_method)
773                            .body_type(body_type)
774                            .build(),
775                    )
776                }
777                Point3dAxis3dOrGeometryReference::Face(face_tag) => {
778                    let face_id = face_tag.get_face_id_from_tag(exec_state, &args, false).await?;
779                    ModelingCmd::from(
780                        mcmd::ExtrudeToReference::builder()
781                            .target(concrete_target()?.into())
782                            .reference(ExtrudeReference::EntityReference {
783                                entity_id: Some(face_id),
784                                entity_reference: None,
785                            })
786                            .extrude_method(extrude_method)
787                            .body_type(body_type)
788                            .build(),
789                    )
790                }
791                Point3dAxis3dOrGeometryReference::Sketch(sketch_ref) => ModelingCmd::from(
792                    mcmd::ExtrudeToReference::builder()
793                        .target(concrete_target()?.into())
794                        .reference(ExtrudeReference::EntityReference {
795                            entity_id: Some(sketch_ref.id),
796                            entity_reference: None,
797                        })
798                        .extrude_method(extrude_method)
799                        .body_type(body_type)
800                        .build(),
801                ),
802                Point3dAxis3dOrGeometryReference::Solid(solid) => ModelingCmd::from(
803                    mcmd::ExtrudeToReference::builder()
804                        .target(concrete_target()?.into())
805                        .reference(ExtrudeReference::EntityReference {
806                            entity_id: Some(solid.id),
807                            entity_reference: None,
808                        })
809                        .extrude_method(extrude_method)
810                        .body_type(body_type)
811                        .build(),
812                ),
813                Point3dAxis3dOrGeometryReference::TaggedEdgeOrFace(tag) => {
814                    let tagged_edge_or_face = args.get_tag_engine_info(exec_state, tag)?;
815                    let tagged_edge_or_face_id = tagged_edge_or_face.id;
816                    ModelingCmd::from(
817                        mcmd::ExtrudeToReference::builder()
818                            .target(concrete_target()?.into())
819                            .reference(ExtrudeReference::EntityReference {
820                                entity_id: Some(tagged_edge_or_face_id),
821                                entity_reference: None,
822                            })
823                            .extrude_method(extrude_method)
824                            .body_type(body_type)
825                            .build(),
826                    )
827                }
828                Point3dAxis3dOrGeometryReference::EdgeToReference(spec) => {
829                    let inner = edge::resolve_edge_specifier_with_face_tags(spec, None, exec_state, &args).await?;
830                    ModelingCmd::from(
831                        mcmd::ExtrudeToReference::builder()
832                            .target(concrete_target()?.into())
833                            .reference(ExtrudeReference::EntityReference {
834                                entity_id: None,
835                                entity_reference: Some(EntityReference::Edge {
836                                    inner,
837                                    topology_fallback: None,
838                                }),
839                            })
840                            .extrude_method(extrude_method)
841                            .body_type(body_type)
842                            .build(),
843                    )
844                }
845            },
846            (Some(_), _, _, None, None, None) => {
847                return Err(KclError::new_semantic(KclErrorDetails::new(
848                    "The `length` parameter must be provided when using twist angle for extrusion.".to_owned(),
849                    vec![args.source_range],
850                )));
851            }
852            (_, _, _, None, None, None) => {
853                return Err(KclError::new_semantic(KclErrorDetails::new(
854                    "Either `length` or `to` parameter must be provided for extrusion.".to_owned(),
855                    vec![args.source_range],
856                )));
857            }
858            (_, _, _, Some(_), Some(_), None) => {
859                return Err(KclError::new_semantic(KclErrorDetails::new(
860                    "You cannot give both `length` and `to` params, you have to choose one or the other".to_owned(),
861                    vec![args.source_range],
862                )));
863            }
864            (_, _, _, _, _, _) => {
865                return Err(KclError::new_semantic(KclErrorDetails::new(
866                    "Invalid combination of parameters for extrusion.".to_owned(),
867                    vec![args.source_range],
868                )));
869            }
870        };
871
872        let being_extruded = match extrudable {
873            Extrudable::Sketch(..) if extruding_sketch_segments => BeingExtruded::SketchSegments,
874            Extrudable::Sketch(..) => BeingExtruded::Sketch,
875            Extrudable::FaceTag(face_tag) => {
876                let face_id = concrete_target()?;
877                let solid_id = match face_tag.geometry() {
878                    Some(crate::execution::Geometry::Solid(solid)) => solid.id,
879                    Some(crate::execution::Geometry::Sketch(sketch)) => match sketch.on {
880                        SketchSurface::Face(face) => face.parent_solid.solid_id,
881                        SketchSurface::Plane(_) => sketch.id,
882                    },
883                    None => face_id,
884                };
885                BeingExtruded::Face { face_id, solid_id }
886            }
887            Extrudable::Face(face) => BeingExtruded::Face {
888                face_id: face.id,
889                solid_id: face.parent_solid.solid_id,
890            },
891            Extrudable::EdgeTag(_) => BeingExtruded::Edge,
892            Extrudable::Edge(_) => BeingExtruded::Edge,
893            Extrudable::EdgeSpecifier(_) => BeingExtruded::Edge,
894        };
895        if let Some(post_extr_sketch) = extrudable.as_sketch() {
896            let cmds = post_extr_sketch.build_sketch_mode_cmds(
897                exec_state,
898                ModelingCmdReq {
899                    cmd_id: extrude_cmd_id.into(),
900                    cmd,
901                },
902            );
903            exec_state
904                .batch_modeling_cmds(ModelingCmdMeta::from_args_id(exec_state, &args, extrude_cmd_id), &cmds)
905                .await?;
906            solids.push(
907                do_post_extrude(
908                    &post_extr_sketch,
909                    extrude_cmd_id.into(),
910                    false,
911                    &NamedCapTags {
912                        start: tag_start.as_ref(),
913                        end: tag_end.as_ref(),
914                    },
915                    extrude_method,
916                    exec_state,
917                    &args,
918                    None,
919                    None,
920                    body_type,
921                    being_extruded,
922                )
923                .await?,
924            );
925        } else if is_edge {
926            // Ensure that edges do not use the MERGE method.
927            match extrude_method {
928                ExtrudeMethod::New => {
929                    // This is expected.
930                }
931                ExtrudeMethod::Merge => {
932                    return Err(KclError::new_semantic(KclErrorDetails::new(
933                        "Cannot use method MERGE with surface extrude of an edge".to_owned(),
934                        vec![args.source_range],
935                    )));
936                }
937                _ => {
938                    return Err(KclError::new_internal(KclErrorDetails::new(
939                        format!("Unknown extrude method: {extrude_method:?}"),
940                        vec![args.source_range],
941                    )));
942                }
943            }
944
945            // Surface-extrude an edge.
946            exec_state
947                .batch_modeling_cmd(ModelingCmdMeta::from_args_id(exec_state, &args, extrude_cmd_id), cmd)
948                .await?;
949            // Extract the edge tag.
950            let edge_tag = match extrudable {
951                Extrudable::Sketch(_) => None,
952                Extrudable::FaceTag(_) => None,
953                Extrudable::Face(_) => None,
954                Extrudable::EdgeTag(tag) => Some(TagDeclarator::new(&tag.value)),
955                Extrudable::Edge(_) => None,
956                Extrudable::EdgeSpecifier(_) => None,
957            };
958            solids.push(after_surface_creation(extrude_cmd_id.into(), edge_tag, exec_state, &args).await?);
959        } else {
960            return Err(KclError::new_type(KclErrorDetails::new(
961                "Expected a sketch for extrusion".to_owned(),
962                vec![args.source_range],
963            )));
964        }
965    }
966
967    Ok(solids)
968}
969
970#[derive(Debug, Default)]
971pub(crate) struct NamedCapTags<'a> {
972    pub start: Option<&'a TagNode>,
973    pub end: Option<&'a TagNode>,
974}
975
976#[derive(Debug, Clone, Copy)]
977pub enum BeingExtruded {
978    Sketch,
979    SketchSegments,
980    Face { face_id: Uuid, solid_id: Uuid },
981    Edge,
982}
983
984/// Which edge should we use for querying Solid3dGetExtrusionInfo and GetAdjacencyInfo?
985/// It can be any edge of the body, but if our body is a clone, we should use an edge of
986/// the original body, not the new cloned body.
987fn get_extrusion_info_edge_id(
988    sketch: &Sketch,
989    any_edge_id: Uuid,
990    clone_id_map: Option<&HashMap<Uuid, Uuid>>,
991) -> Option<Uuid> {
992    // If this isn't a clone, there's no old/new body distinction.
993    // So just use the edge.
994    if sketch.clone.is_none() {
995        return Some(any_edge_id);
996    }
997    let Some(clone_map) = clone_id_map else {
998        return Some(any_edge_id);
999    };
1000
1001    // clone_map maps old IDs -> new IDs.
1002    // If the `any_edge_id` is an ID of the OLD body
1003    // (we know this if it's a _key_ of the map)
1004    // we should use it (because that's the old body we're querying).
1005    if clone_map.contains_key(&any_edge_id) {
1006        return Some(any_edge_id);
1007    }
1008
1009    // Otherwise, if the `any_edge_id` is an ID of the NEW body
1010    // (we know this if it's a _value_ of the map),
1011    // we should query the corresponding ID in the OLD body.
1012    // i.e. if it's a hashmap value, find the corresponding key.
1013    if let Some((old_edge_id, _)) = clone_map.iter().find(|(_, new_edge_id)| **new_edge_id == any_edge_id) {
1014        return Some(*old_edge_id);
1015    }
1016
1017    // Fall back to this if the clone_map doesn't have the data we expect.
1018    // Engine will intuit an edge for the relevant calls, but it may mean the clone map was built wrong,
1019    // or KCL and the engine disagree about what geometry exists.
1020    None
1021}
1022
1023/// This is similar to [`do_post_extrude()`], but for surfaces where a sketch
1024/// isn't available.
1025pub(crate) async fn after_surface_creation(
1026    extrude_cmd_id: ArtifactId,
1027    edge_tag: Option<crate::parsing::ast::types::Node<TagDeclarator>>,
1028    exec_state: &mut ExecState,
1029    args: &Args,
1030) -> Result<Solid, KclError> {
1031    let body_id = extrude_cmd_id.into();
1032
1033    // Bring the object to the front of the scene.
1034    // See: https://github.com/KittyCAD/modeling-app/issues/806
1035
1036    exec_state
1037        .batch_modeling_cmd(
1038            ModelingCmdMeta::from_args(exec_state, args),
1039            ModelingCmd::from(mcmd::ObjectBringToFront::builder().object_id(body_id).build()),
1040        )
1041        .await?;
1042
1043    let (face_id, edge_id) = if args.ctx.no_engine_commands().await {
1044        (exec_state.next_uuid(), exec_state.next_uuid())
1045    } else {
1046        // Get the body entity ids.
1047        let response = exec_state
1048            .send_modeling_cmd(
1049                ModelingCmdMeta::from_args(exec_state, args),
1050                ModelingCmd::from(mcmd::EntityGetAllChildUuids::builder().entity_id(body_id).build()),
1051            )
1052            .await?;
1053        let OkWebSocketResponseData::Modeling {
1054            modeling_response: OkModelingCmdResponse::EntityGetAllChildUuids(ref all_child_ids_resp),
1055        } = response
1056        else {
1057            return Err(KclError::new_engine(KclErrorDetails::new(
1058                format!("EntityGetAllChildUuids response was not as expected: {response:?}"),
1059                vec![args.source_range],
1060            )));
1061        };
1062        let entity_ids = &all_child_ids_resp.entity_ids;
1063        let Some(face_id) = entity_ids.first().copied() else {
1064            return Err(KclError::new_internal(KclErrorDetails::new(
1065                format!("Expected EntityGetAllChildUuids response to have at least 1 ID: {response:?}",),
1066                vec![args.source_range],
1067            )));
1068        };
1069        let Some(edge_id) = entity_ids.get(1).copied() else {
1070            return Err(KclError::new_internal(KclErrorDetails::new(
1071                format!("Expected EntityGetAllChildUuids response to have at least 2 IDs: {response:?}"),
1072                vec![args.source_range],
1073            )));
1074        };
1075        (face_id, edge_id)
1076    };
1077
1078    // TODO: Do we need to use ExtrudeArc?
1079    let extrude_surface = ExtrudeSurface::ExtrudePlane(ExtrudePlane {
1080        face_id,
1081        tag: edge_tag,
1082        geo_meta: GeoMeta {
1083            id: face_id,
1084            metadata: args.source_range.into(),
1085        },
1086    });
1087    let new_value = vec![extrude_surface];
1088
1089    Ok(Solid {
1090        id: body_id,
1091        value_id: body_id,
1092        topology_id: body_id,
1093        pattern_source_artifact_id: None,
1094        best_guess_body_type: Some(BodyType::Surface),
1095        artifact_id: extrude_cmd_id,
1096        value: new_value,
1097        faces: Default::default(),
1098        meta: vec![args.source_range.into()],
1099        // Normally, we would propagate the units of the sketch. But an edge
1100        // doesn't have units. We also don't seem to use this field anywhere.
1101        units: kcl_api::UnitLength::Millimeters,
1102        sectional: false,
1103        creator: SolidCreator::Edge(CreatorEdge { edge_id, body_id }),
1104        start_cap_id: None,
1105        end_cap_id: None,
1106        edge_cuts: Vec::new(),
1107        pending_edge_cut_ids: Vec::new(),
1108    })
1109}
1110
1111#[allow(clippy::too_many_arguments)]
1112pub(crate) async fn do_post_extrude<'a>(
1113    sketch: &Sketch,
1114    extrude_cmd_id: ArtifactId,
1115    sectional: bool,
1116    named_cap_tags: &'a NamedCapTags<'a>,
1117    extrude_method: ExtrudeMethod,
1118    exec_state: &mut ExecState,
1119    args: &Args,
1120    edge_id: Option<Uuid>,
1121    clone_id_map: Option<&HashMap<Uuid, Uuid>>, // old sketch id -> new sketch id
1122    body_type: BodyType,
1123    being_extruded: BeingExtruded,
1124) -> Result<Solid, KclError> {
1125    // Bring the object to the front of the scene.
1126    // See: https://github.com/KittyCAD/modeling-app/issues/806
1127
1128    exec_state
1129        .batch_modeling_cmd(
1130            ModelingCmdMeta::from_args(exec_state, args),
1131            ModelingCmd::from(mcmd::ObjectBringToFront::builder().object_id(sketch.id).build()),
1132        )
1133        .await?;
1134
1135    let any_edge_id = if let Some(edge_id) = sketch.mirror {
1136        edge_id
1137    } else if let Some(id) = edge_id {
1138        id
1139    } else {
1140        // The "get extrusion face info" API call requires *any* edge on the sketch being extruded.
1141        // So, let's just use the first one.
1142        let Some(any_edge_id) = sketch.paths.front().map(|edge| edge.get_base().geo_meta.id) else {
1143            return Err(KclError::new_type(KclErrorDetails::new(
1144                "Expected a non-empty sketch".to_owned(),
1145                vec![args.source_range],
1146            )));
1147        };
1148        any_edge_id
1149    };
1150
1151    // If the sketch is a clone, we will use the original info to get the extrusion face info.
1152    // So let's find an edge of the old body.
1153    let extrusion_info_edge_id = get_extrusion_info_edge_id(sketch, any_edge_id, clone_id_map);
1154
1155    let mut sketch = sketch.clone();
1156    match body_type {
1157        BodyType::Solid => {
1158            sketch.is_closed = ProfileClosed::Explicitly;
1159        }
1160        BodyType::Surface => {}
1161        _other => {
1162            // At some point in the future we'll add sheet metal or something.
1163            // Figure this out then.
1164        }
1165    }
1166
1167    match (extrude_method, being_extruded) {
1168        (ExtrudeMethod::Merge, BeingExtruded::Face { .. }) => {
1169            // Merge the IDs.
1170            // If we were sketching on a face, we need the original face id.
1171            if let SketchSurface::Face(ref face) = sketch.on {
1172                // If we're merging into an existing body, then assign the existing body's ID,
1173                // because the variable binding for this solid won't be its own object, it's just modifying the original one.
1174                sketch.id = face.parent_solid.sketch_or_solid_id();
1175            }
1176        }
1177        (ExtrudeMethod::New, BeingExtruded::Face { .. }) => {
1178            // We're creating a new solid, it's not based on any existing sketch (it's based on a face).
1179            // So we need a new ID, the extrude command ID.
1180            sketch.id = extrude_cmd_id.into();
1181        }
1182        (ExtrudeMethod::New, BeingExtruded::Sketch | BeingExtruded::SketchSegments) => {
1183            // If we are creating a new body we need to preserve its new id.
1184            // The sketch's ID is already correct here, it should be the ID of the sketch.
1185        }
1186        (ExtrudeMethod::Merge, BeingExtruded::Sketch | BeingExtruded::SketchSegments) => {
1187            if let SketchSurface::Face(ref face) = sketch.on {
1188                // If we're merging into an existing body, then assign the existing body's ID,
1189                // because the variable binding for this solid won't be its own object, it's just modifying the original one.
1190                sketch.id = face.parent_solid.sketch_or_solid_id();
1191            }
1192        }
1193        (other, _) => {
1194            // If you ever hit this, you should add a new arm to the match expression, and implement support for the new ExtrudeMethod variant.
1195            return Err(KclError::new_internal(KclErrorDetails::new(
1196                format!("Zoo does not yet support creating bodies via {other:?}"),
1197                vec![args.source_range],
1198            )));
1199        }
1200    }
1201
1202    // Similarly, if the sketch is a clone, we need to use the original sketch id to get the extrusion face info.
1203    let sketch_id = if let Some(cloned_from) = sketch.clone
1204        && clone_id_map.is_some()
1205    {
1206        cloned_from
1207    } else {
1208        sketch.id
1209    };
1210
1211    let solid3d_info = exec_state
1212        .send_modeling_cmd(
1213            ModelingCmdMeta::from_args(exec_state, args),
1214            ModelingCmd::from(
1215                mcmd::Solid3dGetExtrusionFaceInfo::builder()
1216                    .maybe_edge_id(extrusion_info_edge_id)
1217                    .object_id(sketch_id)
1218                    .build(),
1219            ),
1220        )
1221        .await?;
1222
1223    let face_infos = if let OkWebSocketResponseData::Modeling {
1224        modeling_response: OkModelingCmdResponse::Solid3dGetExtrusionFaceInfo(data),
1225    } = solid3d_info
1226    {
1227        data.faces
1228    } else {
1229        vec![]
1230    };
1231
1232    // Only do this if we need the artifact graph.
1233    if !args.ctx.settings.skip_artifact_graph {
1234        // Getting the ids of a sectional sweep does not work well and we cannot guarantee that
1235        // any of these call will not just fail.
1236        if !sectional {
1237            exec_state
1238                .batch_modeling_cmd(
1239                    ModelingCmdMeta::from_args(exec_state, args),
1240                    ModelingCmd::from(
1241                        mcmd::Solid3dGetAdjacencyInfo::builder()
1242                            .object_id(sketch_id)
1243                            .maybe_edge_id(extrusion_info_edge_id)
1244                            .build(),
1245                    ),
1246                )
1247                .await?;
1248        }
1249    }
1250
1251    let Faces {
1252        sides: mut face_id_map,
1253        mut start_cap_id,
1254        mut end_cap_id,
1255    } = analyze_faces(exec_state, args, face_infos).await;
1256
1257    // If this is a clone, we will use the clone_id_map to map the face info from the original sketch to the clone sketch.
1258    if sketch.clone.is_some()
1259        && let Some(clone_id_map) = clone_id_map
1260    {
1261        face_id_map = face_id_map
1262            .into_iter()
1263            .filter_map(|(k, v)| {
1264                let fe_key = clone_id_map.get(&k)?;
1265                let fe_value = clone_id_map.get(&(v?)).copied();
1266                Some((*fe_key, fe_value))
1267            })
1268            .collect::<HashMap<Uuid, Option<Uuid>>>();
1269        // The face info above was queried using the original solid's id, so
1270        // the cap ids belong to the original. Map them to the clone's ids.
1271        start_cap_id = start_cap_id.and_then(|id| clone_id_map.get(&id).copied());
1272        end_cap_id = end_cap_id.and_then(|id| clone_id_map.get(&id).copied());
1273    }
1274
1275    // Iterate over the sketch.value array and add face_id to GeoMeta
1276    let no_engine_commands = args.ctx.no_engine_commands().await;
1277    let mut new_value: Vec<ExtrudeSurface> = Vec::with_capacity(sketch.paths.len() + sketch.inner_paths.len() + 2);
1278    let outer_surfaces = sketch.paths.iter().flat_map(|path| {
1279        if let Some(Some(actual_face_id)) = face_id_map.get(&path.get_base().geo_meta.id) {
1280            surface_of(path, *actual_face_id)
1281        } else if no_engine_commands {
1282            crate::log::logln!(
1283                "No face ID found for path ID {:?}, but in no-engine-commands mode, so faking it",
1284                path.get_base().geo_meta.id
1285            );
1286            // Only pre-populate the extrude surface if we are in mock mode.
1287            fake_extrude_surface(exec_state, path)
1288        } else if sketch.clone.is_some()
1289            && let Some(clone_map) = clone_id_map
1290        {
1291            let new_path = clone_map.get(&(path.get_base().geo_meta.id));
1292
1293            if let Some(new_path) = new_path {
1294                match face_id_map.get(new_path) {
1295                    Some(Some(actual_face_id)) => clone_surface_of(path, *new_path, *actual_face_id),
1296                    _ => {
1297                        let actual_face_id = face_id_map.iter().find_map(|(key, value)| {
1298                            if let Some(value) = value {
1299                                if value == new_path { Some(key) } else { None }
1300                            } else {
1301                                None
1302                            }
1303                        });
1304                        match actual_face_id {
1305                            Some(actual_face_id) => clone_surface_of(path, *new_path, *actual_face_id),
1306                            None => {
1307                                crate::log::logln!("No face ID found for clone path ID {:?}, so skipping it", new_path);
1308                                None
1309                            }
1310                        }
1311                    }
1312                }
1313            } else {
1314                None
1315            }
1316        } else {
1317            crate::log::logln!(
1318                "No face ID found for path ID {:?}, and not in no-engine-commands mode, so skipping it",
1319                path.get_base().geo_meta.id
1320            );
1321            None
1322        }
1323    });
1324
1325    new_value.extend(outer_surfaces);
1326    let inner_surfaces = sketch.inner_paths.iter().flat_map(|path| {
1327        if let Some(Some(actual_face_id)) = face_id_map.get(&path.get_base().geo_meta.id) {
1328            surface_of(path, *actual_face_id)
1329        } else if no_engine_commands {
1330            // Only pre-populate the extrude surface if we are in mock mode.
1331            fake_extrude_surface(exec_state, path)
1332        } else {
1333            None
1334        }
1335    });
1336    new_value.extend(inner_surfaces);
1337
1338    // Add the tags for the start or end caps. A CSG can split or remove a
1339    // canonical cap before a body is cloned or mirrored, so reconstruction
1340    // cannot preserve that tag as one cap when the engine no longer reports it.
1341    if let Some(tag_start) = named_cap_tags.start {
1342        if let Some(start_cap_id) = start_cap_id {
1343            new_value.push(ExtrudeSurface::ExtrudePlane(crate::execution::ExtrudePlane {
1344                face_id: start_cap_id,
1345                tag: Some(tag_start.clone()),
1346                geo_meta: GeoMeta {
1347                    id: start_cap_id,
1348                    metadata: args.source_range.into(),
1349                },
1350            }));
1351        } else if clone_id_map.is_none() {
1352            return Err(KclError::new_type(KclErrorDetails::new(
1353                format!(
1354                    "Expected a start cap ID for tag `{}` for extrusion of sketch {:?}",
1355                    tag_start.name, sketch.id
1356                ),
1357                vec![args.source_range],
1358            )));
1359        }
1360    }
1361    if let Some(tag_end) = named_cap_tags.end {
1362        if let Some(end_cap_id) = end_cap_id {
1363            new_value.push(ExtrudeSurface::ExtrudePlane(crate::execution::ExtrudePlane {
1364                face_id: end_cap_id,
1365                tag: Some(tag_end.clone()),
1366                geo_meta: GeoMeta {
1367                    id: end_cap_id,
1368                    metadata: args.source_range.into(),
1369                },
1370            }));
1371        } else if clone_id_map.is_none() {
1372            return Err(KclError::new_type(KclErrorDetails::new(
1373                format!(
1374                    "Expected an end cap ID for tag `{}` for extrusion of sketch {:?}",
1375                    tag_end.name, sketch.id
1376                ),
1377                vec![args.source_range],
1378            )));
1379        }
1380    }
1381
1382    let meta = sketch.meta.clone();
1383    let units = sketch.units;
1384    let id = sketch.id;
1385    let topology_id = sketch.original_id;
1386    let creator = match being_extruded {
1387        BeingExtruded::Sketch | BeingExtruded::SketchSegments => SolidCreator::Sketch(sketch),
1388        BeingExtruded::Face { face_id, solid_id } => SolidCreator::Face(CreatorFace {
1389            face_id,
1390            solid_id,
1391            sketch,
1392        }),
1393        BeingExtruded::Edge => {
1394            let message = "Expected an edge to have been extruded via another code path";
1395            debug_assert!(false, "{message}");
1396            return Err(KclError::new_internal(KclErrorDetails::new(
1397                message.to_owned(),
1398                vec![args.source_range],
1399            )));
1400        }
1401    };
1402
1403    let mut solid = Solid {
1404        id,
1405        value_id: extrude_cmd_id.into(),
1406        topology_id,
1407        pattern_source_artifact_id: None,
1408        best_guess_body_type: Some(body_type),
1409        artifact_id: extrude_cmd_id,
1410        value: new_value,
1411        faces: Default::default(),
1412        meta,
1413        units,
1414        sectional,
1415        creator,
1416        start_cap_id,
1417        end_cap_id,
1418        edge_cuts: vec![],
1419        pending_edge_cut_ids: vec![],
1420    };
1421
1422    if matches!(being_extruded, BeingExtruded::SketchSegments) {
1423        let geometry = Geometry::Solid(solid.clone());
1424        for surface in &solid.value {
1425            let Some(tag) = surface.get_tag() else {
1426                continue;
1427            };
1428            solid.faces.insert(
1429                tag.name.clone(),
1430                TagIdentifier {
1431                    value: tag.name.clone(),
1432                    info: vec![(
1433                        exec_state.stack().current_epoch(),
1434                        TagEngineInfo {
1435                            id: surface.get_id(),
1436                            surface: Some(surface.clone()),
1437                            path: None,
1438                            geometry: geometry.clone(),
1439                        },
1440                    )],
1441                    meta: vec![Metadata {
1442                        source_range: tag.clone().into(),
1443                    }],
1444                },
1445            );
1446        }
1447    }
1448
1449    Ok(solid)
1450}
1451
1452#[derive(Debug, Default)]
1453struct Faces {
1454    /// Maps curve ID to face ID for each side.
1455    sides: HashMap<Uuid, Option<Uuid>>,
1456    /// Top face ID.
1457    end_cap_id: Option<Uuid>,
1458    /// Bottom face ID.
1459    start_cap_id: Option<Uuid>,
1460}
1461
1462async fn analyze_faces(exec_state: &mut ExecState, args: &Args, face_infos: Vec<ExtrusionFaceInfo>) -> Faces {
1463    let mut faces = Faces {
1464        sides: HashMap::with_capacity(face_infos.len()),
1465        ..Default::default()
1466    };
1467    if args.ctx.no_engine_commands().await {
1468        // Create fake IDs for start and end caps, to make extrudes mock-execute safe
1469        faces.start_cap_id = Some(exec_state.next_uuid());
1470        faces.end_cap_id = Some(exec_state.next_uuid());
1471    }
1472    for face_info in face_infos {
1473        match face_info.cap {
1474            ExtrusionFaceCapType::Bottom => faces.start_cap_id = face_info.face_id,
1475            ExtrusionFaceCapType::Top => faces.end_cap_id = face_info.face_id,
1476            ExtrusionFaceCapType::Both => {
1477                faces.end_cap_id = face_info.face_id;
1478                faces.start_cap_id = face_info.face_id;
1479            }
1480            ExtrusionFaceCapType::None => {
1481                if let Some(curve_id) = face_info.curve_id {
1482                    faces.sides.insert(curve_id, face_info.face_id);
1483                }
1484            }
1485            other => {
1486                exec_state.warn(
1487                    crate::CompilationIssue {
1488                        source_range: args.source_range,
1489                        message: format!("unknown extrusion face type {other:?}"),
1490                        suggestion: None,
1491                        severity: crate::errors::Severity::Warning,
1492                        tag: crate::errors::Tag::Unnecessary,
1493                    },
1494                    annotations::WARN_NOT_YET_SUPPORTED,
1495                );
1496            }
1497        }
1498    }
1499    faces
1500}
1501fn surface_of(path: &Path, actual_face_id: Uuid) -> Option<ExtrudeSurface> {
1502    match path {
1503        Path::Arc { .. }
1504        | Path::TangentialArc { .. }
1505        | Path::TangentialArcTo { .. }
1506        // TODO: (bc) fix me
1507        | Path::Ellipse { .. }
1508        | Path::Conic {.. }
1509        | Path::Circle { .. }
1510        | Path::CircleThreePoint { .. } => {
1511            let extrude_surface = ExtrudeSurface::ExtrudeArc(crate::execution::ExtrudeArc {
1512                face_id: actual_face_id,
1513                tag: path.get_base().tag.clone(),
1514                geo_meta: GeoMeta {
1515                    id: path.get_base().geo_meta.id,
1516                    metadata: path.get_base().geo_meta.metadata,
1517                },
1518            });
1519            Some(extrude_surface)
1520        }
1521        Path::Base { .. } | Path::ToPoint { .. } | Path::Horizontal { .. } | Path::AngledLineTo { .. } | Path::Bezier { .. } => {
1522            let extrude_surface = ExtrudeSurface::ExtrudePlane(crate::execution::ExtrudePlane {
1523                face_id: actual_face_id,
1524                tag: path.get_base().tag.clone(),
1525                geo_meta: GeoMeta {
1526                    id: path.get_base().geo_meta.id,
1527                    metadata: path.get_base().geo_meta.metadata,
1528                },
1529            });
1530            Some(extrude_surface)
1531        }
1532        Path::ArcThreePoint { .. } => {
1533            let extrude_surface = ExtrudeSurface::ExtrudeArc(crate::execution::ExtrudeArc {
1534                face_id: actual_face_id,
1535                tag: path.get_base().tag.clone(),
1536                geo_meta: GeoMeta {
1537                    id: path.get_base().geo_meta.id,
1538                    metadata: path.get_base().geo_meta.metadata,
1539                },
1540            });
1541            Some(extrude_surface)
1542        }
1543    }
1544}
1545
1546fn clone_surface_of(path: &Path, clone_path_id: Uuid, actual_face_id: Uuid) -> Option<ExtrudeSurface> {
1547    match path {
1548        Path::Arc { .. }
1549        | Path::TangentialArc { .. }
1550        | Path::TangentialArcTo { .. }
1551        // TODO: (gserena) fix me
1552        | Path::Ellipse { .. }
1553        | Path::Conic {.. }
1554        | Path::Circle { .. }
1555        | Path::CircleThreePoint { .. } => {
1556            let extrude_surface = ExtrudeSurface::ExtrudeArc(crate::execution::ExtrudeArc {
1557                face_id: actual_face_id,
1558                tag: path.get_base().tag.clone(),
1559                geo_meta: GeoMeta {
1560                    id: clone_path_id,
1561                    metadata: path.get_base().geo_meta.metadata,
1562                },
1563            });
1564            Some(extrude_surface)
1565        }
1566        Path::Base { .. } | Path::ToPoint { .. } | Path::Horizontal { .. } | Path::AngledLineTo { .. } | Path::Bezier { .. } => {
1567            let extrude_surface = ExtrudeSurface::ExtrudePlane(crate::execution::ExtrudePlane {
1568                face_id: actual_face_id,
1569                tag: path.get_base().tag.clone(),
1570                geo_meta: GeoMeta {
1571                    id: clone_path_id,
1572                    metadata: path.get_base().geo_meta.metadata,
1573                },
1574            });
1575            Some(extrude_surface)
1576        }
1577        Path::ArcThreePoint { .. } => {
1578            let extrude_surface = ExtrudeSurface::ExtrudeArc(crate::execution::ExtrudeArc {
1579                face_id: actual_face_id,
1580                tag: path.get_base().tag.clone(),
1581                geo_meta: GeoMeta {
1582                    id: clone_path_id,
1583                    metadata: path.get_base().geo_meta.metadata,
1584                },
1585            });
1586            Some(extrude_surface)
1587        }
1588    }
1589}
1590
1591/// Create a fake extrude surface to report for mock execution, when there's no engine response.
1592fn fake_extrude_surface(exec_state: &mut ExecState, path: &Path) -> Option<ExtrudeSurface> {
1593    let extrude_surface = ExtrudeSurface::ExtrudePlane(crate::execution::ExtrudePlane {
1594        // pushing this values with a fake face_id to make extrudes mock-execute safe
1595        face_id: exec_state.next_uuid(),
1596        tag: path.get_base().tag.clone(),
1597        geo_meta: GeoMeta {
1598            id: path.get_base().geo_meta.id,
1599            metadata: path.get_base().geo_meta.metadata,
1600        },
1601    });
1602    Some(extrude_surface)
1603}
1604
1605#[cfg(test)]
1606mod tests {
1607    use kcl_api::UnitLength;
1608
1609    use super::*;
1610    use crate::execution::AbstractSegment;
1611    use crate::execution::Plane;
1612    use crate::execution::SegmentRepr;
1613    use crate::execution::parse_execute;
1614    use crate::execution::types::NumericType;
1615    use crate::execution::types::NumericTypeExt;
1616    use crate::front::Expr;
1617    use crate::front::Number;
1618    use crate::front::ObjectId;
1619    use crate::front::Point2d;
1620    use crate::front::PointCtor;
1621    use crate::std::sketch::PlaneData;
1622
1623    fn point_expr(x: f64, y: f64) -> Point2d<Expr> {
1624        Point2d {
1625            x: Expr::Var(Number::from((x, UnitLength::Millimeters))),
1626            y: Expr::Var(Number::from((y, UnitLength::Millimeters))),
1627        }
1628    }
1629
1630    fn segment_value(exec_state: &mut ExecState) -> KclValue {
1631        let plane = Plane::from_plane_data_skipping_engine(PlaneData::XY, exec_state).unwrap();
1632        let segment = Segment {
1633            id: exec_state.next_uuid(),
1634            object_id: ObjectId(1),
1635            kind: SegmentKind::Point {
1636                position: [TyF64::new(0.0, NumericType::mm()), TyF64::new(0.0, NumericType::mm())],
1637                ctor: Box::new(PointCtor {
1638                    position: point_expr(0.0, 0.0),
1639                }),
1640                freedom: None,
1641            },
1642            surface: SketchSurface::Plane(Box::new(plane)),
1643            sketch_id: exec_state.next_uuid(),
1644            sketch: None,
1645            tag: None,
1646            node_path: None,
1647            meta: vec![],
1648        };
1649        KclValue::Segment {
1650            value: Box::new(AbstractSegment {
1651                repr: SegmentRepr::Solved {
1652                    segment: Box::new(segment),
1653                },
1654                meta: vec![],
1655            }),
1656        }
1657    }
1658
1659    #[tokio::test(flavor = "multi_thread")]
1660    async fn extrude_accepts_negative_bidirectional_length_in_mock_exec() {
1661        let code = r#"
1662profile001 = startSketchOn(XY)
1663  |> startProfile(at = [0, 0])
1664  |> line(end = [1, 0])
1665  |> line(end = [0, 1])
1666  |> close()
1667
1668extrude(profile001, length = 1, bidirectionalLength = -1)
1669"#;
1670
1671        let result = parse_execute(code).await.unwrap();
1672        let extrude = result
1673            .root_module_artifact_commands()
1674            .iter()
1675            .find_map(|artifact_command| match &artifact_command.command {
1676                ModelingCmd::Extrude(extrude) => Some(extrude),
1677                _ => None,
1678            })
1679            .expect("expected an extrude command");
1680
1681        assert_eq!(extrude.opposite, Opposite::Other(LengthUnit(-1.0)));
1682    }
1683
1684    fn extrude_direction_code(default_unit: &str, direction: &str) -> String {
1685        format!(
1686            r#"@settings(kclVersion = 2.0, defaultLengthUnit = {default_unit})
1687profile = sketch(on = XY) {{
1688  circle1 = circle(center = [10mm, 0mm], start = [11mm, 0mm])
1689}}
1690extrude(profile.circle1, length = 1, direction = {direction}, bodyType = SURFACE)"#
1691        )
1692    }
1693
1694    #[tokio::test(flavor = "multi_thread")]
1695    async fn extrude_converts_direction_to_the_file_units() {
1696        // https://github.com/KittyCAD/modeling-app/issues/14343
1697        // Each component is converted to the file's unit before the direction is sent to the engine.
1698        let cases = [
1699            ("mm", "[-1, 0, 1ft]", [-1.0, 0.0, 304.8]),
1700            ("mm", "[-1mm, 0mm, 304.8mm]", [-1.0, 0.0, 304.8]),
1701            ("mm", "[-1, 0, 1]", [-1.0, 0.0, 1.0]),
1702            ("in", "[-1mm, 0, 1ft]", [-1.0 / 25.4, 0.0, 12.0]),
1703            ("in", "[-1, 0, 1]", [-1.0, 0.0, 1.0]),
1704        ];
1705
1706        for (default_unit, direction, expected) in cases {
1707            let code = extrude_direction_code(default_unit, direction);
1708            let result = parse_execute(&code).await.unwrap();
1709            let direction = result
1710                .root_module_artifact_commands()
1711                .iter()
1712                .find_map(|artifact_command| match &artifact_command.command {
1713                    ModelingCmd::Extrude(extrude) => extrude.direction,
1714                    _ => None,
1715                })
1716                .expect("expected an extrude command with a direction");
1717            let DirectionType::Axis { direction } = direction else {
1718                panic!("expected an axis direction, got {direction:?} for:\n{code}");
1719            };
1720            let actual = [direction.x, direction.y, direction.z];
1721            assert!(
1722                actual.iter().zip(expected).all(|(a, e)| (a - e).abs() < 1e-9),
1723                "expected {expected:?}, got {actual:?} for:\n{code}"
1724            );
1725        }
1726    }
1727
1728    #[tokio::test(flavor = "multi_thread")]
1729    async fn extrude_rejects_direction_that_is_not_lengths() {
1730        for direction in ["[0, 0, 1deg]", "[0, 0, 1mm + 1deg]", "[0, 0, 1_]"] {
1731            let code = extrude_direction_code("mm", direction);
1732            let err = parse_execute(&code).await.unwrap_err();
1733            assert!(matches!(&err, KclError::Type { .. }), "{err:?} for:\n{code}");
1734            let message = err.message();
1735            assert!(
1736                message.contains("The components of `direction` must be lengths"),
1737                "{message} for:\n{code}"
1738            );
1739        }
1740    }
1741
1742    #[tokio::test(flavor = "multi_thread")]
1743    async fn explicit_merge_warns_for_plane_based_sketches() {
1744        let code = r#"
1745@settings(kclVersion = 2.0)
1746
1747profiles = sketch(on = XY) {
1748  circle1 = circle(start = [var 1mm, var 0mm], center = [var 0mm, var 0mm])
1749  circle2 = circle(start = [var 4mm, var 0mm], center = [var 3mm, var 0mm])
1750  circle3 = circle(start = [var 7mm, var 0mm], center = [var 6mm, var 0mm])
1751}
1752
1753leftRegion = region(segments = [profiles.circle1])
1754rightRegion = region(segments = [profiles.circle2])
1755extrude([leftRegion, rightRegion], length = 1mm, method = MERGE)
1756
1757defaultRegion = region(segments = [profiles.circle3])
1758extrude(defaultRegion, length = 1mm)
1759"#;
1760
1761        let result = parse_execute(code).await.unwrap();
1762        let warnings: Vec<_> = result
1763            .issues()
1764            .iter()
1765            .filter(|issue| issue.severity == crate::errors::Severity::Warning)
1766            .collect();
1767
1768        assert_eq!(warnings.len(), 1, "expected one warning, got {warnings:#?}");
1769        assert!(
1770            warnings[0].message.contains(
1771                "2 plane-based sketches have no parent body for `method = MERGE`, so each will create a separate body"
1772            ),
1773            "{}",
1774            warnings[0].message
1775        );
1776    }
1777
1778    #[tokio::test(flavor = "multi_thread")]
1779    async fn extrude_rejects_an_empty_target_array() {
1780        let err = parse_execute("nothing = extrude([], length = 5)").await.unwrap_err();
1781
1782        assert!(matches!(err, KclError::Argument { .. }), "{err:?}");
1783        assert!(err.message().contains("requires one or more"), "{err:?}");
1784    }
1785
1786    #[tokio::test(flavor = "multi_thread")]
1787    async fn edge_extrude_succeeds_in_mock_exec() {
1788        let code = r#"
1789@settings(kclVersion = 2.0)
1790
1791sketch001 = sketch(on = XZ) {
1792  line1 = line(start = [0mm, 0mm], end = [1mm, 0mm])
1793}
1794extrude001 = extrude(sketch001.line1, length = 5, bodyType = SURFACE)
1795extrude(
1796  getOppositeEdge(extrude001.sketch.tags.line1),
1797  length = 1,
1798  method = NEW,
1799  bodyType = SURFACE,
1800)
1801"#;
1802
1803        parse_execute(code).await.unwrap();
1804    }
1805
1806    #[tokio::test(flavor = "multi_thread")]
1807    async fn edge_specifier_target_cannot_be_extruded_to_a_reference() {
1808        let code = r#"
1809@settings(kclVersion = 2.0, experimentalFeatures = allow)
1810
1811profile = startSketchOn(XY)
1812  |> startProfile(at = [0, 0])
1813  |> line(end = [1, 0], tag = $sideFace)
1814  |> line(end = [0, 1])
1815  |> line(end = [-1, 0])
1816  |> close()
1817body = extrude(profile, length = 1, tagEnd = $endFace)
1818
1819extrude(
1820  { sideFaces = [sideFace, endFace] },
1821  to = offsetPlane(XY, offset = 10),
1822  bodyType = SURFACE,
1823  method = NEW,
1824)
1825"#;
1826
1827        let err = parse_execute(code).await.unwrap_err();
1828
1829        assert!(matches!(err, KclError::Semantic { .. }), "{err:?}");
1830        assert!(
1831            err.message()
1832                .contains("Edge specifiers cannot be extruded to a reference"),
1833            "{err:?}"
1834        );
1835    }
1836
1837    #[tokio::test(flavor = "multi_thread")]
1838    async fn segment_extrude_rejects_cap_tags() {
1839        let ctx = ExecutorContext::new_mock(None).await;
1840        let mut exec_state = ExecState::new(&ctx);
1841        let err = coerce_extrude_targets(
1842            vec![segment_value(&mut exec_state)],
1843            BodyType::Surface,
1844            Some(&TagDeclarator::new("cap_start")),
1845            None,
1846            &mut exec_state,
1847            &ctx,
1848            crate::SourceRange::default(),
1849        )
1850        .await
1851        .unwrap_err();
1852
1853        assert!(
1854            err.message()
1855                .contains("`tagStart` and `tagEnd` are not supported when extruding sketch segments"),
1856            "{err:?}"
1857        );
1858        ctx.close().await;
1859    }
1860
1861    /// `getOppositeEdge()` and the other edge getters return a raw edge as
1862    /// `KclValue::Uuid`, which coerces to `Extrudable::Edge`.
1863    fn edge_value(exec_state: &mut ExecState) -> KclValue {
1864        KclValue::Uuid {
1865            value: exec_state.next_uuid(),
1866            meta: vec![],
1867        }
1868    }
1869
1870    #[tokio::test(flavor = "multi_thread")]
1871    async fn edge_extrude_rejects_solid_body_type() {
1872        let ctx = ExecutorContext::new_mock(None).await;
1873        let mut exec_state = ExecState::new(&ctx);
1874        let edge = edge_value(&mut exec_state);
1875        let err = coerce_extrude_targets(
1876            vec![edge],
1877            BodyType::Solid,
1878            None,
1879            None,
1880            &mut exec_state,
1881            &ctx,
1882            crate::SourceRange::default(),
1883        )
1884        .await
1885        .unwrap_err();
1886
1887        assert!(
1888            err.message()
1889                .contains("edges can only be extruded with surface extrudes"),
1890            "{err:?}"
1891        );
1892        ctx.close().await;
1893    }
1894
1895    #[tokio::test(flavor = "multi_thread")]
1896    async fn edge_extrude_rejects_cap_tags() {
1897        let ctx = ExecutorContext::new_mock(None).await;
1898        let mut exec_state = ExecState::new(&ctx);
1899        let edge = edge_value(&mut exec_state);
1900        let err = coerce_extrude_targets(
1901            vec![edge],
1902            BodyType::Surface,
1903            Some(&TagDeclarator::new("cap_start")),
1904            None,
1905            &mut exec_state,
1906            &ctx,
1907            crate::SourceRange::default(),
1908        )
1909        .await
1910        .unwrap_err();
1911
1912        assert!(
1913            err.message()
1914                .contains("`tagStart` and `tagEnd` are not supported when extruding edges"),
1915            "{err:?}"
1916        );
1917        ctx.close().await;
1918    }
1919
1920    #[tokio::test(flavor = "multi_thread")]
1921    async fn edge_extrude_rejects_mixing_with_face() {
1922        let ctx = ExecutorContext::new_mock(None).await;
1923        let mut exec_state = ExecState::new(&ctx);
1924        let edge = edge_value(&mut exec_state);
1925        // The string "START" coerces to a `FaceTag`, i.e. a non-edge extrudable.
1926        let face = KclValue::String {
1927            value: "START".to_owned(),
1928            meta: vec![],
1929        };
1930        let err = coerce_extrude_targets(
1931            vec![edge, face],
1932            BodyType::Surface,
1933            None,
1934            None,
1935            &mut exec_state,
1936            &ctx,
1937            crate::SourceRange::default(),
1938        )
1939        .await
1940        .unwrap_err();
1941
1942        assert!(
1943            err.message()
1944                .contains("Cannot extrude edges together with sketches or faces"),
1945            "{err:?}"
1946        );
1947        ctx.close().await;
1948    }
1949}