Skip to main content

kcl_lib/std/
csg.rs

1//! Constructive Solid Geometry (CSG) operations.
2
3use anyhow::Result;
4use kcl_error::CompilationIssue;
5use kcmc::ModelingCmd;
6use kcmc::each_cmd as mcmd;
7use kcmc::length_unit::LengthUnit;
8use kittycad_modeling_cmds::ok_response::OkModelingCmdResponse;
9use kittycad_modeling_cmds::websocket::OkWebSocketResponseData;
10use kittycad_modeling_cmds::{self as kcmc};
11
12use super::DEFAULT_TOLERANCE_MM;
13use super::args::TyF64;
14use super::solid_consumption::record_consumed_solids;
15use super::solid_consumption::validate_solids_not_consumed;
16use crate::errors::KclError;
17use crate::errors::KclErrorDetails;
18use crate::execution::ConsumedSolidOperation;
19use crate::execution::ExecState;
20use crate::execution::KclValue;
21use crate::execution::ModelingCmdMeta;
22use crate::execution::Solid;
23use crate::execution::annotations;
24use crate::execution::types::RuntimeType;
25use crate::std::Args;
26use crate::std::patterns::GeometryTrait;
27
28/// Union two or more solids into a single solid.
29pub async fn union(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
30    let solids: Vec<Solid> =
31        args.get_unlabeled_kw_arg("solids", &RuntimeType::Union(vec![RuntimeType::solids()]), exec_state)?;
32    let tolerance: Option<TyF64> = args.get_kw_arg_opt("tolerance", &RuntimeType::length(), exec_state)?;
33    let legacy_csg: Option<bool> = args.get_kw_arg_opt("legacyMethod", &RuntimeType::bool(), exec_state)?;
34    let csg_algorithm = CsgAlgorithm::legacy(legacy_csg.unwrap_or_default());
35
36    if solids.len() < 2 {
37        return Err(KclError::new_semantic(KclErrorDetails::new(
38            "At least two solids are required for a union operation.".to_string(),
39            vec![args.source_range],
40        )));
41    }
42
43    let solids = inner_union(solids, tolerance, csg_algorithm, exec_state, args).await?;
44    Ok(solids.into())
45}
46
47pub enum CsgAlgorithm {
48    Latest,
49    Legacy,
50}
51
52impl CsgAlgorithm {
53    pub fn legacy(is_legacy: bool) -> Self {
54        if is_legacy { Self::Legacy } else { Self::Latest }
55    }
56    pub fn is_legacy(&self) -> bool {
57        match self {
58            CsgAlgorithm::Latest => false,
59            CsgAlgorithm::Legacy => true,
60        }
61    }
62}
63
64fn is_single_target_self_subtract(target_ids: &[uuid::Uuid], tool_ids: &[uuid::Uuid]) -> bool {
65    target_ids.len() == 1 && tool_ids.len() == 1 && target_ids[0] == tool_ids[0]
66}
67
68fn subtract_output_ids(
69    solid_out_id: uuid::Uuid,
70    target_ids: &[uuid::Uuid],
71    tool_ids: &[uuid::Uuid],
72    extra_solid_ids: &[uuid::Uuid],
73) -> Vec<uuid::Uuid> {
74    if is_single_target_self_subtract(target_ids, tool_ids) {
75        return Vec::new();
76    }
77
78    let mut output_ids = if target_ids.len() == 1 {
79        vec![solid_out_id]
80    } else {
81        Vec::new()
82    };
83
84    for extra_solid_id in extra_solid_ids {
85        if !output_ids.contains(extra_solid_id) {
86            output_ids.push(*extra_solid_id);
87        }
88    }
89
90    output_ids
91}
92
93pub(crate) async fn inner_union(
94    solids: Vec<Solid>,
95    tolerance: Option<TyF64>,
96    csg_algorithm: CsgAlgorithm,
97    exec_state: &mut ExecState,
98    args: Args,
99) -> Result<Vec<Solid>, KclError> {
100    validate_solids_not_consumed(&solids, exec_state, args.source_range)?;
101
102    let solid_out_id = exec_state.next_uuid();
103
104    let mut solid = solids[0].clone();
105    solid.set_id(solid_out_id);
106    solid.become_new_body(solid_out_id, solid_out_id.into());
107    let mut new_solids = vec![solid.clone()];
108
109    if args.ctx.no_engine_commands().await {
110        record_consumed_solids(exec_state, &solids, ConsumedSolidOperation::Union, &new_solids);
111        return Ok(new_solids);
112    }
113
114    // Flush the fillets for the solids.
115    exec_state
116        .flush_batch_for_solids(ModelingCmdMeta::from_args(exec_state, &args), &solids)
117        .await?;
118
119    let result = exec_state
120        .send_modeling_cmd(
121            ModelingCmdMeta::from_args_id(exec_state, &args, solid_out_id),
122            ModelingCmd::from(
123                mcmd::BooleanUnion::builder()
124                    .use_legacy(csg_algorithm.is_legacy())
125                    .solid_ids(solids.iter().map(|s| s.id).collect())
126                    .tolerance(LengthUnit(tolerance.map(|t| t.to_mm()).unwrap_or(DEFAULT_TOLERANCE_MM)))
127                    .build(),
128            ),
129        )
130        .await?;
131
132    let OkWebSocketResponseData::Modeling {
133        modeling_response: OkModelingCmdResponse::BooleanUnion(boolean_resp),
134    } = result
135    else {
136        return Err(KclError::new_internal(KclErrorDetails::new(
137            "Failed to get the result of the union operation.".to_string(),
138            vec![args.source_range],
139        )));
140    };
141
142    if !boolean_resp.any_intersections {
143        exec_state.warn(
144            CompilationIssue::err(
145                args.source_range,
146                "The bodies in this union had no overlap. This usually indicates a problem in your model, these bodies were probably intended to intersect somewhere.".to_string(),
147            ),
148            annotations::WARN_CSG_NO_INTERSECTION,
149        );
150    }
151
152    // If we have more solids, set those as well.
153    for extra_solid_id in boolean_resp.extra_solid_ids {
154        if extra_solid_id == solid_out_id {
155            continue;
156        }
157        let mut new_solid = solid.clone();
158        new_solid.set_id(extra_solid_id);
159        new_solid.value_id = solid_out_id;
160        new_solid.become_new_body(extra_solid_id, extra_solid_id.into());
161        new_solids.push(new_solid);
162    }
163
164    record_consumed_solids(exec_state, &solids, ConsumedSolidOperation::Union, &new_solids);
165
166    Ok(new_solids)
167}
168
169/// Intersect returns the shared volume between multiple solids, preserving only
170/// overlapping regions.
171pub async fn intersect(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
172    let solids: Vec<Solid> = args.get_unlabeled_kw_arg("solids", &RuntimeType::solids(), exec_state)?;
173    let tolerance: Option<TyF64> = args.get_kw_arg_opt("tolerance", &RuntimeType::length(), exec_state)?;
174    let legacy_csg: Option<bool> = args.get_kw_arg_opt("legacyMethod", &RuntimeType::bool(), exec_state)?;
175    let csg_algorithm = CsgAlgorithm::legacy(legacy_csg.unwrap_or_default());
176
177    if solids.len() < 2 {
178        return Err(KclError::new_semantic(KclErrorDetails::new(
179            "At least two solids are required for an intersect operation.".to_string(),
180            vec![args.source_range],
181        )));
182    }
183
184    let solids = inner_intersect(solids, tolerance, csg_algorithm, exec_state, args).await?;
185    Ok(solids.into())
186}
187
188pub(crate) async fn inner_intersect(
189    solids: Vec<Solid>,
190    tolerance: Option<TyF64>,
191    csg_algorithm: CsgAlgorithm,
192    exec_state: &mut ExecState,
193    args: Args,
194) -> Result<Vec<Solid>, KclError> {
195    validate_solids_not_consumed(&solids, exec_state, args.source_range)?;
196
197    let solid_out_id = exec_state.next_uuid();
198
199    let mut solid = solids[0].clone();
200    solid.set_id(solid_out_id);
201    solid.become_new_body(solid_out_id, solid_out_id.into());
202    let mut new_solids = vec![solid.clone()];
203
204    if args.ctx.no_engine_commands().await {
205        record_consumed_solids(exec_state, &solids, ConsumedSolidOperation::Intersect, &new_solids);
206        return Ok(new_solids);
207    }
208
209    // Flush the fillets for the solids.
210    exec_state
211        .flush_batch_for_solids(ModelingCmdMeta::from_args(exec_state, &args), &solids)
212        .await?;
213
214    let result = exec_state
215        .send_modeling_cmd(
216            ModelingCmdMeta::from_args_id(exec_state, &args, solid_out_id),
217            ModelingCmd::from(
218                mcmd::BooleanIntersection::builder()
219                    .use_legacy(csg_algorithm.is_legacy())
220                    .solid_ids(solids.iter().map(|s| s.id).collect())
221                    .tolerance(LengthUnit(tolerance.map(|t| t.to_mm()).unwrap_or(DEFAULT_TOLERANCE_MM)))
222                    .build(),
223            ),
224        )
225        .await?;
226
227    let OkWebSocketResponseData::Modeling {
228        modeling_response: OkModelingCmdResponse::BooleanIntersection(boolean_resp),
229    } = result
230    else {
231        return Err(KclError::new_internal(KclErrorDetails::new(
232            "Failed to get the result of the intersection operation.".to_string(),
233            vec![args.source_range],
234        )));
235    };
236    if !boolean_resp.any_intersections {
237        exec_state.warn(
238            CompilationIssue::err(
239                args.source_range,
240                "The bodies in this intersection had no overlap. This usually indicates a problem in your model, these bodies were probably intended to intersect somewhere.".to_string(),
241            ),
242            annotations::WARN_CSG_NO_INTERSECTION,
243        );
244    }
245
246    // If we have more solids, set those as well.
247    for extra_solid_id in boolean_resp.extra_solid_ids {
248        if extra_solid_id == solid_out_id {
249            continue;
250        }
251        let mut new_solid = solid.clone();
252        new_solid.set_id(extra_solid_id);
253        new_solid.value_id = solid_out_id;
254        new_solid.become_new_body(extra_solid_id, extra_solid_id.into());
255        new_solids.push(new_solid);
256    }
257
258    record_consumed_solids(exec_state, &solids, ConsumedSolidOperation::Intersect, &new_solids);
259
260    Ok(new_solids)
261}
262
263/// Subtract removes tool solids from base solids, leaving the remaining material.
264pub async fn subtract(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
265    let solids: Vec<Solid> = args.get_unlabeled_kw_arg("solids", &RuntimeType::solids(), exec_state)?;
266    let tools: Vec<Solid> = args.get_kw_arg("tools", &RuntimeType::solids(), exec_state)?;
267
268    let tolerance: Option<TyF64> = args.get_kw_arg_opt("tolerance", &RuntimeType::length(), exec_state)?;
269    let legacy_csg: Option<bool> = args.get_kw_arg_opt("legacyMethod", &RuntimeType::bool(), exec_state)?;
270    let csg_algorithm = CsgAlgorithm::legacy(legacy_csg.unwrap_or_default());
271
272    let solids = inner_subtract(solids, tools, tolerance, csg_algorithm, exec_state, args).await?;
273    Ok(solids.into())
274}
275
276pub(crate) async fn inner_subtract(
277    solids: Vec<Solid>,
278    tools: Vec<Solid>,
279    tolerance: Option<TyF64>,
280    csg_algorithm: CsgAlgorithm,
281    exec_state: &mut ExecState,
282    args: Args,
283) -> Result<Vec<Solid>, KclError> {
284    let combined_solids = solids.iter().chain(tools.iter()).cloned().collect::<Vec<Solid>>();
285    validate_solids_not_consumed(&combined_solids, exec_state, args.source_range)?;
286
287    let solid_out_id = exec_state.next_uuid();
288    let target_ids = solids.iter().map(|s| s.id).collect::<Vec<_>>();
289    let tool_ids = tools.iter().map(|s| s.id).collect::<Vec<_>>();
290
291    if args.ctx.no_engine_commands().await {
292        // Output N new bodies, where N is the number of input target bodies.
293        let new_solids = solids
294            .iter()
295            .enumerate()
296            .map(|(index, solid)| {
297                // The first ID is set by the user, subsequent IDs are not.
298                // This matches the usual production normal execution path.
299                let output_id = if index == 0 {
300                    solid_out_id
301                } else {
302                    exec_state.next_uuid()
303                };
304                let mut new_solid = solid.clone();
305                new_solid.set_id(output_id);
306                new_solid.become_new_body(output_id, output_id.into());
307                new_solid
308            })
309            .collect::<Vec<_>>();
310        record_consumed_solids(exec_state, &solids, ConsumedSolidOperation::Subtract, &new_solids);
311        record_consumed_solids(exec_state, &tools, ConsumedSolidOperation::Subtract, &[]);
312        return Ok(new_solids);
313    }
314
315    // Flush the fillets for the solids and the tools.
316    exec_state
317        .flush_batch_for_solids(ModelingCmdMeta::from_args(exec_state, &args), &combined_solids)
318        .await?;
319
320    let result = exec_state
321        .send_modeling_cmd(
322            ModelingCmdMeta::from_args_id(exec_state, &args, solid_out_id),
323            ModelingCmd::from(
324                mcmd::BooleanSubtract::builder()
325                    .use_legacy(csg_algorithm.is_legacy())
326                    .target_ids(target_ids.clone())
327                    .tool_ids(tool_ids.clone())
328                    .tolerance(LengthUnit(tolerance.map(|t| t.to_mm()).unwrap_or(DEFAULT_TOLERANCE_MM)))
329                    .build(),
330            ),
331        )
332        .await?;
333
334    let OkWebSocketResponseData::Modeling {
335        modeling_response: OkModelingCmdResponse::BooleanSubtract(boolean_resp),
336    } = result
337    else {
338        return Err(KclError::new_internal(KclErrorDetails::new(
339            "Failed to get the result of the subtract operation.".to_string(),
340            vec![args.source_range],
341        )));
342    };
343
344    if !boolean_resp.any_intersections {
345        exec_state.warn(
346            CompilationIssue::err(
347                args.source_range,
348                "The bodies in this subtraction had no overlap. This usually indicates a problem in your model, these bodies were probably intended to intersect somewhere.".to_string(),
349            ),
350            annotations::WARN_CSG_NO_INTERSECTION,
351        );
352    }
353
354    let output_ids = subtract_output_ids(solid_out_id, &target_ids, &tool_ids, &boolean_resp.extra_solid_ids);
355    let new_solids = output_ids
356        .into_iter()
357        .map(|output_id| {
358            let mut new_solid = solids[0].clone();
359            new_solid.set_id(output_id);
360            new_solid.value_id = solid_out_id;
361            new_solid.become_new_body(output_id, output_id.into());
362            new_solid
363        })
364        .collect::<Vec<_>>();
365
366    record_consumed_solids(exec_state, &solids, ConsumedSolidOperation::Subtract, &new_solids);
367    record_consumed_solids(exec_state, &tools, ConsumedSolidOperation::Subtract, &[]);
368
369    Ok(new_solids)
370}
371
372/// Split a target body into two parts: the part that overlaps with the tool, and the part that doesn't.
373pub async fn split(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
374    let targets: Vec<Solid> = args.get_unlabeled_kw_arg("targets", &RuntimeType::solids(), exec_state)?;
375    let tolerance: Option<TyF64> = args.get_kw_arg_opt("tolerance", &RuntimeType::length(), exec_state)?;
376    let legacy_csg: Option<bool> = args.get_kw_arg_opt("legacyMethod", &RuntimeType::bool(), exec_state)?;
377    let csg_algorithm = CsgAlgorithm::legacy(legacy_csg.unwrap_or_default());
378    let tools: Option<Vec<Solid>> = args.get_kw_arg_opt("tools", &RuntimeType::solids(), exec_state)?;
379    let keep_tools = args
380        .get_kw_arg_opt("keepTools", &RuntimeType::bool(), exec_state)?
381        .unwrap_or_default();
382    let merge = args
383        .get_kw_arg_opt("merge", &RuntimeType::bool(), exec_state)?
384        .unwrap_or_default();
385
386    if targets.is_empty() {
387        return Err(KclError::new_semantic(KclErrorDetails::new(
388            "At least one target body is required.".to_string(),
389            vec![args.source_range],
390        )));
391    }
392
393    let body = inner_imprint(
394        targets,
395        tools,
396        keep_tools,
397        merge,
398        tolerance,
399        csg_algorithm,
400        exec_state,
401        args,
402    )
403    .await?;
404    Ok(body.into())
405}
406
407#[allow(clippy::too_many_arguments)]
408pub(crate) async fn inner_imprint(
409    targets: Vec<Solid>,
410    tools: Option<Vec<Solid>>,
411    keep_tools: bool,
412    merge: bool,
413    tolerance: Option<TyF64>,
414    csg_algorithm: CsgAlgorithm,
415    exec_state: &mut ExecState,
416    args: Args,
417) -> Result<Vec<Solid>, KclError> {
418    validate_solids_not_consumed(&targets, exec_state, args.source_range)?;
419    if let Some(tools) = tools.as_ref() {
420        validate_solids_not_consumed(tools, exec_state, args.source_range)?;
421    }
422
423    let body_out_id = exec_state.next_uuid();
424
425    let mut body = targets[0].clone();
426    body.set_id(body_out_id);
427    body.become_new_body(body_out_id, body_out_id.into());
428    let mut new_solids = vec![body.clone()];
429    let separate_bodies = !merge;
430
431    if args.ctx.no_engine_commands().await {
432        if separate_bodies {
433            let extra_solid_id = exec_state.next_uuid();
434            let mut new_solid = body.clone();
435            new_solid.set_id(extra_solid_id);
436            new_solid.value_id = body_out_id;
437            new_solid.become_new_body(extra_solid_id, extra_solid_id.into());
438            new_solids.push(new_solid);
439        }
440        record_consumed_solids(exec_state, &targets, ConsumedSolidOperation::Split, &new_solids);
441        if !keep_tools && let Some(tools) = tools.as_ref() {
442            record_consumed_solids(exec_state, tools, ConsumedSolidOperation::Split, &[]);
443        }
444        return Ok(new_solids);
445    }
446
447    // Flush pending edge-cut operations for any solids consumed by imprint.
448    let mut imprint_solids = targets.clone();
449    if let Some(tool_solids) = tools.as_ref() {
450        imprint_solids.extend_from_slice(tool_solids);
451    }
452    exec_state
453        .flush_batch_for_solids(ModelingCmdMeta::from_args(exec_state, &args), &imprint_solids)
454        .await?;
455
456    let body_ids = targets.iter().map(|body| body.id).collect();
457    let tool_ids = tools.as_ref().map(|tools| tools.iter().map(|tool| tool.id).collect());
458    let tolerance = LengthUnit(tolerance.map(|t| t.to_mm()).unwrap_or(DEFAULT_TOLERANCE_MM));
459    let imprint_cmd = mcmd::BooleanImprint::builder()
460        .use_legacy(csg_algorithm.is_legacy())
461        .body_ids(body_ids)
462        .tolerance(tolerance)
463        .separate_bodies(separate_bodies)
464        .keep_tools(keep_tools)
465        .maybe_tool_ids(tool_ids)
466        .build();
467    let result = exec_state
468        .send_modeling_cmd(
469            ModelingCmdMeta::from_args_id(exec_state, &args, body_out_id),
470            ModelingCmd::from(imprint_cmd),
471        )
472        .await?;
473
474    let OkWebSocketResponseData::Modeling {
475        modeling_response: OkModelingCmdResponse::BooleanImprint(boolean_resp),
476    } = result
477    else {
478        return Err(KclError::new_internal(KclErrorDetails::new(
479            "Failed to get the result of the Imprint operation.".to_string(),
480            vec![args.source_range],
481        )));
482    };
483    if !boolean_resp.any_intersections {
484        exec_state.warn(
485            CompilationIssue::err(
486                args.source_range,
487                "The bodies in this split had no overlap. This usually indicates a problem in your model, these bodies were probably intended to intersect somewhere.".to_string(),
488            ),
489            annotations::WARN_CSG_NO_INTERSECTION,
490        );
491    }
492
493    // If we have more solids, set those as well.
494    for extra_solid_id in boolean_resp.extra_solid_ids {
495        if extra_solid_id == body_out_id {
496            continue;
497        }
498        let mut new_solid = body.clone();
499        new_solid.set_id(extra_solid_id);
500        new_solid.value_id = body_out_id;
501        new_solid.become_new_body(extra_solid_id, extra_solid_id.into());
502        new_solids.push(new_solid);
503    }
504
505    record_consumed_solids(exec_state, &targets, ConsumedSolidOperation::Split, &new_solids);
506    if !keep_tools && let Some(tools) = tools.as_ref() {
507        record_consumed_solids(exec_state, tools, ConsumedSolidOperation::Split, &[]);
508    }
509
510    Ok(new_solids)
511}
512
513#[cfg(test)]
514mod tests {
515    use uuid::Uuid;
516
517    use super::subtract_output_ids;
518    use crate::errors::KclError;
519    use crate::execution::MockConfig;
520
521    fn test_uuid(id: u128) -> Uuid {
522        Uuid::from_u128(id)
523    }
524
525    #[test]
526    fn subtract_output_ids_single_target_uses_command_id() {
527        let output_id = test_uuid(100);
528        let target_id = test_uuid(1);
529        let tool_id = test_uuid(2);
530        let extra_id = test_uuid(3);
531
532        let output_ids = subtract_output_ids(output_id, &[target_id], &[tool_id], &[extra_id]);
533
534        assert_eq!(output_ids, vec![output_id, extra_id]);
535    }
536
537    #[test]
538    fn subtract_output_ids_multi_target_uses_response_ids_only() {
539        let output_id = test_uuid(100);
540        let target_ids = [test_uuid(1), test_uuid(2)];
541        let tool_id = test_uuid(3);
542        let extra_ids = [test_uuid(4), test_uuid(5)];
543
544        let output_ids = subtract_output_ids(output_id, &target_ids, &[tool_id], &extra_ids);
545
546        assert_eq!(output_ids, extra_ids);
547    }
548
549    #[test]
550    fn subtract_output_ids_self_subtract_returns_no_outputs() {
551        let output_id = test_uuid(100);
552        let target_id = test_uuid(1);
553
554        let output_ids = subtract_output_ids(output_id, &[target_id], &[target_id], &[]);
555
556        assert!(output_ids.is_empty());
557    }
558
559    #[tokio::test(flavor = "multi_thread")]
560    async fn subtract_reusing_consumed_target_reports_kcl_error() {
561        let code = r#"
562targetSketch = sketch(on = XY) {
563  line1 = line(start = [var -10, var -10], end = [var 10, var -10])
564  line2 = line(start = [var 10, var -10], end = [var 10, var 10])
565  line3 = line(start = [var 10, var 10], end = [var -10, var 10])
566  line4 = line(start = [var -10, var 10], end = [var -10, var -10])
567  coincident([line1.end, line2.start])
568  coincident([line2.end, line3.start])
569  coincident([line3.end, line4.start])
570  coincident([line4.end, line1.start])
571  equalLength([line1, line2, line3, line4])
572}
573
574target = extrude(region(point = [0, 0], sketch = targetSketch), length = 20)
575
576tool1Sketch = sketch(on = XY) {
577  line1 = line(start = [var -11, var -11], end = [var -7, var -11])
578  line2 = line(start = [var -7, var -11], end = [var -7, var -7])
579  line3 = line(start = [var -7, var -7], end = [var -11, var -7])
580  line4 = line(start = [var -11, var -7], end = [var -11, var -11])
581  coincident([line1.end, line2.start])
582  coincident([line2.end, line3.start])
583  coincident([line3.end, line4.start])
584  coincident([line4.end, line1.start])
585  equalLength([line1, line2, line3, line4])
586}
587
588tool1 = extrude(region(point = [-9, -9], sketch = tool1Sketch), length = 4)
589
590tool2Sketch = sketch(on = XY) {
591  line1 = line(start = [var 7, var 7], end = [var 11, var 7])
592  line2 = line(start = [var 11, var 7], end = [var 11, var 11])
593  line3 = line(start = [var 11, var 11], end = [var 7, var 11])
594  line4 = line(start = [var 7, var 11], end = [var 7, var 7])
595  coincident([line1.end, line2.start])
596  coincident([line2.end, line3.start])
597  coincident([line3.end, line4.start])
598  coincident([line4.end, line1.start])
599  equalLength([line1, line2, line3, line4])
600}
601
602tool2 = extrude(region(point = [9, 9], sketch = tool2Sketch), length = 4)
603
604first = subtract(target, tools = [tool1])
605second = subtract(target, tools = [tool2])
606"#;
607
608        let ctx = crate::ExecutorContext::new_mock(None).await;
609        let program = crate::Program::parse_no_errs(code).unwrap();
610        let err = ctx.run_mock(&program, &MockConfig::default()).await.unwrap_err();
611        ctx.close().await;
612
613        assert!(matches!(&err.error, KclError::Semantic { .. }), "{:?}", err.error);
614        let message = err.error.message();
615        assert!(
616            message.contains("`target` was already consumed by a `subtract` operation"),
617            "{message}"
618        );
619        assert!(
620            message.contains("The operation result is now in `first`; use that for subsequent operations"),
621            "{message}"
622        );
623    }
624
625    #[tokio::test(flavor = "multi_thread")]
626    async fn subtract_reusing_consumed_tool_reports_kcl_error() {
627        let code = r#"
628targetSketch = sketch(on = XY) {
629  line1 = line(start = [var -10, var -10], end = [var 10, var -10])
630  line2 = line(start = [var 10, var -10], end = [var 10, var 10])
631  line3 = line(start = [var 10, var 10], end = [var -10, var 10])
632  line4 = line(start = [var -10, var 10], end = [var -10, var -10])
633  coincident([line1.end, line2.start])
634  coincident([line2.end, line3.start])
635  coincident([line3.end, line4.start])
636  coincident([line4.end, line1.start])
637  equalLength([line1, line2, line3, line4])
638}
639
640target = extrude(region(point = [0, 0], sketch = targetSketch), length = 20)
641
642toolSketch = sketch(on = XY) {
643  line1 = line(start = [var -2, var -2], end = [var 2, var -2])
644  line2 = line(start = [var 2, var -2], end = [var 2, var 2])
645  line3 = line(start = [var 2, var 2], end = [var -2, var 2])
646  line4 = line(start = [var -2, var 2], end = [var -2, var -2])
647  coincident([line1.end, line2.start])
648  coincident([line2.end, line3.start])
649  coincident([line3.end, line4.start])
650  coincident([line4.end, line1.start])
651  equalLength([line1, line2, line3, line4])
652}
653
654tool = extrude(region(point = [0, 0], sketch = toolSketch), length = 4)
655
656first = subtract(target, tools = [tool])
657second = subtract(first, tools = [tool])
658"#;
659
660        let ctx = crate::ExecutorContext::new_mock(None).await;
661        let program = crate::Program::parse_no_errs(code).unwrap();
662        let err = ctx.run_mock(&program, &MockConfig::default()).await.unwrap_err();
663        ctx.close().await;
664
665        assert!(matches!(&err.error, KclError::Semantic { .. }), "{:?}", err.error);
666        let message = err.error.message();
667        assert!(
668            message.contains("`tool` was already consumed by a `subtract` operation"),
669            "{message}"
670        );
671        assert!(message.contains("can no longer be used"), "{message}");
672    }
673
674    #[tokio::test(flavor = "multi_thread")]
675    async fn union_reusing_consumed_solid_reports_kcl_error() {
676        let code = r#"
677leftSketch = sketch(on = XY) {
678  line1 = line(start = [var -10, var -10], end = [var -2, var -10])
679  line2 = line(start = [var -2, var -10], end = [var -2, var -2])
680  line3 = line(start = [var -2, var -2], end = [var -10, var -2])
681  line4 = line(start = [var -10, var -2], end = [var -10, var -10])
682  coincident([line1.end, line2.start])
683  coincident([line2.end, line3.start])
684  coincident([line3.end, line4.start])
685  coincident([line4.end, line1.start])
686  equalLength([line1, line2, line3, line4])
687}
688
689left = extrude(region(point = [-6, -6], sketch = leftSketch), length = 8)
690
691rightSketch = sketch(on = XY) {
692  line1 = line(start = [var -2, var -2], end = [var 6, var -2])
693  line2 = line(start = [var 6, var -2], end = [var 6, var 6])
694  line3 = line(start = [var 6, var 6], end = [var -2, var 6])
695  line4 = line(start = [var -2, var 6], end = [var -2, var -2])
696  coincident([line1.end, line2.start])
697  coincident([line2.end, line3.start])
698  coincident([line3.end, line4.start])
699  coincident([line4.end, line1.start])
700  equalLength([line1, line2, line3, line4])
701}
702
703right = extrude(region(point = [2, 2], sketch = rightSketch), length = 8)
704
705toolSketch = sketch(on = XY) {
706  line1 = line(start = [var -1, var -1], end = [var 1, var -1])
707  line2 = line(start = [var 1, var -1], end = [var 1, var 1])
708  line3 = line(start = [var 1, var 1], end = [var -1, var 1])
709  line4 = line(start = [var -1, var 1], end = [var -1, var -1])
710  coincident([line1.end, line2.start])
711  coincident([line2.end, line3.start])
712  coincident([line3.end, line4.start])
713  coincident([line4.end, line1.start])
714  equalLength([line1, line2, line3, line4])
715}
716
717tool = extrude(region(point = [0, 0], sketch = toolSketch), length = 2)
718
719first = union([left, right])
720second = union([first, tool])
721third = subtract(left, tools = [tool])
722"#;
723
724        let ctx = crate::ExecutorContext::new_mock(None).await;
725        let program = crate::Program::parse_no_errs(code).unwrap();
726        let err = ctx.run_mock(&program, &MockConfig::default()).await.unwrap_err();
727        ctx.close().await;
728
729        assert!(matches!(&err.error, KclError::Semantic { .. }), "{:?}", err.error);
730        let message = err.error.message();
731        assert!(
732            message.contains("`left` was already consumed by a `union` operation"),
733            "{message}"
734        );
735        assert!(
736            message.contains("The operation result is now in `second`; use that for subsequent operations"),
737            "{message}"
738        );
739    }
740
741    #[tokio::test(flavor = "multi_thread")]
742    async fn intersect_reusing_consumed_solid_reports_kcl_error() {
743        let code = r#"
744leftSketch = sketch(on = XY) {
745  line1 = line(start = [var -10, var -10], end = [var 4, var -10])
746  line2 = line(start = [var 4, var -10], end = [var 4, var 4])
747  line3 = line(start = [var 4, var 4], end = [var -10, var 4])
748  line4 = line(start = [var -10, var 4], end = [var -10, var -10])
749  coincident([line1.end, line2.start])
750  coincident([line2.end, line3.start])
751  coincident([line3.end, line4.start])
752  coincident([line4.end, line1.start])
753  equalLength([line1, line2, line3, line4])
754}
755
756left = extrude(region(point = [-3, -3], sketch = leftSketch), length = 8)
757
758rightSketch = sketch(on = XY) {
759  line1 = line(start = [var -4, var -4], end = [var 10, var -4])
760  line2 = line(start = [var 10, var -4], end = [var 10, var 10])
761  line3 = line(start = [var 10, var 10], end = [var -4, var 10])
762  line4 = line(start = [var -4, var 10], end = [var -4, var -4])
763  coincident([line1.end, line2.start])
764  coincident([line2.end, line3.start])
765  coincident([line3.end, line4.start])
766  coincident([line4.end, line1.start])
767  equalLength([line1, line2, line3, line4])
768}
769
770right = extrude(region(point = [3, 3], sketch = rightSketch), length = 8)
771
772toolSketch = sketch(on = XY) {
773  line1 = line(start = [var -1, var -1], end = [var 1, var -1])
774  line2 = line(start = [var 1, var -1], end = [var 1, var 1])
775  line3 = line(start = [var 1, var 1], end = [var -1, var 1])
776  line4 = line(start = [var -1, var 1], end = [var -1, var -1])
777  coincident([line1.end, line2.start])
778  coincident([line2.end, line3.start])
779  coincident([line3.end, line4.start])
780  coincident([line4.end, line1.start])
781  equalLength([line1, line2, line3, line4])
782}
783
784tool = extrude(region(point = [0, 0], sketch = toolSketch), length = 2)
785
786first = intersect([left, right])
787second = subtract(left, tools = [tool])
788"#;
789
790        let ctx = crate::ExecutorContext::new_mock(None).await;
791        let program = crate::Program::parse_no_errs(code).unwrap();
792        let err = ctx.run_mock(&program, &MockConfig::default()).await.unwrap_err();
793        ctx.close().await;
794
795        assert!(matches!(&err.error, KclError::Semantic { .. }), "{:?}", err.error);
796        let message = err.error.message();
797        assert!(
798            message.contains("`left` was already consumed by an `intersect` operation"),
799            "{message}"
800        );
801        assert!(
802            message.contains("The operation result is now in `first`; use that for subsequent operations"),
803            "{message}"
804        );
805    }
806
807    #[tokio::test(flavor = "multi_thread")]
808    async fn split_keep_tools_does_not_consume_tools() {
809        let code = r#"
810targetSketch = sketch(on = XY) {
811  line1 = line(start = [var -10, var -10], end = [var 10, var -10])
812  line2 = line(start = [var 10, var -10], end = [var 10, var 10])
813  line3 = line(start = [var 10, var 10], end = [var -10, var 10])
814  line4 = line(start = [var -10, var 10], end = [var -10, var -10])
815  coincident([line1.end, line2.start])
816  coincident([line2.end, line3.start])
817  coincident([line3.end, line4.start])
818  coincident([line4.end, line1.start])
819  equalLength([line1, line2, line3, line4])
820}
821
822target = extrude(region(point = [0, 0], sketch = targetSketch), length = 20)
823
824toolSketch = sketch(on = XY) {
825  line1 = line(start = [var -2, var -10], end = [var 2, var -10])
826  line2 = line(start = [var 2, var -10], end = [var 2, var 10])
827  line3 = line(start = [var 2, var 10], end = [var -2, var 10])
828  line4 = line(start = [var -2, var 10], end = [var -2, var -10])
829  coincident([line1.end, line2.start])
830  coincident([line2.end, line3.start])
831  coincident([line3.end, line4.start])
832  coincident([line4.end, line1.start])
833}
834
835tool = extrude(region(point = [0, 0], sketch = toolSketch), length = 20)
836
837first = split(target, tools = [tool], keepTools = true)
838second = subtract(first, tools = [tool])
839"#;
840
841        let ctx = crate::ExecutorContext::new_mock(None).await;
842        let program = crate::Program::parse_no_errs(code).unwrap();
843        let outcome = ctx.run_mock(&program, &MockConfig::default()).await.unwrap();
844        ctx.close().await;
845
846        assert!(outcome.variables.contains_key("second"));
847    }
848
849    #[tokio::test(flavor = "multi_thread")]
850    async fn split_without_keep_tools_consumes_tools() {
851        let code = r#"
852targetSketch = sketch(on = XY) {
853  line1 = line(start = [var -10, var -10], end = [var 10, var -10])
854  line2 = line(start = [var 10, var -10], end = [var 10, var 10])
855  line3 = line(start = [var 10, var 10], end = [var -10, var 10])
856  line4 = line(start = [var -10, var 10], end = [var -10, var -10])
857  coincident([line1.end, line2.start])
858  coincident([line2.end, line3.start])
859  coincident([line3.end, line4.start])
860  coincident([line4.end, line1.start])
861  equalLength([line1, line2, line3, line4])
862}
863
864target = extrude(region(point = [0, 0], sketch = targetSketch), length = 20)
865
866toolSketch = sketch(on = XY) {
867  line1 = line(start = [var -2, var -10], end = [var 2, var -10])
868  line2 = line(start = [var 2, var -10], end = [var 2, var 10])
869  line3 = line(start = [var 2, var 10], end = [var -2, var 10])
870  line4 = line(start = [var -2, var 10], end = [var -2, var -10])
871  coincident([line1.end, line2.start])
872  coincident([line2.end, line3.start])
873  coincident([line3.end, line4.start])
874  coincident([line4.end, line1.start])
875}
876
877tool = extrude(region(point = [0, 0], sketch = toolSketch), length = 20)
878
879first = split(target, tools = [tool])
880second = subtract(first, tools = [tool])
881"#;
882
883        let ctx = crate::ExecutorContext::new_mock(None).await;
884        let program = crate::Program::parse_no_errs(code).unwrap();
885        let err = ctx.run_mock(&program, &MockConfig::default()).await.unwrap_err();
886        ctx.close().await;
887
888        assert!(matches!(&err.error, KclError::Semantic { .. }), "{:?}", err.error);
889        let message = err.error.message();
890        assert!(
891            message.contains("`tool` was already consumed by a `split` operation"),
892            "{message}"
893        );
894        assert!(message.contains("can no longer be used"), "{message}");
895    }
896}