kcl-lib 0.2.186

KittyCAD Language implementation and tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
//! Standard library chamfers.

use anyhow::Result;
use kcmc::ModelingCmd;
use kcmc::each_cmd as mcmd;
use kcmc::length_unit::LengthUnit;
use kcmc::shared::Angle;
use kcmc::shared::CutStrategy;
use kcmc::shared::CutTypeV2;
use kcmc::shared::EdgeCutVersion;
use kittycad_modeling_cmds::{self as kcmc};

use super::args::TyF64;
use crate::errors::KclError;
use crate::errors::KclErrorDetails;
use crate::execution::ChamferSurface;
use crate::execution::EdgeCut;
use crate::execution::ExecState;
use crate::execution::ExtrudeSurface;
use crate::execution::GeoMeta;
use crate::execution::KclValue;
use crate::execution::KclVersion;
use crate::execution::ModelingCmdMeta;
use crate::execution::Sketch;
use crate::execution::Solid;
use crate::execution::types::RuntimeType;
use crate::parsing::ast::types::TagNode;
use crate::std::Args;
use crate::std::csg::CsgAlgorithm;
use crate::std::fillet::EdgeReference;
use crate::std::fillet::default_edge_cut_version;

pub(crate) const DEFAULT_TOLERANCE: f64 = 0.0000001;

/// Create chamfers on tagged paths.
pub async fn chamfer(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let solid: Box<Solid> = args.get_unlabeled_kw_arg("solid", &RuntimeType::solid(), exec_state)?;
    let length: TyF64 = args.get_kw_arg("length", &RuntimeType::length(), exec_state)?;
    let second_length = args.get_kw_arg_opt("secondLength", &RuntimeType::length(), exec_state)?;
    let angle = args.get_kw_arg_opt("angle", &RuntimeType::angle(), exec_state)?;
    let legacy_csg: Option<bool> = args.get_kw_arg_opt("legacyMethod", &RuntimeType::bool(), exec_state)?;
    let csg_algorithm = CsgAlgorithm::legacy(legacy_csg.unwrap_or_default());
    // KCL 3.0 removes the version parameter (`removed_in` in solid.kcl),
    // so from 3.0 on this is always the default: the newest edge cut
    // algorithm, which cuts all edges at once in a single engine command.
    let edge_cut_number: Option<u32> = args.get_kw_arg_opt("version", &RuntimeType::count(), exec_state)?;
    let tangent_chain: Option<bool> = args.get_kw_arg_opt("tangentChain", &RuntimeType::bool(), exec_state)?;
    let tangent_chain = tangent_chain.unwrap_or(exec_state.kcl_version() >= KclVersion::V3Preview);
    let edge_cut_version: EdgeCutVersion = edge_cut_number
        .map(|num| {
            num.try_into().map_err(|()| {
                KclError::new_semantic(KclErrorDetails::new(
                    format!("{} is not a version of the Zoo edge cut algorithm", num),
                    vec![args.source_range],
                ))
            })
        })
        .transpose()?
        .unwrap_or_else(|| default_edge_cut_version(exec_state.kcl_version()));

    let tag = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;

    // Edge specifiers are object-shaped payloads, so there is no narrow RuntimeType for them yet.
    // Keep this broad at the boundary and validate the shape in parse_tagged_edge_inputs.
    let edge_refs = args.get_kw_arg_opt("edges", &RuntimeType::any_array(), exec_state)?;
    let tags = args.kw_arg_edge_array_and_source_opt("tags")?;

    let edge_inputs = super::fillet::parse_tagged_edge_inputs(
        edge_refs,
        tags,
        Some(solid.as_ref()),
        exec_state,
        &args,
        "You must provide either 'tags' or 'edges' to chamfer edges",
        "You must provide either 'tags' or 'edges' to chamfer edges, not both",
    )
    .await?;

    match edge_inputs {
        super::fillet::TaggedEdgeInputs::EngineRefs(edge_refs) => {
            let value = inner_chamfer_with_engine_refs(
                solid,
                length,
                edge_refs,
                second_length,
                angle,
                csg_algorithm,
                edge_cut_version,
                tangent_chain,
                tag,
                exec_state,
                args,
            )
            .await?;
            Ok(KclValue::Solid { value })
        }
        super::fillet::TaggedEdgeInputs::Tags(tags) => match edge_cut_version {
            // TODO: When we change the default algorithm to V2, we need to make
            // it so that V0 (default) takes the route below.
            EdgeCutVersion::V0 | EdgeCutVersion::V1 => {
                let value = inner_chamfer(
                    solid,
                    length,
                    tags,
                    second_length,
                    angle,
                    None,
                    tag,
                    csg_algorithm,
                    edge_cut_version,
                    tangent_chain,
                    exec_state,
                    args,
                )
                .await?;
                Ok(KclValue::Solid { value })
            }
            EdgeCutVersion::V2 | _ => {
                let value = inner_chamfer_v2(
                    solid,
                    length,
                    tags,
                    second_length,
                    angle,
                    None,
                    tag,
                    csg_algorithm,
                    edge_cut_version,
                    tangent_chain,
                    exec_state,
                    args,
                )
                .await?;
                Ok(KclValue::Solid { value })
            }
        },
    }
}

#[allow(clippy::too_many_arguments)]
async fn inner_chamfer(
    solid: Box<Solid>,
    length: TyF64,
    tags: Vec<(EdgeReference, crate::SourceRange)>,
    second_length: Option<TyF64>,
    angle: Option<TyF64>,
    custom_profile: Option<Sketch>,
    tag: Option<TagNode>,
    csg_algorithm: CsgAlgorithm,
    edge_cut_version: EdgeCutVersion,
    tangent_chain: bool,
    exec_state: &mut ExecState,
    args: Args,
) -> Result<Box<Solid>, KclError> {
    // If you try and tag multiple edges with a tagged chamfer, we want to return an
    // error to the user that they can only tag one edge at a time.
    if tag.is_some() && tags.len() > 1 {
        return Err(KclError::new_type(KclErrorDetails::new(
            "You can only tag one edge at a time with a tagged chamfer. Either delete the tag for the chamfer fn if you don't need it OR separate into individual chamfer functions for each tag.".to_string(),
            vec![args.source_range],
        )));
    }

    if angle.is_some() && second_length.is_some() {
        return Err(KclError::new_semantic(KclErrorDetails::new(
            "Cannot specify both an angle and a second length. Specify only one.".to_string(),
            vec![args.source_range],
        )));
    }

    let strategy = if second_length.is_some() || angle.is_some() || custom_profile.is_some() {
        CutStrategy::Csg
    } else {
        Default::default()
    };

    let second_distance = second_length.map(|x| LengthUnit(x.to_mm()));
    let angle = angle.map(|x| Angle::from_degrees(x.to_degrees(exec_state, args.source_range)));
    if let Some(angle) = angle
        && (angle.ge(&Angle::quarter_circle()) || angle.le(&Angle::zero()))
    {
        return Err(KclError::new_semantic(KclErrorDetails::new(
            "The angle of a chamfer must be greater than zero and less than 90 degrees.".to_string(),
            vec![args.source_range],
        )));
    }

    let cut_type = if let Some(custom_profile) = custom_profile {
        // Hide the custom profile since it's no longer its own profile
        exec_state
            .batch_modeling_cmd(
                ModelingCmdMeta::from_args(exec_state, &args),
                ModelingCmd::from(
                    mcmd::ObjectVisible::builder()
                        .object_id(custom_profile.id)
                        .hidden(true)
                        .build(),
                ),
            )
            .await?;
        CutTypeV2::Custom {
            path: custom_profile.id,
        }
    } else {
        CutTypeV2::Chamfer {
            distance: LengthUnit(length.to_mm()),
            second_distance,
            angle,
            swap: false,
        }
    };

    let mut solid = solid.clone();
    let mut tag_entries: Vec<crate::execution::DirectTagFilletTagEntry> = Vec::new();
    for (edge_ref, source_range) in &tags {
        let edge_id = match edge_ref {
            EdgeReference::Uuid(u) => *u,
            EdgeReference::Tag(t) => args.get_tag_engine_info(exec_state, t)?.id,
        };
        if crate::runtime_flags::z0006_refactor_metadata_enabled()
            && let Ok(face_ids) = super::edge::get_face_ids_for_edge(exec_state, solid.id, edge_id, &args).await
            && let [a, b] = face_ids.as_slice()
        {
            let tag_identifier = match edge_ref {
                EdgeReference::Tag(t) => t.value.clone(),
                EdgeReference::Uuid(_) => String::new(),
            };
            if !tag_identifier.is_empty() {
                tag_entries.push(crate::execution::DirectTagFilletTagEntry {
                    tag_identifier,
                    edge_id,
                    face_ids: [*a, *b],
                });
            } else {
                exec_state.record_edge_refactor_meta_from_pending(edge_id, *source_range, [*a, *b]);
            }
        }
    }
    if !tag_entries.is_empty() {
        exec_state.record_direct_tag_fillet_meta(crate::execution::DirectTagFilletMeta {
            call_source_range: args.source_range,
            tags: tag_entries,
        });
    }
    for (edge_tag, _) in tags {
        let edge_ids = edge_tag.get_all_engine_ids(exec_state, &args)?;
        for edge_id in edge_ids {
            let id = exec_state.next_uuid();
            exec_state
                .batch_edge_cut_cmd(
                    ModelingCmdMeta::from_args_id(exec_state, &args, id),
                    ModelingCmd::from(
                        mcmd::Solid3dCutEdges::builder()
                            .use_legacy(csg_algorithm.is_legacy())
                            .edge_ids(vec![edge_id])
                            .extra_face_ids(vec![])
                            .strategy(strategy)
                            .object_id(solid.id)
                            // We can let the user set this in the future.
                            .tolerance(LengthUnit(DEFAULT_TOLERANCE))
                            .cut_type(cut_type)
                            .version(edge_cut_version)
                            .tangent_chain(tangent_chain)
                            .build(),
                    ),
                )
                .await?;

            solid.edge_cuts.push(EdgeCut::Chamfer {
                id,
                edge_id,
                length: length.clone(),
                tag: Box::new(tag.clone()),
            });

            if let Some(ref tag) = tag {
                solid.value.push(ExtrudeSurface::Chamfer(ChamferSurface {
                    face_id: id,
                    tag: Some(tag.clone()),
                    geo_meta: GeoMeta {
                        id,
                        metadata: args.source_range.into(),
                    },
                }));
            }
        }
    }

    Ok(solid)
}

#[allow(clippy::too_many_arguments)]
async fn inner_chamfer_v2(
    solid: Box<Solid>,
    length: TyF64,
    tags: Vec<(EdgeReference, crate::SourceRange)>,
    second_length: Option<TyF64>,
    angle: Option<TyF64>,
    custom_profile: Option<Sketch>,
    tag: Option<TagNode>,
    csg_algorithm: CsgAlgorithm,
    edge_cut_version: EdgeCutVersion,
    tangent_chain: bool,
    exec_state: &mut ExecState,
    args: Args,
) -> Result<Box<Solid>, KclError> {
    // If you try and tag multiple edges with a tagged chamfer, we want to return an
    // error to the user that they can only tag one edge at a time.
    if tag.is_some() && tags.len() > 1 {
        return Err(KclError::new_type(KclErrorDetails::new(
            "You can only tag one edge at a time with a tagged chamfer. Either delete the tag for the chamfer fn if you don't need it OR separate into individual chamfer functions for each tag.".to_string(),
            vec![args.source_range],
        )));
    }
    if tags.is_empty() {
        return Err(KclError::new_semantic(KclErrorDetails {
            source_ranges: vec![args.source_range],
            message: "You must chamfer at least one tag".to_owned(),
            backtrace: Default::default(),
        }));
    }

    if angle.is_some() && second_length.is_some() {
        return Err(KclError::new_semantic(KclErrorDetails::new(
            "Cannot specify both an angle and a second length. Specify only one.".to_string(),
            vec![args.source_range],
        )));
    }

    let strategy = if second_length.is_some() || angle.is_some() || custom_profile.is_some() {
        CutStrategy::Csg
    } else {
        Default::default()
    };

    let second_distance = second_length.map(|x| LengthUnit(x.to_mm()));
    let angle = angle.map(|x| Angle::from_degrees(x.to_degrees(exec_state, args.source_range)));
    if let Some(angle) = angle
        && (angle.ge(&Angle::quarter_circle()) || angle.le(&Angle::zero()))
    {
        return Err(KclError::new_semantic(KclErrorDetails::new(
            "The angle of a chamfer must be greater than zero and less than 90 degrees.".to_string(),
            vec![args.source_range],
        )));
    }

    let cut_type = if let Some(custom_profile) = custom_profile {
        // Hide the custom profile since it's no longer its own profile
        exec_state
            .batch_modeling_cmd(
                ModelingCmdMeta::from_args(exec_state, &args),
                ModelingCmd::from(
                    mcmd::ObjectVisible::builder()
                        .object_id(custom_profile.id)
                        .hidden(true)
                        .build(),
                ),
            )
            .await?;
        CutTypeV2::Custom {
            path: custom_profile.id,
        }
    } else {
        CutTypeV2::Chamfer {
            distance: LengthUnit(length.to_mm()),
            second_distance,
            angle,
            swap: false,
        }
    };

    let mut solid = solid.clone();
    let mut edge_ids = Vec::new();
    let mut tag_entries: Vec<crate::execution::DirectTagFilletTagEntry> = Vec::new();
    for (edge_ref, source_range) in &tags {
        let ids = edge_ref.get_all_engine_ids(exec_state, &args)?;
        edge_ids.extend(ids.iter().copied());
        let tag_identifier = match edge_ref {
            EdgeReference::Tag(t) => t.value.clone(),
            EdgeReference::Uuid(_) => String::new(),
        };
        for edge_id in ids {
            if crate::runtime_flags::z0006_refactor_metadata_enabled()
                && let Ok(face_ids) = super::edge::get_face_ids_for_edge(exec_state, solid.id, edge_id, &args).await
                && let [a, b] = face_ids.as_slice()
            {
                if !tag_identifier.is_empty() {
                    tag_entries.push(crate::execution::DirectTagFilletTagEntry {
                        tag_identifier: tag_identifier.clone(),
                        edge_id,
                        face_ids: [*a, *b],
                    });
                } else {
                    exec_state.record_edge_refactor_meta_from_pending(edge_id, *source_range, [*a, *b]);
                }
            }
        }
    }
    if !tag_entries.is_empty() {
        exec_state.record_direct_tag_fillet_meta(crate::execution::DirectTagFilletMeta {
            call_source_range: args.source_range,
            tags: tag_entries,
        });
    }

    let id = exec_state.next_uuid();
    let num_extra_ids = edge_ids.len().saturating_sub(1);
    let mut extra_face_ids = Vec::with_capacity(num_extra_ids);
    for _ in 0..num_extra_ids {
        extra_face_ids.push(exec_state.next_uuid());
    }
    exec_state
        .batch_edge_cut_cmd(
            ModelingCmdMeta::from_args_id(exec_state, &args, id),
            ModelingCmd::from(
                mcmd::Solid3dCutEdges::builder()
                    .use_legacy(csg_algorithm.is_legacy())
                    .edge_ids(edge_ids.clone())
                    .extra_face_ids(extra_face_ids)
                    .strategy(strategy)
                    .object_id(solid.id)
                    // We can let the user set this in the future.
                    .tolerance(LengthUnit(DEFAULT_TOLERANCE))
                    .cut_type(cut_type)
                    .version(edge_cut_version)
                    .tangent_chain(tangent_chain)
                    .build(),
            ),
        )
        .await?;

    let new_edge_cuts = edge_ids.into_iter().map(|edge_id| EdgeCut::Chamfer {
        id,
        edge_id,
        length: length.clone(),
        tag: Box::new(tag.clone()),
    });
    solid.edge_cuts.extend(new_edge_cuts);

    if let Some(ref tag) = tag {
        solid.value.push(ExtrudeSurface::Chamfer(ChamferSurface {
            face_id: id,
            tag: Some(tag.clone()),
            geo_meta: GeoMeta {
                id,
                metadata: args.source_range.into(),
            },
        }));
    }

    Ok(solid)
}

#[expect(clippy::too_many_arguments)]
async fn inner_chamfer_with_engine_refs(
    solid: Box<Solid>,
    length: TyF64,
    edge_references: Vec<kcmc::shared::EdgeSpecifier>,
    second_length: Option<TyF64>,
    angle: Option<TyF64>,
    csg_algorithm: CsgAlgorithm,
    edge_cut_version: EdgeCutVersion,
    tangent_chain: bool,
    tag: Option<TagNode>,
    exec_state: &mut ExecState,
    args: Args,
) -> Result<Box<Solid>, KclError> {
    if tag.is_some() && edge_references.len() > 1 {
        return Err(KclError::new_type(KclErrorDetails::new(
            "You can only tag one edge at a time with a tagged chamfer. Either delete the tag for the chamfer fn if you don't need it OR separate into individual chamfer functions for each edgeRef.".to_string(),
            vec![args.source_range],
        )));
    }

    if angle.is_some() && second_length.is_some() {
        return Err(KclError::new_semantic(KclErrorDetails::new(
            "Cannot specify both an angle and a second length. Specify only one.".to_string(),
            vec![args.source_range],
        )));
    }

    let strategy = if second_length.is_some() || angle.is_some() {
        CutStrategy::Csg
    } else {
        Default::default()
    };

    let second_distance = second_length.map(|x| LengthUnit(x.to_mm()));
    let angle = angle.map(|x| Angle::from_degrees(x.to_degrees(exec_state, args.source_range)));
    if let Some(angle) = angle
        && (angle.ge(&Angle::quarter_circle()) || angle.le(&Angle::zero()))
    {
        return Err(KclError::new_semantic(KclErrorDetails::new(
            "The angle of a chamfer must be greater than zero and less than 90 degrees.".to_string(),
            vec![args.source_range],
        )));
    }

    let cut_type = CutTypeV2::Chamfer {
        distance: LengthUnit(length.to_mm()),
        second_distance,
        angle,
        swap: false,
    };

    let id = exec_state.next_uuid();
    let num_extra_ids = edge_references.len().saturating_sub(1);
    let mut extra_face_ids = Vec::with_capacity(num_extra_ids);
    for _ in 0..num_extra_ids {
        extra_face_ids.push(exec_state.next_uuid());
    }

    let mut solid = solid.clone();
    exec_state
        .batch_edge_cut_cmd(
            ModelingCmdMeta::from_args_id(exec_state, &args, id),
            ModelingCmd::from(
                mcmd::Solid3dCutEdgeReferences::builder()
                    .object_id(solid.id)
                    .edges_references(edge_references)
                    .cut_type(cut_type)
                    .tolerance(LengthUnit(DEFAULT_TOLERANCE))
                    .strategy(strategy)
                    .extra_face_ids(extra_face_ids)
                    .use_legacy(csg_algorithm.is_legacy())
                    .version(edge_cut_version)
                    .tangent_chain(tangent_chain)
                    .build(),
            ),
        )
        .await?;

    solid.pending_edge_cut_ids.push(id);

    if let Some(ref tag) = tag {
        solid.value.push(ExtrudeSurface::Chamfer(ChamferSurface {
            face_id: id,
            tag: Some(tag.clone()),
            geo_meta: GeoMeta {
                id,
                metadata: args.source_range.into(),
            },
        }));
    }

    Ok(solid)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::execution::ExecTestResults;
    use crate::execution::parse_execute;

    /// Test what version of chamfer each KCL version uses by default.
    #[tokio::test(flavor = "multi_thread")]
    async fn chamfer_default_depends_on_kcl_version() {
        assert_eq!(emitted_chamfer_version("2.0", None).await, EdgeCutVersion::V1);
        assert_eq!(
            emitted_chamfer_version("\"3.0-preview\"", None).await,
            EdgeCutVersion::V2
        );
    }

    /// If the user chooses a chamfer algorithm version, KCL should respect it,
    /// and not use that KCL version's default chamfer algorithm version.
    #[tokio::test(flavor = "multi_thread")]
    async fn explicit_chamfer_version_overrides_kcl_default() {
        assert_eq!(emitted_chamfer_version("2.0", Some(2)).await, EdgeCutVersion::V2);
    }

    /// KCL 3.0 removed `chamfer(version = )`. Passing it is reported like any
    /// other unknown argument, and the default algorithm is used.
    #[tokio::test(flavor = "multi_thread")]
    async fn chamfer_version_is_removed_in_kcl_3() {
        let result = run_chamfer("\"3.0-preview\"", Some(1)).await;
        assert!(
            result
                .issues()
                .iter()
                .any(|issue| {
                    issue.message
                        == "`version` is not an argument of `chamfer`; it was removed in KCL 3.0, but this program uses KCL 3.0-preview"
                }),
            "issues: {:#?}",
            result.issues()
        );
        assert_eq!(emitted_cut_edges_version(&result), EdgeCutVersion::V2);
    }

    /// For a given KCL version, and optional `chamfer(version = )` version,
    /// show what chamfer algorithm version the runtime sent to the engine.
    async fn emitted_chamfer_version(kcl_version: &str, explicit_version: Option<u32>) -> EdgeCutVersion {
        emitted_cut_edges_version(&run_chamfer(kcl_version, explicit_version).await)
    }

    /// Chamfer one edge of a box under the given KCL version, optionally
    /// passing `chamfer(version = )`.
    async fn run_chamfer(kcl_version: &str, explicit_version: Option<u32>) -> ExecTestResults {
        let version_arg = explicit_version
            .map(|version| format!(", version = {version}"))
            .unwrap_or_default();
        let code = format!(
            r#"@settings(kclVersion = {kcl_version}, experimentalFeatures = allow)

profile = sketch(on = XY) {{
  edge1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
  edge2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
  edge3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
  edge4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
  coincident([edge1.end, edge2.start])
  coincident([edge2.end, edge3.start])
  coincident([edge3.end, edge4.start])
  coincident([edge4.end, edge1.start])
}}
profileRegion = region(point = [5mm, 5mm], sketch = profile)
solid = extrude(profileRegion, length = 10mm, tagEnd = $top)
chamfer(solid, tags = [getCommonEdge(faces = [profileRegion.tags.edge1, top])], length = 1mm{version_arg})
"#
        );

        parse_execute(&code).await.unwrap()
    }

    /// The chamfer algorithm version the runtime sent to the engine.
    fn emitted_cut_edges_version(result: &ExecTestResults) -> EdgeCutVersion {
        result
            .root_module_artifact_commands()
            .iter()
            .find_map(|artifact_command| match &artifact_command.command {
                ModelingCmd::Solid3dCutEdges(command) => Some(command.version),
                _ => None,
            })
            .expect("chamfer should emit a Solid3dCutEdges command")
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn tangent_chain_requires_kcl_3_and_is_sent_to_engine() {
        let body = r#"
profile = sketch(on = XY) {
  edge1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
  edge2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
  edge3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
  edge4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
  coincident([edge1.end, edge2.start])
  coincident([edge2.end, edge3.start])
  coincident([edge3.end, edge4.start])
  coincident([edge4.end, edge1.start])
}
profileRegion = region(point = [5mm, 5mm], sketch = profile)
solid = extrude(profileRegion, length = 10mm, tagEnd = $top)
chamfer(solid, tags = [getCommonEdge(faces = [profileRegion.tags.edge1, top])], length = 1mm, tangentChain = true)
"#;

        let result = parse_execute(&format!("@settings(kclVersion = 2.0)\n{body}"))
            .await
            .unwrap();
        assert!(result.issues().iter().any(|issue| {
            issue.message
                == "`tangentChain` is not an argument of `chamfer`; it was added in KCL 3.0, but this program uses KCL 2.0"
        }));

        let result = parse_execute(&format!("@settings(kclVersion = \"3.0-preview\")\n{body}"))
            .await
            .unwrap();
        let tangent_chain = result
            .root_module_artifact_commands()
            .iter()
            .find_map(|artifact_command| match &artifact_command.command {
                ModelingCmd::Solid3dCutEdges(command) => Some(command.tangent_chain),
                _ => None,
            })
            .expect("chamfer should emit a Solid3dCutEdges command");
        assert!(tangent_chain);

        let default_body = body.replace(", tangentChain = true", "");
        let result = parse_execute(&format!("@settings(kclVersion = \"3.0-preview\")\n{default_body}"))
            .await
            .unwrap();
        let tangent_chain = result
            .root_module_artifact_commands()
            .iter()
            .find_map(|artifact_command| match &artifact_command.command {
                ModelingCmd::Solid3dCutEdges(command) => Some(command.tangent_chain),
                _ => None,
            })
            .expect("chamfer should emit a Solid3dCutEdges command");
        assert!(tangent_chain, "tangentChain should default to true after KCL 2");

        let disabled_body = body.replace("tangentChain = true", "tangentChain = false");
        let result = parse_execute(&format!("@settings(kclVersion = \"3.0-preview\")\n{disabled_body}"))
            .await
            .unwrap();
        let tangent_chain = result
            .root_module_artifact_commands()
            .iter()
            .find_map(|artifact_command| match &artifact_command.command {
                ModelingCmd::Solid3dCutEdges(command) => Some(command.tangent_chain),
                _ => None,
            })
            .expect("chamfer should emit a Solid3dCutEdges command");
        assert!(!tangent_chain, "an explicit false should override the default");
    }
}