Skip to main content

kcl_lib/execution/
fn_call.rs

1use async_recursion::async_recursion;
2use indexmap::IndexMap;
3use kcl_api::Group;
4use kcl_api::OpArg;
5
6use crate::CompilationIssue;
7use crate::NodePath;
8use crate::NodePathExt;
9use crate::SourceRange;
10use crate::errors::KclError;
11use crate::errors::KclErrorDetails;
12use crate::execution::BodyType;
13use crate::execution::ExecState;
14use crate::execution::ExecutorContext;
15use crate::execution::Geometry;
16use crate::execution::KclValue;
17use crate::execution::KclValueControlFlow;
18use crate::execution::Metadata;
19use crate::execution::Solid;
20use crate::execution::StatementKind;
21use crate::execution::TagEngineInfo;
22use crate::execution::TagIdentifier;
23use crate::execution::annotations;
24use crate::execution::cad_op::Operation;
25use crate::execution::cad_op::op_from_kcl_value;
26use crate::execution::control_continue;
27use crate::execution::kcl_value::FunctionBody;
28use crate::execution::kcl_value::FunctionSource;
29use crate::execution::kcl_value::NamedParam;
30use crate::execution::memory;
31use crate::execution::types::CoercionMode;
32use crate::execution::types::RuntimeType;
33use crate::parsing::ast::types::CallExpressionKw;
34use crate::parsing::ast::types::Node;
35use crate::parsing::ast::types::Type;
36use crate::std::ConsumedSolidArgCheck;
37use crate::std::RegionBehavior;
38use crate::std::StaleRegionPolicy;
39use crate::std::region_consumption::PendingRegionConsumption;
40use crate::std::region_consumption::prepare_region_consumption;
41use crate::std::region_consumption::record_consumed_regions;
42use crate::std::region_consumption::validate_region_args_not_consumed;
43use crate::std::region_consumption::warn_if_region_args_consumed;
44use crate::std::solid_consumption::validate_value_not_consumed;
45use crate::std::solid_consumption::warn_if_value_consumed_for_deprecated_call;
46
47#[derive(Debug, Clone)]
48pub struct Args<Status: ArgsStatus = Desugared> {
49    /// Name of the function these args are being passed into.
50    pub fn_name: Option<String>,
51    /// Unlabeled keyword args. Currently only the first formal arg can be unlabeled.
52    /// If the argument was a local variable, then the first element of the tuple is its name
53    /// which may be used to treat this arg as a labelled arg.
54    pub unlabeled: Vec<(Option<String>, Arg)>,
55    /// Labeled args.
56    pub labeled: IndexMap<String, Arg>,
57    pub source_range: SourceRange,
58    pub node_path: Option<NodePath>,
59    pub ctx: ExecutorContext,
60    /// If this call happens inside a pipe (|>) expression, this holds the LHS of that |>.
61    /// Otherwise it's None.
62    pub pipe_value: Option<Arg>,
63    _status: std::marker::PhantomData<Status>,
64}
65
66pub trait ArgsStatus: std::fmt::Debug + Clone {}
67
68#[derive(Debug, Clone)]
69pub struct Sugary;
70impl ArgsStatus for Sugary {}
71
72// Invariants guaranteed by the `Desugared` status:
73// - There is either 0 or 1 unlabeled arguments
74// - Any lableled args are in the labeled map, and not the unlabeled Vec.
75// - The arguments match the type signature of the function exactly
76// - pipe_value.is_none()
77#[derive(Debug, Clone)]
78pub struct Desugared;
79impl ArgsStatus for Desugared {}
80
81impl Args<Sugary> {
82    /// Collect the given keyword arguments.
83    pub fn new(
84        labeled: IndexMap<String, Arg>,
85        unlabeled: Vec<(Option<String>, Arg)>,
86        source_range: SourceRange,
87        node_path: Option<NodePath>,
88        exec_state: &mut ExecState,
89        ctx: ExecutorContext,
90        fn_name: Option<String>,
91    ) -> Args<Sugary> {
92        Args {
93            fn_name,
94            labeled,
95            unlabeled,
96            source_range,
97            node_path,
98            ctx,
99            pipe_value: exec_state.pipe_value().map(|v| Arg::new(v.clone(), source_range)),
100            _status: std::marker::PhantomData,
101        }
102    }
103}
104
105impl<Status: ArgsStatus> Args<Status> {
106    /// How many arguments are there?
107    pub fn len(&self) -> usize {
108        self.labeled.len() + self.unlabeled.len()
109    }
110
111    /// Are there no arguments?
112    pub fn is_empty(&self) -> bool {
113        self.labeled.is_empty() && self.unlabeled.is_empty()
114    }
115}
116
117impl Args<Desugared> {
118    pub fn new_no_args(
119        source_range: SourceRange,
120        node_path: Option<NodePath>,
121        ctx: ExecutorContext,
122        fn_name: Option<String>,
123    ) -> Args {
124        Args {
125            fn_name,
126            unlabeled: Default::default(),
127            labeled: Default::default(),
128            source_range,
129            node_path,
130            ctx,
131            pipe_value: None,
132            _status: std::marker::PhantomData,
133        }
134    }
135
136    /// Get the unlabeled keyword argument. If not set, returns None.
137    pub(crate) fn unlabeled_kw_arg_unconverted(&self) -> Option<&Arg> {
138        self.unlabeled.first().map(|(_, a)| a)
139    }
140}
141
142#[derive(Debug, Clone)]
143pub struct Arg {
144    /// The evaluated argument.
145    pub value: KclValue,
146    /// The source range of the unevaluated argument.
147    pub source_range: SourceRange,
148}
149
150impl Arg {
151    pub fn new(value: KclValue, source_range: SourceRange) -> Self {
152        Self { value, source_range }
153    }
154
155    pub fn synthetic(value: KclValue) -> Self {
156        Self {
157            value,
158            source_range: SourceRange::synthetic(),
159        }
160    }
161
162    pub fn source_ranges(&self) -> Vec<SourceRange> {
163        vec![self.source_range]
164    }
165}
166
167impl Node<CallExpressionKw> {
168    #[async_recursion]
169    pub(super) async fn execute(
170        &self,
171        exec_state: &mut ExecState,
172        ctx: &ExecutorContext,
173    ) -> Result<KclValueControlFlow, KclError> {
174        let fn_name = &self.callee;
175        let callsite: SourceRange = self.into();
176
177        // Resolve the function before evaluating arguments so calls can mutate
178        // exec_state without holding a memory borrow.
179        let func: KclValue = fn_name.get_result(exec_state, ctx).await?;
180
181        let Some(fn_src) = func.as_function() else {
182            return Err(KclError::new_semantic(KclErrorDetails::new(
183                "cannot call this because it isn't a function".to_string(),
184                vec![callsite],
185            )));
186        };
187
188        // Build a hashmap from argument labels to the final evaluated values.
189        let mut fn_args = IndexMap::with_capacity(self.arguments.len());
190        let mut unlabeled = Vec::new();
191
192        // Evaluate the unlabeled first param, if any exists.
193        if let Some(ref arg_expr) = self.unlabeled {
194            let source_range = SourceRange::from(arg_expr.clone());
195            let metadata = Metadata { source_range };
196            let value_cf = ctx
197                .execute_expr(arg_expr, exec_state, &metadata, &[], StatementKind::Expression)
198                .await?;
199            let value = control_continue!(value_cf);
200
201            let label = arg_expr.ident_name().map(str::to_owned);
202
203            unlabeled.push((label, Arg::new(value, source_range)))
204        }
205
206        for arg_expr in &self.arguments {
207            let source_range = SourceRange::from(arg_expr.arg.clone());
208            let metadata = Metadata { source_range };
209            let value_cf = ctx
210                .execute_expr(&arg_expr.arg, exec_state, &metadata, &[], StatementKind::Expression)
211                .await?;
212            let value = control_continue!(value_cf);
213            let arg = Arg::new(value, source_range);
214            match &arg_expr.label {
215                Some(l) => {
216                    fn_args.insert(l.name.clone(), arg);
217                }
218                None => {
219                    unlabeled.push((arg_expr.arg.ident_name().map(str::to_owned), arg));
220                }
221            }
222        }
223
224        let args = Args::new(
225            fn_args,
226            unlabeled,
227            callsite,
228            self.node_path.clone(),
229            exec_state,
230            ctx.clone(),
231            Some(fn_name.name.name.clone()),
232        );
233
234        let return_value = fn_src
235            .call_kw(Some(fn_name.to_string()), exec_state, ctx, args, callsite)
236            .await
237            .map_err(|e| {
238                // Add the call expression to the source ranges.
239                //
240                // TODO: Use the name that the function was defined
241                // with, not the identifier it was used with.
242                e.add_unwind_location(Some(fn_name.to_string()), callsite)
243            })?;
244
245        let result = return_value.ok_or_else(move || {
246            let mut source_ranges: Vec<SourceRange> = vec![callsite];
247            // We want to send the source range of the original function.
248            if let KclValue::Function { meta, .. } = func {
249                source_ranges = meta.iter().map(|m| m.source_range).collect();
250            };
251            KclError::new_undefined_value(
252                KclErrorDetails::new(
253                    format!("Result of user-defined function {fn_name} is undefined"),
254                    source_ranges,
255                ),
256                None,
257            )
258        })?;
259
260        Ok(result)
261    }
262}
263
264/// Guidance included in deprecation warnings for sketch v1 stdlib functions.
265/// The warning must stand on its own: a human or AI agent reading it should
266/// learn what replaces the function and where to find conversion examples
267/// without any other context.
268const SKETCH_V1_MIGRATION_HELP: &str = "It is part of the legacy sketch API (sketch v1), which is replaced by the sketch-solve API.
269
270See https://zoo.dev/docs/kcl-book/sketch2d_constraints.html for an introduction to sketch-solve with examples.
271
272Draw profiles inside a `sketch(on = XY) { ... }` block using segment functions with absolute points, e.g. `line(start = [0, 0], end = [4, 3])`, optionally marking values as adjustable with `var` and constraining them with constraint functions like `coincident()` or `horizontal()`. ";
273
274/// Migration guidance for a deprecated stdlib function, when it has a
275/// dedicated replacement story beyond its docs page.
276fn migration_help(fn_src: &FunctionSource) -> Option<&'static str> {
277    let name = &fn_src.std_props.as_ref()?.name;
278    // Every deprecated function in std::sketch is part of sketch v1, which
279    // sketch-solve replaces in KCL 2.0.
280    name.starts_with("std::sketch::").then_some(SKETCH_V1_MIGRATION_HELP)
281}
282
283impl FunctionSource {
284    pub(crate) async fn call_kw(
285        &self,
286        fn_name: Option<String>,
287        exec_state: &mut ExecState,
288        ctx: &ExecutorContext,
289        args: Args<Sugary>,
290        callsite: SourceRange,
291    ) -> Result<Option<KclValueControlFlow>, KclError> {
292        exec_state.inc_call_stack_size(callsite)?;
293
294        let result = self.inner_call_kw(fn_name, exec_state, ctx, args, callsite).await;
295
296        exec_state.dec_call_stack_size(callsite)?;
297        result
298    }
299
300    async fn inner_call_kw(
301        &self,
302        fn_name: Option<String>,
303        exec_state: &mut ExecState,
304        ctx: &ExecutorContext,
305        args: Args<Sugary>,
306        callsite: SourceRange,
307    ) -> Result<Option<KclValueControlFlow>, KclError> {
308        let (state, args) = self.call_setup(&fn_name, exec_state, args, callsite)?;
309        // Do not early return via ? or something until we've called
310        // call_finish (or call_abort_on_arg_binding_failure), so that the
311        // ambient flags are restored and the callee env is popped.
312        let result = match &self.body {
313            FunctionBody::Rust(f) => f(exec_state, args).await.map(Some),
314            FunctionBody::Kcl(_) => {
315                if let Err(e) = assign_args_to_params_kw(self, args, exec_state) {
316                    return Err(Self::call_abort_on_arg_binding_failure(state, e, exec_state));
317                }
318
319                let block_result = ctx.exec_block(&self.ast.body, exec_state, BodyType::Block).await;
320                self.kcl_body_result(block_result, exec_state)
321            }
322        };
323        self.call_finish(state, result, exec_state)
324    }
325
326    /// The first half of a function call: warnings, argument type checking,
327    /// operation setup, pushing the callee environment, and stdlib
328    /// ambient-flag tracking. After this succeeds, the callee environment is
329    /// pushed and the ambient flags are set, so every path must reach
330    /// [`Self::call_finish`] (or [`Self::call_abort_on_arg_binding_failure`])
331    /// to balance them. The recursive executor keeps the returned [`CallState`]
332    /// across the body await; the machine executor parks it in a call-boundary
333    /// continuation.
334    pub(super) fn call_setup(
335        &self,
336        fn_name: &Option<String>,
337        exec_state: &mut ExecState,
338        args: Args<Sugary>,
339        callsite: SourceRange,
340    ) -> Result<(CallState, Args), KclError> {
341        // The KCL stdlib is allowed to use deprecated sketch1 functions inside.
342        let warn_on_deprecated_usage = !exec_state.mod_local.inside_stdlib;
343        if warn_on_deprecated_usage {
344            let subject = match &fn_name {
345                Some(n) => format!("`{n}`"),
346                None => "This function".to_owned(),
347            };
348            let message = if self.deprecated {
349                Some(match migration_help(self) {
350                    Some(help) => format!("{subject} is deprecated. {help}"),
351                    None => format!("{subject} is deprecated, see the docs for a recommended replacement"),
352                })
353            } else if let Some(since) = &self.deprecated_since
354                && annotations::version_ge(exec_state.deprecation_version(), since)
355            {
356                Some(match migration_help(self) {
357                    Some(help) => format!("{subject} is deprecated as of KCL {since}. {help}"),
358                    None => {
359                        format!(
360                            "{subject} is deprecated as of KCL {since}. See the docs for a recommended replacement."
361                        )
362                    }
363                })
364            } else {
365                None
366            };
367            if let Some(message) = message {
368                let mut issue = CompilationIssue::err(callsite, message);
369                issue.tag = crate::errors::Tag::Deprecated;
370                exec_state.warn(issue, annotations::WARN_DEPRECATED);
371            }
372        }
373        if self.experimental {
374            exec_state.warn_experimental(
375                &match &fn_name {
376                    Some(n) => format!("`{n}`"),
377                    None => "This function".to_owned(),
378                },
379                callsite,
380            );
381        }
382
383        let args = type_check_params_kw(fn_name.as_deref(), self, args, exec_state)?;
384        let face_tag_names = face_tag_names_for_call(self, &args);
385        let pending_region_consumption = prepare_region_consumption(
386            self.std_props
387                .as_ref()
388                .map_or(RegionBehavior::WarnOnConsumed, |props| props.region_behavior),
389            &args,
390            exec_state,
391        )?;
392
393        // Warn if experimental or deprecated arguments are used after desugaring.
394        for (label, arg) in &args.labeled {
395            let Some(param) = self.named_args.get(label.as_str()) else {
396                continue;
397            };
398            if param.experimental {
399                exec_state.warn_experimental(
400                    &match &fn_name {
401                        Some(f) => format!("`{f}({label})`"),
402                        None => label.to_owned(),
403                    },
404                    arg.source_range,
405                );
406            }
407            // `deprecated` deprecates the parameter for all versions, whereas
408            // `deprecated_since` only deprecates it at or after a given version.
409            let deprecation_suffix = if !warn_on_deprecated_usage {
410                None
411            } else if param.deprecated {
412                Some("is deprecated, see the docs for a recommended replacement".to_owned())
413            } else if let Some(since) = &param.deprecated_since
414                && annotations::version_ge(exec_state.deprecation_version(), since)
415            {
416                Some(format!(
417                    "is deprecated as of KCL {since}. See the docs for a recommended replacement."
418                ))
419            } else {
420                None
421            };
422            if let Some(suffix) = deprecation_suffix {
423                let qualified = match &fn_name {
424                    Some(f) => format!("`{f}({label})`"),
425                    None => format!("`{label}`"),
426                };
427                let mut issue = CompilationIssue::err(arg.source_range, format!("{qualified} {suffix}"));
428                issue.tag = crate::errors::Tag::Deprecated;
429                exec_state.warn(issue, annotations::WARN_DEPRECATED);
430            }
431        }
432
433        // Don't early return until the stack frame is popped!
434        self.body.prep_mem(exec_state)?;
435
436        // Some function calls might get added to the feature tree.
437        // We do this by adding an "operation".
438
439        // Don't add operations if the KCL code being executed is
440        // just the KCL stdlib calling other KCL stdlib,
441        // because the stdlib internals aren't relevant to users,
442        // that would just be pointless noise.
443        //
444        // Do add operations if the KCL being executed is
445        // user-defined, or the calling code is user-defined,
446        // because that's relevant to the user.
447        let would_trace_stdlib_internals = exec_state.mod_local.inside_stdlib && self.is_std();
448        // self.include_in_feature_tree is set by the KCL annotation `@(feature_tree = true)`.
449        let should_track_operation = !would_trace_stdlib_internals && self.include_in_feature_tree;
450        let op = if should_track_operation {
451            let op_labeled_args = args
452                .labeled
453                .iter()
454                .map(|(k, arg)| (k.clone(), OpArg::new(op_from_kcl_value(&arg.value), arg.source_range)))
455                .collect();
456
457            // If you're calling a stdlib function, track that call as an operation.
458            if self.is_std() {
459                Some(Operation::StdLibCall {
460                    name: fn_name.clone().unwrap_or_else(|| "unknown function".to_owned()),
461                    unlabeled_arg: args
462                        .unlabeled_kw_arg_unconverted()
463                        .map(|arg| OpArg::new(op_from_kcl_value(&arg.value), arg.source_range)),
464                    labeled_args: op_labeled_args,
465                    node_path: NodePath::placeholder(),
466                    source_range: callsite,
467                    stdlib_entry_source_range: exec_state.mod_local.stdlib_entry_source_range,
468                    is_error: false,
469                })
470            } else {
471                // Otherwise, you're calling a user-defined function, track that call as an operation.
472                exec_state.push_op(Operation::GroupBegin {
473                    group: Group::FunctionCall {
474                        name: fn_name.clone(),
475                        function_source_range: self.ast.as_source_range(),
476                        unlabeled_arg: args
477                            .unlabeled_kw_arg_unconverted()
478                            .map(|arg| OpArg::new(op_from_kcl_value(&arg.value), arg.source_range)),
479                        labeled_args: op_labeled_args,
480                    },
481                    node_path: NodePath::placeholder(),
482                    source_range: callsite,
483                });
484
485                None
486            }
487        } else {
488            None
489        };
490
491        let is_calling_into_stdlib = match &self.body {
492            FunctionBody::Rust(_) => true,
493            FunctionBody::Kcl(_) => self.is_std(),
494        };
495        let is_crossing_into_stdlib = is_calling_into_stdlib && !exec_state.mod_local.inside_stdlib;
496        let is_crossing_out_of_stdlib = !is_calling_into_stdlib && exec_state.mod_local.inside_stdlib;
497        let stdlib_entry_source_range = if is_crossing_into_stdlib {
498            // When we're calling into the stdlib, for example calling hole(),
499            // track the location so that any further stdlib calls like
500            // subtract() can point to the hole() call. The frontend needs this.
501            Some(callsite)
502        } else if is_crossing_out_of_stdlib {
503            // When map() calls a user-defined function, and it calls extrude()
504            // for example, we want it to point the the extrude() call, not
505            // the map() call.
506            None
507        } else {
508            // When we're not crossing the stdlib boundary, keep the previous
509            // value.
510            exec_state.mod_local.stdlib_entry_source_range
511        };
512
513        let prev_inside_stdlib = std::mem::replace(&mut exec_state.mod_local.inside_stdlib, is_calling_into_stdlib);
514        let prev_stdlib_entry_source_range = std::mem::replace(
515            &mut exec_state.mod_local.stdlib_entry_source_range,
516            stdlib_entry_source_range,
517        );
518
519        Ok((
520            CallState {
521                prev_inside_stdlib,
522                prev_stdlib_entry_source_range,
523                op,
524                should_track_operation,
525                is_calling_into_stdlib,
526                face_tag_names,
527                pending_region_consumption,
528            },
529            args,
530        ))
531    }
532
533    /// Compute a KCL function body's result while the callee environment is
534    /// still pushed: an `Exit` or `Return` passes through untouched;
535    /// otherwise the function's result is the `__return` value recorded in
536    /// the callee environment, if any.
537    ///
538    /// NOTE: under a pre-KCL-3.0 entry point, a `return` statement does NOT
539    /// stop the body -- it records `__return` and execution continues to the
540    /// following statements (see exec_block's ReturnStatement arm). The block's
541    /// own trailing value is deliberately ignored here; only `__return` counts.
542    /// Under KCL 3.0, `return` stops the body and arrives here as a `Return`
543    /// control flow instead; `__return` is never written.
544    pub(super) fn kcl_body_result(
545        &self,
546        block_result: Result<Option<KclValueControlFlow>, KclError>,
547        exec_state: &mut ExecState,
548    ) -> Result<Option<KclValueControlFlow>, KclError> {
549        block_result.map(|cf| {
550            if let Some(cf) = cf
551                && cf.is_some_return()
552            {
553                return Some(cf);
554            }
555            // Ignore the block's value and extract the return value
556            // from memory.
557            exec_state
558                .stack()
559                .get(memory::RETURN_NAME, self.ast.as_source_range())
560                .ok()
561                .map(KclValue::continue_)
562        })
563    }
564
565    /// The failure path when binding a KCL function's arguments fails, before
566    /// the body ran: restore `inside_stdlib` and pop the callee environment.
567    /// Deliberately asymmetric with [`Self::call_finish`] -- it does not
568    /// restore `stdlib_entry_source_range` and does not finalize the
569    /// operation -- preserving the recursive executor's historical behavior
570    /// exactly.
571    pub(super) fn call_abort_on_arg_binding_failure(
572        state: CallState,
573        e: KclError,
574        exec_state: &mut ExecState,
575    ) -> KclError {
576        exec_state.mod_local.inside_stdlib = state.prev_inside_stdlib;
577        match exec_state.mut_stack().pop_env() {
578            Ok(_) => e,
579            Err(pop_err) => pop_err,
580        }
581    }
582
583    /// The second half of a function call: restore the ambient stdlib flags,
584    /// pop the callee environment, finalize the operation, and then -- for
585    /// normal completions only -- apply tag updates and return-type coercion.
586    /// `Exit` control flow bypasses tags and coercion (it terminates the whole
587    /// evaluation rather than completing this function normally), and errors
588    /// skip them too; both still restore ambient state and finalize the
589    /// operation. `Return` control flow (a KCL 3.0 early return) is absorbed
590    /// here: it completes this function normally, so tags and coercion apply to
591    /// it exactly as they do to a `__return` value.
592    pub(super) fn call_finish(
593        &self,
594        state: CallState,
595        result: Result<Option<KclValueControlFlow>, KclError>,
596        exec_state: &mut ExecState,
597    ) -> Result<Option<KclValueControlFlow>, KclError> {
598        let CallState {
599            prev_inside_stdlib,
600            prev_stdlib_entry_source_range,
601            op,
602            should_track_operation,
603            is_calling_into_stdlib,
604            face_tag_names,
605            pending_region_consumption,
606        } = state;
607        exec_state.mod_local.inside_stdlib = prev_inside_stdlib;
608        exec_state.mod_local.stdlib_entry_source_range = prev_stdlib_entry_source_range;
609        exec_state.mut_stack().pop_env()?;
610
611        if result.is_ok()
612            && let Some(pending_region_consumption) = pending_region_consumption
613        {
614            record_consumed_regions(exec_state, pending_region_consumption);
615        }
616
617        if should_track_operation {
618            if let Some(mut op) = op {
619                op.set_std_lib_call_is_error(result.is_err());
620                // Track call operation.  We do this after the call
621                // since things like patternTransform may call user code
622                // before running, and we will likely want to use the
623                // return value. The call takes ownership of the args,
624                // so we need to build the op before the call.
625                exec_state.push_op(op);
626            } else if !is_calling_into_stdlib {
627                exec_state.push_op(Operation::GroupEnd);
628            }
629        }
630
631        let mut result = match result {
632            Ok(Some(value)) => {
633                if value.is_exit() {
634                    // `Exit` terminates the whole evaluation rather than completing this
635                    // function normally, so it bypasses return-type validation, including
636                    // the `never` contract.
637                    return Ok(Some(value));
638                } else {
639                    // `Continue` and `Return` both complete this function
640                    // normally.
641                    Ok(Some(value.into_value()))
642                }
643            }
644            Ok(None) => Ok(None),
645            Err(e) => Err(e),
646        };
647
648        if self.is_std()
649            && let Ok(Some(result)) = &mut result
650        {
651            update_memory_for_tags_of_geometry(result, exec_state)?;
652            if !face_tag_names.is_empty() {
653                attach_face_tags_to_geometry(result, exec_state, &face_tag_names);
654            }
655        }
656
657        coerce_result_type(result, self, exec_state).map(|r| r.map(KclValue::continue_))
658    }
659}
660
661/// State captured by [`FunctionSource::call_setup`] that
662/// [`FunctionSource::call_finish`] needs to complete the call: the ambient
663/// flags to restore, the deferred operation, and details of what was called.
664#[derive(Debug)]
665pub(super) struct CallState {
666    prev_inside_stdlib: bool,
667    prev_stdlib_entry_source_range: Option<SourceRange>,
668    /// Deferred stdlib-call operation, pushed by call_finish.
669    op: Option<Operation>,
670    should_track_operation: bool,
671    is_calling_into_stdlib: bool,
672    face_tag_names: Vec<String>,
673    pending_region_consumption: Option<PendingRegionConsumption>,
674}
675
676impl FunctionBody {
677    fn prep_mem(&self, exec_state: &mut ExecState) -> Result<(), KclError> {
678        match self {
679            FunctionBody::Rust(_) => exec_state.mut_stack().push_new_root_env(true),
680            FunctionBody::Kcl(memory) => exec_state.mut_stack().push_new_env_for_call(*memory),
681        }
682    }
683}
684
685/// Whether `value` may have come from a legacy (v1) sketch rather than a
686/// sketch block, which is what gates the legacy tag-memory updates in
687/// `update_memory_for_tags_of_geometry`.
688///
689/// Anything that is not a sketch or a solid answers `false`: a number or an
690/// enum variant is not a sketch of either generation, so it must not pull in
691/// legacy behavior. The match stays exhaustive so that adding a `KclValue`
692/// variant forces an explicit answer here instead of inheriting one.
693fn might_be_legacy_sketch(value: &KclValue) -> bool {
694    match value {
695        KclValue::Uuid { .. } => false,
696        KclValue::Bool { .. } => false,
697        KclValue::Number { .. } => false,
698        KclValue::String { .. } => false,
699        KclValue::Enum { .. } => false,
700        KclValue::SketchVar { .. } => false,
701        KclValue::SketchConstraint { .. } => false,
702        KclValue::Tuple { value, .. } => value.iter().any(might_be_legacy_sketch),
703        KclValue::HomArray { value, .. } => value.iter().any(might_be_legacy_sketch),
704        // TODO: sketch block result should return false.
705        KclValue::Object { value, .. } => value.values().any(might_be_legacy_sketch),
706        KclValue::TagIdentifier(_) => false,
707        KclValue::TagDeclarator(_) => false,
708        KclValue::GdtAnnotation { .. } => false,
709        KclValue::CameraView { .. } => false,
710        KclValue::NamedView { .. } => false,
711        KclValue::Plane { .. } => false,
712        KclValue::Face { .. } => false,
713        KclValue::BoundedEdge { .. } => false,
714        KclValue::Segment { .. } => false,
715        KclValue::Sketch { value: sketch } => sketch.origin_sketch_id.is_none(),
716        // A solid with no sketch has no tag container, so the caller returns
717        // early without consulting this answer; `true` keeps it the exact
718        // negation of the previous `originates_from_sketch_block`.
719        KclValue::Solid { value: solid } => solid
720            .sketch()
721            .map(|sketch| sketch.origin_sketch_id.is_none())
722            .unwrap_or(true),
723        KclValue::Helix { .. } => false,
724        KclValue::ImportedGeometry(_) => false,
725        KclValue::Function { .. } => false,
726        KclValue::Module { .. } => false,
727        KclValue::Type { .. } => false,
728        KclValue::KclNone { .. } => false,
729    }
730}
731
732fn face_tag_names_for_call(fn_def: &FunctionSource, args: &Args<Desugared>) -> Vec<String> {
733    let Some(std_props) = &fn_def.std_props else {
734        return Vec::new();
735    };
736
737    if !std_function_allows_face_tags(&std_props.name) {
738        return Vec::new();
739    }
740
741    args.labeled
742        .iter()
743        .filter(|(label, _)| matches!(label.as_str(), "tag" | "tagStart" | "tagEnd"))
744        .filter_map(|(_, arg)| match &arg.value {
745            KclValue::TagDeclarator(tag) => Some(tag.name.clone()),
746            _ => None,
747        })
748        .collect()
749}
750
751fn std_function_allows_face_tags(std_fn_name: &str) -> bool {
752    matches!(
753        std_fn_name,
754        "std::sketch::extrude"
755            | "std::solid::chamfer"
756            | "std::solid::fillet"
757            | "std::sketch::sweep"
758            | "std::sketch::loft"
759            | "std::sketch::revolve"
760    )
761}
762
763fn attach_face_tags_to_geometry(result: &mut KclValue, exec_state: &ExecState, tag_names: &[String]) {
764    match result {
765        KclValue::Solid { value } => attach_face_tags_to_solid(value, exec_state, tag_names),
766        KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
767            for v in value {
768                attach_face_tags_to_geometry(v, exec_state, tag_names);
769            }
770        }
771        _ => {}
772    }
773}
774
775fn attach_face_tags_to_solid(solid: &mut Solid, exec_state: &ExecState, tag_names: &[String]) {
776    let surfaces = solid.value.clone();
777    for surface in surfaces {
778        let Some(tag) = surface.get_tag() else {
779            continue;
780        };
781        if !tag_names.iter().any(|tag_name| tag_name == &tag.name) {
782            continue;
783        }
784
785        let tag_id = solid
786            .sketch()
787            .and_then(|sketch| sketch.tags.get(&tag.name))
788            .cloned()
789            .unwrap_or_else(|| {
790                let mut solid_copy = solid.clone();
791                clear_tags_from_solid_copy(&mut solid_copy);
792                TagIdentifier {
793                    value: tag.name.clone(),
794                    info: vec![(
795                        exec_state.stack().current_epoch(),
796                        TagEngineInfo {
797                            id: surface.get_id(),
798                            surface: Some(surface.clone()),
799                            path: None,
800                            geometry: Geometry::Solid(solid_copy),
801                        },
802                    )],
803                    meta: vec![Metadata {
804                        source_range: tag.clone().into(),
805                    }],
806                }
807            });
808
809        match solid.faces.get_mut(&tag.name) {
810            Some(existing_tag) => existing_tag.merge_info(&tag_id),
811            None => {
812                solid.faces.insert(tag.name.clone(), tag_id);
813            }
814        }
815    }
816}
817
818fn clear_tags_from_solid_copy(solid: &mut Solid) {
819    if let Some(sketch) = solid.sketch_mut() {
820        sketch.tags.clear(); // Avoid recursive tags.
821    }
822    solid.faces.clear();
823}
824
825fn update_memory_for_tags_of_geometry(result: &mut KclValue, exec_state: &mut ExecState) -> Result<(), KclError> {
826    let might_be_legacy = might_be_legacy_sketch(&*result);
827    // If the return result is a sketch or solid, we want to update the
828    // memory for the tags of the group.
829    // TODO: This could probably be done in a better way, but as of now this was my only idea
830    // and it works.
831    match result {
832        KclValue::Sketch { value } if might_be_legacy => {
833            for (name, tag) in value.tags.iter() {
834                if exec_state.stack().cur_frame_contains(name)? {
835                    exec_state.mut_stack().update(name, |v, _| {
836                        if let Some(existing_tag) = v.as_mut_tag() {
837                            existing_tag.merge_info(tag);
838                        }
839                    })?;
840                } else {
841                    exec_state.mut_stack().add(
842                        name.to_owned(),
843                        KclValue::TagIdentifier(Box::new(tag.clone())),
844                        SourceRange::default(),
845                    )?;
846                }
847            }
848        }
849        KclValue::Solid { value } => {
850            let surfaces = value.value.clone();
851            if value.sketch_mut().is_none() {
852                // If the solid isn't based on a sketch, then it doesn't have a tag container,
853                // so there's nothing to do here.
854                return Ok(());
855            };
856            // Now that we know there's work to do (because there's a tag container),
857            // run some clones.
858            let solid_copies: Vec<Box<Solid>> = surfaces.iter().map(|_| value.clone()).collect();
859            // Get the tag container. We expect it to always succeed because we already checked
860            // for a tag container above.
861            let Some(sketch) = value.sketch_mut() else {
862                return Ok(());
863            };
864            for (v, mut solid_copy) in surfaces.iter().zip(solid_copies) {
865                clear_tags_from_solid_copy(&mut solid_copy);
866                if let Some(tag) = v.get_tag() {
867                    // Get the past tag and update it.
868                    let mut is_part_of_sketch = false;
869                    let tag_id = if let Some(t) = sketch.tags.get(&tag.name) {
870                        is_part_of_sketch = true;
871                        let mut t = t.clone();
872                        let Some(info) = t.get_cur_info() else {
873                            return Err(KclError::new_internal(KclErrorDetails::new(
874                                format!("Tag {} does not have path info", tag.name),
875                                vec![tag.into()],
876                            )));
877                        };
878
879                        let mut info = info.clone();
880                        info.id = v.get_id();
881                        info.surface = Some(v.clone());
882                        info.geometry = Geometry::Solid(*solid_copy);
883                        t.info.push((exec_state.stack().current_epoch(), info));
884                        t
885                    } else {
886                        // It's probably a fillet or a chamfer.
887                        // Initialize it.
888                        TagIdentifier {
889                            value: tag.name.clone(),
890                            info: vec![(
891                                exec_state.stack().current_epoch(),
892                                TagEngineInfo {
893                                    id: v.get_id(),
894                                    surface: Some(v.clone()),
895                                    path: None,
896                                    geometry: Geometry::Solid(*solid_copy),
897                                },
898                            )],
899                            meta: vec![Metadata {
900                                source_range: tag.clone().into(),
901                            }],
902                        }
903                    };
904
905                    // update the sketch tags.
906                    sketch.merge_tags(Some(&tag_id).into_iter());
907
908                    if exec_state.stack().cur_frame_contains(&tag.name)? {
909                        exec_state.mut_stack().update(&tag.name, |v, _| {
910                            if let Some(existing_tag) = v.as_mut_tag() {
911                                existing_tag.merge_info(&tag_id);
912                            }
913                        })?;
914                    } else if might_be_legacy || !is_part_of_sketch {
915                        // The above condition is saying that we add a tag to
916                        // the stack in either of these cases:
917                        //
918                        // 1. It originates from a legacy sketch v1.
919                        //
920                        // 2. It originates from a sketch block and it's not
921                        // part of the sketch. Instead, it's part of the solid,
922                        // as in tagging a cap face `extrude(tagEnd, tagStart)`
923                        // or chamfer face `chamfer(tag)`.
924                        exec_state.mut_stack().add(
925                            tag.name.clone(),
926                            KclValue::TagIdentifier(Box::new(tag_id)),
927                            SourceRange::default(),
928                        )?;
929                    }
930                }
931            }
932
933            // Find the stale sketch in memory and update it.
934            if let Some(sketch) = value.sketch() {
935                if sketch.tags.is_empty() {
936                    return Ok(());
937                }
938                let sketch_tags: Vec<_> = sketch.tags.values().cloned().collect();
939                let sketches_to_update: Vec<_> = exec_state.stack().find_keys_in_current_env(|v| match v {
940                    KclValue::Sketch { value: sk } => sk.original_id == sketch.original_id,
941                    _ => false,
942                })?;
943
944                for k in sketches_to_update {
945                    exec_state.mut_stack().update(&k, |v, _| {
946                        if let Some(sketch) = v.as_mut_sketch() {
947                            sketch.merge_tags(sketch_tags.iter());
948                        }
949                    })?;
950                }
951            }
952        }
953        KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
954            for v in value {
955                update_memory_for_tags_of_geometry(v, exec_state)?;
956            }
957        }
958        _ => {}
959    }
960    Ok(())
961}
962
963fn type_err_str(expected: &Type, found: &KclValue, source_range: &SourceRange, exec_state: &mut ExecState) -> String {
964    fn strip_backticks(s: &str) -> &str {
965        let mut result = s;
966        if s.starts_with('`') {
967            result = &result[1..]
968        }
969        if s.ends_with('`') {
970            result = &result[..result.len() - 1]
971        }
972        result
973    }
974
975    let expected_human = expected.human_friendly_type();
976    let expected_ty = expected.to_string();
977    let expected_str =
978        if expected_human == expected_ty || expected_human == format!("a value with type `{expected_ty}`") {
979            format!("a value with type `{expected_ty}`")
980        } else {
981            format!("{expected_human} (`{expected_ty}`)")
982        };
983    let found_human = found.human_friendly_type();
984    let found_ty = found.principal_type_string();
985    let found_str = if found_human == found_ty || found_human == format!("a {}", strip_backticks(&found_ty)) {
986        format!("a value with type {found_ty}")
987    } else {
988        format!("{found_human} (with type {found_ty})")
989    };
990
991    let mut result = format!("{expected_str}, but found {found_str}.");
992
993    if found.is_unknown_number() {
994        exec_state.clear_units_warnings(source_range);
995        result.push_str("\nThe found value is a number but has incomplete units information. You can probably fix this error by specifying the units using type ascription, e.g., `len: mm` or `(a * b): deg`.");
996    }
997
998    result
999}
1000
1001/// Build the error message for a labeled argument whose label doesn't match any
1002/// parameter of the callee. Shared between keyword function calls and sketch
1003/// blocks so the wording stays consistent.
1004pub(crate) fn unexpected_kw_arg_message(label: &str, callee_name: Option<&str>) -> String {
1005    format!(
1006        "`{label}` is not an argument of {}",
1007        callee_name
1008            .map(|n| format!("`{n}`"))
1009            .unwrap_or_else(|| "this function".to_owned()),
1010    )
1011}
1012
1013/// Fetch the definition-time resolution of a type written in a function
1014/// signature.
1015///
1016/// [`FunctionSource::resolve_signature_types`] runs whenever a function
1017/// declaration executes, so a written type without a stored resolution is a
1018/// bug in KCL, not in the user's program.
1019fn resolved_signature_type<'a>(
1020    resolved: Option<&'a RuntimeType>,
1021    written: &Type,
1022    source_range: SourceRange,
1023) -> Result<&'a RuntimeType, KclError> {
1024    resolved.ok_or_else(|| {
1025        KclError::new_internal(KclErrorDetails::new(
1026            format!(
1027                "The type `{written}` in this function's signature was not resolved when the function was declared. This is a bug in KCL and not in your code, please report this to Zoo."
1028            ),
1029            vec![source_range],
1030        ))
1031    })
1032}
1033
1034fn type_check_params_kw(
1035    fn_name: Option<&str>,
1036    fn_def: &FunctionSource,
1037    mut args: Args<Sugary>,
1038    exec_state: &mut ExecState,
1039) -> Result<Args<Desugared>, KclError> {
1040    let fn_name = fn_name.or(args.fn_name.as_deref());
1041    let mut result = Args::new_no_args(
1042        args.source_range,
1043        args.node_path.clone(),
1044        args.ctx,
1045        fn_name.map(|f| f.to_string()).or_else(|| args.fn_name.clone()),
1046    );
1047
1048    // If it's possible the input arg was meant to be labelled and we probably don't want to use
1049    // it as the input arg, then treat it as labelled.
1050    if let Some((Some(label), _)) = args.unlabeled.first()
1051        && args.unlabeled.len() == 1
1052        && (fn_def.input_arg.is_none() || args.pipe_value.is_some())
1053        && fn_def.named_args.iter().any(|p| p.0 == label)
1054        && !args.labeled.contains_key(label)
1055    {
1056        let Some((label, arg)) = args.unlabeled.pop() else {
1057            let message = "Expected unlabeled arg to be present".to_owned();
1058            debug_assert!(false, "{}", &message);
1059            return Err(KclError::new_internal(KclErrorDetails::new(
1060                message,
1061                vec![args.source_range],
1062            )));
1063        };
1064        args.labeled.insert(label.unwrap(), arg);
1065    }
1066
1067    // Apply the `a == a: a` shorthand by desugaring unlabeled args into labeled ones.
1068    let (labeled_unlabeled, unlabeled_unlabeled) = args.unlabeled.into_iter().partition(|(l, _)| {
1069        if let Some(l) = l
1070            && fn_def.named_args.contains_key(l)
1071            && !args.labeled.contains_key(l)
1072        {
1073            true
1074        } else {
1075            false
1076        }
1077    });
1078    args.unlabeled = unlabeled_unlabeled;
1079    for (l, arg) in labeled_unlabeled {
1080        let previous = args.labeled.insert(l.unwrap(), arg);
1081        debug_assert!(previous.is_none());
1082    }
1083
1084    if let Some((name, ty)) = &fn_def.input_arg {
1085        // Expecting an input arg
1086
1087        if args.unlabeled.is_empty() {
1088            // No args provided
1089
1090            if let Some(pipe) = args.pipe_value {
1091                // But there is a pipeline
1092                result.unlabeled = vec![(None, pipe)];
1093            } else if let Some(arg) = args.labeled.swap_remove(name) {
1094                // Mistakenly labelled
1095                exec_state.err(CompilationIssue::err(
1096                    arg.source_range,
1097                    format!(
1098                        "{} expects an unlabeled first argument (`@{name}`), but it is labelled in the call. You might try removing the `{name} = `",
1099                        fn_name
1100                            .map(|n| format!("The function `{n}`"))
1101                            .unwrap_or_else(|| "This function".to_owned()),
1102                    ),
1103                ));
1104                result.unlabeled = vec![(Some(name.clone()), arg)];
1105            } else {
1106                // Just missing
1107                return Err(KclError::new_argument(KclErrorDetails::new(
1108                    "This function expects an unlabeled first parameter, but you haven't passed it one.".to_owned(),
1109                    fn_def.ast.as_source_ranges(),
1110                )));
1111            }
1112        } else if args.unlabeled.len() == 1
1113            && let Some(unlabeled_arg) = args.unlabeled.pop()
1114        {
1115            let mut arg = unlabeled_arg.1;
1116            if let Some(ty) = ty {
1117                let rty = resolved_signature_type(fn_def.resolved_input_ty.as_ref(), ty, arg.source_range)?;
1118                arg.value = arg
1119                    .value
1120                    .coerce(rty, CoercionMode::implicit(), exec_state)
1121                    .map_err(|_| {
1122                        KclError::new_argument(KclErrorDetails::new(
1123                            format!(
1124                                "The input argument of {} requires {}",
1125                                fn_name
1126                                    .map(|n| format!("`{n}`"))
1127                                    .unwrap_or_else(|| "this function".to_owned()),
1128                                type_err_str(ty, &arg.value, &arg.source_range, exec_state),
1129                            ),
1130                            vec![arg.source_range],
1131                        ))
1132                    })?;
1133            }
1134            result.unlabeled = vec![(None, arg)]
1135        } else {
1136            // Multiple unlabelled args
1137
1138            // Try to un-spread args into an array
1139            if let Some(Type::Array { len, .. }) = ty {
1140                if len.satisfied(args.unlabeled.len(), false).is_none() {
1141                    exec_state.err(CompilationIssue::err(
1142                        args.source_range,
1143                        format!(
1144                            "{} expects an array input argument with {} elements",
1145                            fn_name
1146                                .map(|n| format!("The function `{n}`"))
1147                                .unwrap_or_else(|| "This function".to_owned()),
1148                            len.human_friendly_type(),
1149                        ),
1150                    ));
1151                }
1152
1153                let source_range = SourceRange::merge(args.unlabeled.iter().map(|(_, a)| a.source_range));
1154                exec_state.warn_experimental("array input arguments", source_range);
1155                result.unlabeled = vec![(
1156                    None,
1157                    Arg {
1158                        source_range,
1159                        value: KclValue::HomArray {
1160                            value: args.unlabeled.drain(..).map(|(_, a)| a.value).collect(),
1161                            ty: RuntimeType::any(),
1162                        },
1163                    },
1164                )]
1165            }
1166        }
1167    }
1168
1169    // Either we didn't move the arg above, or we're not expecting one.
1170    if !args.unlabeled.is_empty() {
1171        // Not expecting an input arg, but found one or more
1172        let actuals = args.labeled.keys();
1173        let formals: Vec<_> = fn_def
1174            .named_args
1175            .keys()
1176            .filter_map(|name| {
1177                if actuals.clone().any(|a| a == name) {
1178                    return None;
1179                }
1180
1181                Some(format!("`{name}`"))
1182            })
1183            .collect();
1184
1185        let suggestion = if formals.is_empty() {
1186            String::new()
1187        } else {
1188            format!("; suggested labels: {}", formals.join(", "))
1189        };
1190
1191        let mut errors = args.unlabeled.iter().map(|(_, arg)| {
1192            CompilationIssue::err(
1193                arg.source_range,
1194                format!("This argument needs a label, but it doesn't have one{suggestion}"),
1195            )
1196        });
1197
1198        let first = errors.next().unwrap();
1199        errors.for_each(|e| exec_state.err(e));
1200
1201        return Err(KclError::new_argument(first.into()));
1202    }
1203
1204    for (label, mut arg) in args.labeled {
1205        match fn_def.named_args.get(&label) {
1206            Some(NamedParam {
1207                experimental: _,
1208                deprecated: _,
1209                deprecated_since: _,
1210                default_value: def,
1211                ty,
1212                resolved_ty,
1213            }) => {
1214                // For optional args, passing None should be the same as not passing an arg.
1215                if !(def.is_some() && matches!(arg.value, KclValue::KclNone { .. })) {
1216                    if let Some(ty) = ty {
1217                        let rty = resolved_signature_type(resolved_ty.as_ref(), ty, arg.source_range)?;
1218                        arg.value = arg
1219                                .value
1220                                .coerce(
1221                                    rty,
1222                                    CoercionMode::implicit(),
1223                                    exec_state,
1224                                )
1225                                .map_err(|e| {
1226                                    let mut message = format!(
1227                                        "{label} requires {}",
1228                                        type_err_str(ty, &arg.value, &arg.source_range, exec_state),
1229                                    );
1230                                    if let Some(ty) = e.explicit_coercion {
1231                                        // TODO if we have access to the AST for the argument we could choose which example to suggest.
1232                                        message = format!("{message}\n\nYou may need to add information about the type of the argument, for example:\n  using a numeric suffix: `42{ty}`\n  or using type ascription: `foo(): {ty}`");
1233                                    }
1234                                    KclError::new_argument(KclErrorDetails::new(
1235                                        message,
1236                                        vec![arg.source_range],
1237                                    ))
1238                                })?;
1239                    }
1240                    result.labeled.insert(label, arg);
1241                }
1242            }
1243            None => {
1244                exec_state.err(CompilationIssue::err(
1245                    arg.source_range,
1246                    unexpected_kw_arg_message(&label, fn_name),
1247                ));
1248            }
1249        }
1250    }
1251
1252    let consumed_solid_arg_check = fn_def
1253        .std_props
1254        .as_ref()
1255        .map_or(ConsumedSolidArgCheck::Error, |props| props.consumed_solid_arg_check);
1256    if matches!(fn_def.body, FunctionBody::Rust(_))
1257        && let Some(props) = fn_def.std_props.as_ref()
1258    {
1259        match props.region_behavior.stale_region_policy() {
1260            Some(StaleRegionPolicy::Error) => validate_region_args_not_consumed(&result, exec_state)?,
1261            Some(StaleRegionPolicy::Warning) => {
1262                warn_if_region_args_consumed(&result, exec_state, &props.name)?;
1263            }
1264            None => {}
1265        }
1266    }
1267    match consumed_solid_arg_check {
1268        ConsumedSolidArgCheck::Error => {
1269            result
1270                .unlabeled
1271                .iter()
1272                .map(|(_, arg)| arg)
1273                .chain(result.labeled.values())
1274                .try_for_each(|arg| validate_value_not_consumed(&arg.value, exec_state, arg.source_range))?;
1275        }
1276        ConsumedSolidArgCheck::WarnDeprecated => {
1277            let std_fn_name = fn_def
1278                .std_props
1279                .as_ref()
1280                .map(|props| props.name.as_str())
1281                .unwrap_or("function");
1282            for arg in result
1283                .unlabeled
1284                .iter()
1285                .map(|(_, arg)| arg)
1286                .chain(result.labeled.values())
1287            {
1288                warn_if_value_consumed_for_deprecated_call(&arg.value, exec_state, arg.source_range, std_fn_name)?;
1289            }
1290        }
1291    }
1292
1293    Ok(result)
1294}
1295
1296pub(super) fn assign_args_to_params_kw(
1297    fn_def: &FunctionSource,
1298    args: Args<Desugared>,
1299    exec_state: &mut ExecState,
1300) -> Result<(), KclError> {
1301    // Add the arguments to the memory.  A new call frame should have already
1302    // been created.
1303    let source_ranges = fn_def.ast.as_source_ranges();
1304
1305    for (name, param) in fn_def.named_args.iter() {
1306        let arg = args.labeled.get(name);
1307        match arg {
1308            Some(arg) => {
1309                exec_state.mut_stack().add(
1310                    name.clone(),
1311                    arg.value.clone(),
1312                    arg.source_ranges().pop().unwrap_or(SourceRange::synthetic()),
1313                )?;
1314            }
1315            None => match &param.default_value {
1316                Some(default_val) => {
1317                    let value = KclValue::from_default_param(default_val.clone(), exec_state);
1318                    exec_state
1319                        .mut_stack()
1320                        .add(name.clone(), value, default_val.source_range())?;
1321                }
1322                None => {
1323                    return Err(KclError::new_argument(KclErrorDetails::new(
1324                        format!("This function requires a parameter {name}, but you haven't passed it one."),
1325                        source_ranges,
1326                    )));
1327                }
1328            },
1329        }
1330    }
1331
1332    if let Some((param_name, _)) = &fn_def.input_arg {
1333        let Some(unlabeled) = args.unlabeled_kw_arg_unconverted() else {
1334            debug_assert!(false, "Bad args");
1335            return Err(KclError::new_internal(KclErrorDetails::new(
1336                "Desugared arguments are inconsistent".to_owned(),
1337                source_ranges,
1338            )));
1339        };
1340        exec_state.mut_stack().add(
1341            param_name.clone(),
1342            unlabeled.value.clone(),
1343            unlabeled.source_ranges().pop().unwrap_or(SourceRange::synthetic()),
1344        )?;
1345    }
1346
1347    Ok(())
1348}
1349
1350fn coerce_result_type(
1351    result: Result<Option<KclValue>, KclError>,
1352    fn_def: &FunctionSource,
1353    exec_state: &mut ExecState,
1354) -> Result<Option<KclValue>, KclError> {
1355    let result = result?;
1356
1357    let Some(ret_ty) = &fn_def.return_type else {
1358        return Ok(result);
1359    };
1360
1361    let ty = resolved_signature_type(
1362        fn_def.resolved_return_ty.as_ref(),
1363        &ret_ty.inner,
1364        ret_ty.as_source_range(),
1365    )?;
1366
1367    // `never` describes the absence of normal completion, so either successful
1368    // result shape violates the function's declared contract.
1369    if ty.subtype(&RuntimeType::never()) {
1370        let message = if result.is_some() {
1371            "This function returned a value, but its return type is `never`. A function with return type `never` must stop evaluation abnormally. You may want to use `fail(...)` to stop evaluation and provide a message."
1372        } else {
1373            "This function completed without returning a value, but its return type is `never`. A function with return type `never` must stop evaluation abnormally. You may want to use `fail(...)` to stop evaluation and provide a message."
1374        };
1375        return Err(KclError::new_type(KclErrorDetails::new(
1376            message.to_owned(),
1377            ret_ty.as_source_ranges(),
1378        )));
1379    }
1380
1381    let Some(val) = result else {
1382        return Ok(None);
1383    };
1384
1385    let val = val.coerce(ty, CoercionMode::implicit(), exec_state).map_err(|_| {
1386        KclError::new_type(KclErrorDetails::new(
1387            format!(
1388                "This function requires its result to be {}",
1389                type_err_str(ret_ty, &val, &(&val).into(), exec_state)
1390            ),
1391            ret_ty.as_source_ranges(),
1392        ))
1393    })?;
1394    Ok(Some(val))
1395}
1396
1397#[cfg(test)]
1398mod test {
1399    use std::sync::Arc;
1400
1401    use super::*;
1402    use crate::engine::engine_manager::EngineManager;
1403    use crate::errors::Severity;
1404    use crate::execution::ContextType;
1405    use crate::execution::EnvironmentRef;
1406    use crate::execution::ExecTestResults;
1407    use crate::execution::memory::Stack;
1408    use crate::execution::parse_execute;
1409    use crate::execution::types::NumericType;
1410    use crate::execution::types::NumericTypeExt;
1411    use crate::parsing::ast::types::DefaultParamVal;
1412    use crate::parsing::ast::types::FunctionExpression;
1413    use crate::parsing::ast::types::Identifier;
1414    use crate::parsing::ast::types::Parameter;
1415    use crate::parsing::ast::types::Program;
1416
1417    fn source_texts<'a>(program: &'a str, error: &KclError) -> Vec<&'a str> {
1418        error
1419            .source_ranges()
1420            .into_iter()
1421            .map(|range| &program[range.start()..range.end()])
1422            .collect()
1423    }
1424
1425    fn get_var(result: &ExecTestResults, name: &str) -> KclValue {
1426        result
1427            .exec_state
1428            .stack()
1429            .memory
1430            .get_from_owned(name, result.mem_env, SourceRange::default(), 0)
1431            .unwrap_or_else(|err| panic!("expected variable `{name}` to exist: {err:?}"))
1432    }
1433
1434    fn var_exists(result: &ExecTestResults, name: &str) -> bool {
1435        result
1436            .exec_state
1437            .stack()
1438            .memory
1439            .get_from_owned(name, result.mem_env, SourceRange::default(), 0)
1440            .is_ok()
1441    }
1442
1443    fn assert_vars_are_tags(result: &ExecTestResults, names: &[&str]) {
1444        for name in names {
1445            assert!(
1446                matches!(get_var(result, name), KclValue::TagIdentifier(_)),
1447                "expected variable `{name}` to be a tag identifier"
1448            );
1449        }
1450    }
1451
1452    fn assert_vars_are_missing(result: &ExecTestResults, names: &[&str]) {
1453        for name in names {
1454            assert!(!var_exists(result, name), "expected variable `{name}` to be absent");
1455        }
1456    }
1457
1458    fn assert_body_face_tags(result: &ExecTestResults, expected: &[&str], unexpected: &[&str]) {
1459        let body = get_var(result, "body");
1460        let KclValue::Solid { value: body } = body else {
1461            panic!("expected `body` to be a solid");
1462        };
1463
1464        for tag in expected {
1465            assert!(body.faces.contains_key(*tag), "expected body.faces to contain `{tag}`");
1466        }
1467
1468        for tag in unexpected {
1469            assert!(
1470                !body.faces.contains_key(*tag),
1471                "expected body.faces not to contain sketch tag `{tag}`"
1472            );
1473        }
1474    }
1475
1476    fn deprecated_solid_tag_access_warnings(result: &ExecTestResults) -> Vec<&CompilationIssue> {
1477        result
1478            .exec_state
1479            .issues()
1480            .iter()
1481            .filter(|issue| issue.message.contains("Accessing solid-created face"))
1482            .collect()
1483    }
1484
1485    #[tokio::test(flavor = "multi_thread")]
1486    async fn test_assign_args_to_params() {
1487        // Set up a little framework for this test.
1488        fn mem(number: usize) -> KclValue {
1489            KclValue::Number {
1490                value: number as f64,
1491                ty: NumericType::count(),
1492                meta: Default::default(),
1493            }
1494        }
1495        fn ident(s: &'static str) -> Node<Identifier> {
1496            Node::no_src(Identifier {
1497                name: s.to_owned(),
1498                digest: None,
1499            })
1500        }
1501        fn opt_param(s: &'static str) -> Parameter {
1502            Parameter {
1503                experimental: false,
1504                deprecated: false,
1505                deprecated_since: None,
1506                identifier: ident(s),
1507                param_type: None,
1508                default_value: Some(DefaultParamVal::none()),
1509                labeled: true,
1510                digest: None,
1511            }
1512        }
1513        fn req_param(s: &'static str) -> Parameter {
1514            Parameter {
1515                experimental: false,
1516                deprecated: false,
1517                deprecated_since: None,
1518                identifier: ident(s),
1519                param_type: None,
1520                default_value: None,
1521                labeled: true,
1522                digest: None,
1523            }
1524        }
1525        fn additional_program_memory(items: &[(String, KclValue)]) -> Stack {
1526            let mut program_memory = Stack::new_for_tests();
1527            for (name, item) in items {
1528                program_memory
1529                    .add(name.clone(), item.clone(), SourceRange::default())
1530                    .unwrap();
1531            }
1532            program_memory
1533        }
1534        // Declare the test cases.
1535        for (test_name, params, args, expected) in [
1536            ("empty", Vec::new(), Vec::new(), Ok(additional_program_memory(&[]))),
1537            (
1538                "all params required, and all given, should be OK",
1539                vec![req_param("x")],
1540                vec![("x", mem(1))],
1541                Ok(additional_program_memory(&[("x".to_owned(), mem(1))])),
1542            ),
1543            (
1544                "all params required, none given, should error",
1545                vec![req_param("x")],
1546                vec![],
1547                Err(KclError::new_argument(KclErrorDetails::new(
1548                    "This function requires a parameter x, but you haven't passed it one.".to_owned(),
1549                    vec![SourceRange::default()],
1550                ))),
1551            ),
1552            (
1553                "all params optional, none given, should be OK",
1554                vec![opt_param("x")],
1555                vec![],
1556                Ok(additional_program_memory(&[("x".to_owned(), KclValue::none())])),
1557            ),
1558            (
1559                "mixed params, too few given",
1560                vec![req_param("x"), opt_param("y")],
1561                vec![],
1562                Err(KclError::new_argument(KclErrorDetails::new(
1563                    "This function requires a parameter x, but you haven't passed it one.".to_owned(),
1564                    vec![SourceRange::default()],
1565                ))),
1566            ),
1567            (
1568                "mixed params, minimum given, should be OK",
1569                vec![req_param("x"), opt_param("y")],
1570                vec![("x", mem(1))],
1571                Ok(additional_program_memory(&[
1572                    ("x".to_owned(), mem(1)),
1573                    ("y".to_owned(), KclValue::none()),
1574                ])),
1575            ),
1576            (
1577                "mixed params, maximum given, should be OK",
1578                vec![req_param("x"), opt_param("y")],
1579                vec![("x", mem(1)), ("y", mem(2))],
1580                Ok(additional_program_memory(&[
1581                    ("x".to_owned(), mem(1)),
1582                    ("y".to_owned(), mem(2)),
1583                ])),
1584            ),
1585        ] {
1586            // Run each test.
1587            let func_expr = Node::no_src(FunctionExpression {
1588                name: None,
1589                params,
1590                body: Program::empty(),
1591                return_type: None,
1592                digest: None,
1593            });
1594            let func_src = FunctionSource::kcl(
1595                crate::parsing::ast::types::BoxNode::new(func_expr),
1596                EnvironmentRef::dummy(),
1597                crate::execution::kcl_value::KclFunctionSourceParams {
1598                    std_props: None,
1599                    experimental: false,
1600                    include_in_feature_tree: false,
1601                },
1602            );
1603            let labeled = args
1604                .iter()
1605                .map(|(name, value)| {
1606                    let arg = Arg::new(value.clone(), SourceRange::default());
1607                    ((*name).to_owned(), arg)
1608                })
1609                .collect::<IndexMap<_, _>>();
1610            let exec_ctxt = ExecutorContext {
1611                engine: Arc::new(EngineManager::new_mock()),
1612                engine_batch: crate::engine::EngineBatchContext::default(),
1613                fs: crate::fs::new_file_system_handle(crate::fs::FileManager::new()),
1614                settings: Default::default(),
1615                context_type: ContextType::Mock,
1616                execution_callbacks: Default::default(),
1617                executor_kind: crate::execution::machine::ExecutorKind::resolve(),
1618                machine_call_depth_limit: crate::execution::machine::DEFAULT_MACHINE_CALL_DEPTH_LIMIT,
1619            };
1620            let mut exec_state = ExecState::new(&exec_ctxt);
1621            exec_state.mod_local.stack = Stack::new_for_tests();
1622
1623            let args = Args {
1624                fn_name: Some("test".to_owned()),
1625                labeled,
1626                unlabeled: Vec::new(),
1627                source_range: SourceRange::default(),
1628                node_path: None,
1629                ctx: exec_ctxt,
1630                pipe_value: None,
1631                _status: std::marker::PhantomData,
1632            };
1633
1634            let actual = assign_args_to_params_kw(&func_src, args, &mut exec_state).map(|_| exec_state.mod_local.stack);
1635            assert_eq!(
1636                actual, expected,
1637                "failed test '{test_name}':\ngot {actual:?}\nbut expected\n{expected:?}"
1638            );
1639        }
1640    }
1641
1642    #[tokio::test(flavor = "multi_thread")]
1643    async fn type_check_user_args() {
1644        let program = r#"fn makeMessage(prefix: string, suffix: string) {
1645  return prefix + suffix
1646}
1647
1648msg1 = makeMessage(prefix = "world", suffix = " hello")
1649msg2 = makeMessage(prefix = 1, suffix = 3)"#;
1650        let err = parse_execute(program).await.unwrap_err();
1651        assert_eq!(
1652            err.message(),
1653            "prefix requires a value with type `string`, but found a value with type `number`.\nThe found value is a number but has incomplete units information. You can probably fix this error by specifying the units using type ascription, e.g., `len: mm` or `(a * b): deg`."
1654        )
1655    }
1656
1657    #[tokio::test(flavor = "multi_thread")]
1658    async fn never_function_cannot_return_a_value() {
1659        let program = r#"@settings(experimentalFeatures = allow)
1660fn bad(): never {
1661  return 42
1662}
1663
1664bad()
1665"#;
1666        let err = parse_execute(program).await.unwrap_err();
1667
1668        assert!(matches!(&err, KclError::Type { .. }));
1669        assert_eq!(
1670            err.message(),
1671            "This function returned a value, but its return type is `never`. A function with return type `never` must stop evaluation abnormally. You may want to use `fail(...)` to stop evaluation and provide a message."
1672        );
1673    }
1674
1675    #[tokio::test(flavor = "multi_thread")]
1676    async fn never_function_cannot_fall_through() {
1677        let program = r#"@settings(experimentalFeatures = allow)
1678fn alsoBad(): never {
1679  x = 42
1680}
1681
1682alsoBad()
1683"#;
1684        let err = parse_execute(program).await.unwrap_err();
1685
1686        assert!(matches!(&err, KclError::Type { .. }));
1687        assert_eq!(
1688            err.message(),
1689            "This function completed without returning a value, but its return type is `never`. A function with return type `never` must stop evaluation abnormally. You may want to use `fail(...)` to stop evaluation and provide a message."
1690        );
1691    }
1692
1693    #[tokio::test(flavor = "multi_thread")]
1694    async fn never_union_function_cannot_return_a_value() {
1695        let program = r#"@settings(experimentalFeatures = allow)
1696fn bad(): never | never {
1697  return 42
1698}
1699
1700bad()
1701"#;
1702        let err = parse_execute(program).await.unwrap_err();
1703
1704        assert!(matches!(&err, KclError::Type { .. }));
1705        assert_eq!(
1706            err.message(),
1707            "This function returned a value, but its return type is `never`. A function with return type `never` must stop evaluation abnormally. You may want to use `fail(...)` to stop evaluation and provide a message."
1708        );
1709    }
1710
1711    #[tokio::test(flavor = "multi_thread")]
1712    async fn never_union_function_cannot_fall_through() {
1713        let program = r#"@settings(experimentalFeatures = allow)
1714fn alsoBad(): never | never {
1715  x = 42
1716}
1717
1718alsoBad()
1719"#;
1720        let err = parse_execute(program).await.unwrap_err();
1721
1722        assert!(matches!(&err, KclError::Type { .. }));
1723        assert_eq!(
1724            err.message(),
1725            "This function completed without returning a value, but its return type is `never`. A function with return type `never` must stop evaluation abnormally. You may want to use `fail(...)` to stop evaluation and provide a message."
1726        );
1727    }
1728
1729    #[tokio::test(flavor = "multi_thread")]
1730    async fn never_function_contract_is_path_dependent() {
1731        let function = r#"@settings(experimentalFeatures = allow)
1732fn failOrReturn(@shouldFail: bool): never {
1733  return if shouldFail {
1734    fail("requested failure")
1735  } else {
1736    42
1737  }
1738}
1739"#;
1740
1741        let err = parse_execute(&format!("{function}\nfailOrReturn(true)\n"))
1742            .await
1743            .unwrap_err();
1744        assert!(matches!(&err, KclError::UserDefined { .. }));
1745        assert_eq!(err.message(), "requested failure");
1746
1747        let err = parse_execute(&format!("{function}\nfailOrReturn(false)\n"))
1748            .await
1749            .unwrap_err();
1750        assert!(matches!(&err, KclError::Type { .. }));
1751        assert_eq!(
1752            err.message(),
1753            "This function returned a value, but its return type is `never`. A function with return type `never` must stop evaluation abnormally. You may want to use `fail(...)` to stop evaluation and provide a message."
1754        );
1755    }
1756
1757    #[tokio::test(flavor = "multi_thread")]
1758    async fn never_type_alias_contract_is_path_dependent() {
1759        let function = r#"@settings(experimentalFeatures = allow)
1760type impossible = never
1761fn failOrReturn(@shouldFail: bool): impossible {
1762  return if shouldFail {
1763    fail("requested failure")
1764  } else {
1765    42
1766  }
1767}
1768"#;
1769
1770        let err = parse_execute(&format!("{function}\nfailOrReturn(true)\n"))
1771            .await
1772            .unwrap_err();
1773        assert!(matches!(&err, KclError::UserDefined { .. }));
1774        assert_eq!(err.message(), "requested failure");
1775
1776        let err = parse_execute(&format!("{function}\nfailOrReturn(false)\n"))
1777            .await
1778            .unwrap_err();
1779        assert!(matches!(&err, KclError::Type { .. }));
1780        assert_eq!(
1781            err.message(),
1782            "This function returned a value, but its return type is `never`. A function with return type `never` must stop evaluation abnormally. You may want to use `fail(...)` to stop evaluation and provide a message."
1783        );
1784    }
1785
1786    #[tokio::test(flavor = "multi_thread")]
1787    async fn union_with_never_can_return_a_value_or_fail() {
1788        let function = r#"@settings(experimentalFeatures = allow)
1789fn stringOrFail(@shouldFail: bool): string | never {
1790  return if shouldFail {
1791    fail("requested failure")
1792  } else {
1793    "ok"
1794  }
1795}
1796"#;
1797
1798        let result = parse_execute(&format!("{function}\nresult = stringOrFail(false)\n"))
1799            .await
1800            .unwrap();
1801        let KclValue::String { value, .. } = get_var(&result, "result") else {
1802            panic!("expected `result` to be a string")
1803        };
1804        assert_eq!(value, "ok");
1805
1806        let err = parse_execute(&format!("{function}\nstringOrFail(true)\n"))
1807            .await
1808            .unwrap_err();
1809        assert!(matches!(&err, KclError::UserDefined { .. }));
1810        assert_eq!(err.message(), "requested failure");
1811    }
1812
1813    #[tokio::test(flavor = "multi_thread")]
1814    async fn fail_reports_user_defined_message_and_callsite_once() {
1815        let program = r#"@settings(experimentalFeatures = allow)
1816fail("custom failure")
1817"#;
1818
1819        let err = parse_execute(program).await.unwrap_err();
1820
1821        assert!(matches!(&err, KclError::UserDefined { .. }));
1822        assert_eq!(err.message(), "custom failure");
1823        assert_eq!(err.get_message(), "user-defined: custom failure");
1824        assert_eq!(serde_json::to_value(&err).unwrap()["kind"], "user_defined");
1825        assert_eq!(source_texts(program, &err), [r#"fail("custom failure")"#]);
1826        assert_eq!(err.backtrace().len(), 1);
1827    }
1828
1829    #[tokio::test(flavor = "multi_thread")]
1830    async fn fail_unwinds_through_nested_never_functions_once() {
1831        let program = r#"@settings(experimentalFeatures = allow)
1832fn inner(): never {
1833  fail("nested failure")
1834}
1835
1836fn outer(): never {
1837  inner()
1838}
1839
1840outer()
1841"#;
1842
1843        let err = parse_execute(program).await.unwrap_err();
1844
1845        assert!(matches!(&err, KclError::UserDefined { .. }));
1846        assert_eq!(err.message(), "nested failure");
1847        assert_eq!(
1848            source_texts(program, &err),
1849            [r#"fail("nested failure")"#, "inner()", "outer()"]
1850        );
1851        assert_eq!(
1852            err.backtrace()
1853                .iter()
1854                .map(|item| item.fn_name.as_deref())
1855                .collect::<Vec<_>>(),
1856            [Some("inner"), Some("outer"), None]
1857        );
1858    }
1859
1860    #[tokio::test(flavor = "multi_thread")]
1861    async fn fail_is_valid_in_a_function_with_a_value_return_type() {
1862        let function = r#"@settings(experimentalFeatures = allow)
1863fn valueOrFail(@shouldFail: bool): number {
1864  return if shouldFail {
1865    fail("no value")
1866  } else {
1867    42
1868  }
1869}
1870"#;
1871
1872        parse_execute(&format!("{function}\nresult = valueOrFail(false)\n"))
1873            .await
1874            .unwrap();
1875
1876        let err = parse_execute(&format!("{function}\nvalueOrFail(true)\n"))
1877            .await
1878            .unwrap_err();
1879        assert!(matches!(&err, KclError::UserDefined { .. }));
1880        assert_eq!(err.message(), "no value");
1881    }
1882
1883    #[tokio::test(flavor = "multi_thread")]
1884    async fn never_function_with_fail_or_fallthrough_is_path_dependent() {
1885        let function = r#"@settings(experimentalFeatures = allow)
1886fn failOrFallThrough(@shouldFail: bool): never {
1887  result = if shouldFail {
1888    fail("requested failure")
1889  } else {
1890    42
1891  }
1892}
1893"#;
1894
1895        let err = parse_execute(&format!("{function}\nfailOrFallThrough(true)\n"))
1896            .await
1897            .unwrap_err();
1898        assert!(matches!(&err, KclError::UserDefined { .. }));
1899        assert_eq!(err.message(), "requested failure");
1900
1901        let err = parse_execute(&format!("{function}\nfailOrFallThrough(false)\n"))
1902            .await
1903            .unwrap_err();
1904        assert!(matches!(&err, KclError::Type { .. }));
1905        assert_eq!(
1906            err.message(),
1907            "This function completed without returning a value, but its return type is `never`. A function with return type `never` must stop evaluation abnormally. You may want to use `fail(...)` to stop evaluation and provide a message."
1908        );
1909    }
1910
1911    #[tokio::test(flavor = "multi_thread")]
1912    async fn fail_argument_evaluation_errors_take_precedence() {
1913        let program = r#"@settings(experimentalFeatures = allow)
1914fn stop(): never {
1915  fail(missingMessage)
1916}
1917
1918stop()
1919"#;
1920
1921        let err = parse_execute(program).await.unwrap_err();
1922
1923        assert!(matches!(&err, KclError::UndefinedValue { .. }));
1924        assert_eq!(err.message(), "`missingMessage` is not defined");
1925        assert_eq!(source_texts(program, &err), ["missingMessage", "stop()"]);
1926    }
1927
1928    #[tokio::test(flavor = "multi_thread")]
1929    async fn fail_rejects_invalid_message_arguments_before_invocation() {
1930        for program in [
1931            "@settings(experimentalFeatures = allow)\nfail()\n",
1932            "@settings(experimentalFeatures = allow)\nfail(42)\n",
1933        ] {
1934            let err = parse_execute(program).await.unwrap_err();
1935            assert!(matches!(&err, KclError::Argument { .. }), "{err:?}");
1936        }
1937    }
1938
1939    #[tokio::test(flavor = "multi_thread")]
1940    async fn map_closure_error_mentions_fn_name() {
1941        let program = r#"
1942arr = ["hello"]
1943map(array = arr, f = fn(@item: number) { return item })
1944"#;
1945        let err = parse_execute(program).await.unwrap_err();
1946        assert!(
1947            err.message().contains("map closure"),
1948            "expected map closure errors to include the closure name, got: {}",
1949            err.message()
1950        );
1951    }
1952
1953    #[tokio::test(flavor = "multi_thread")]
1954    async fn array_input_arg() {
1955        let ast = r#"fn f(@input: [mm]) { return 1 }
1956f([1, 2, 3])
1957f(1, 2, 3)
1958"#;
1959        parse_execute(ast).await.unwrap();
1960    }
1961
1962    #[tokio::test(flavor = "multi_thread")]
1963    async fn extrude_tagged_body_gets_face_tags_and_keeps_legacy_bindings() {
1964        let program = r#"@settings(kclVersion = 2.0)
1965profile = sketch(on = XY) {
1966  line1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
1967  line2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
1968  line3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
1969  line4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
1970  coincident([line1.end, line2.start])
1971  coincident([line2.end, line3.start])
1972  coincident([line3.end, line4.start])
1973  coincident([line4.end, line1.start])
1974}
1975region1 = region(point = [5mm, 5mm], sketch = profile)
1976
1977body = extrude(region1, length = 5mm, tagStart = $bottom, tagEnd = $top)
1978bottomFromBody = body.faces.bottom
1979topFromBody = body.faces.top
1980lineFromSketch = region1.tags.line1
1981legacyBottom = bottom
1982legacyTop = top
1983"#;
1984
1985        let result = parse_execute(program).await.unwrap();
1986        assert_body_face_tags(&result, &["bottom", "top"], &["line1"]);
1987        assert_vars_are_tags(
1988            &result,
1989            &[
1990                "bottom",
1991                "top",
1992                "bottomFromBody",
1993                "topFromBody",
1994                "lineFromSketch",
1995                "legacyBottom",
1996                "legacyTop",
1997            ],
1998        );
1999        assert_vars_are_missing(&result, &["line1"]);
2000    }
2001
2002    #[tokio::test(flavor = "multi_thread")]
2003    async fn extrude_without_tag_arguments_does_not_get_face_tags() {
2004        let program = r#"@settings(kclVersion = 2.0)
2005profile = sketch(on = XY) {
2006  line1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
2007  line2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
2008  line3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
2009  line4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
2010  coincident([line1.end, line2.start])
2011  coincident([line2.end, line3.start])
2012  coincident([line3.end, line4.start])
2013  coincident([line4.end, line1.start])
2014}
2015region1 = region(point = [5mm, 5mm], sketch = profile)
2016
2017body = extrude(region1, length = 5mm)
2018"#;
2019
2020        let result = parse_execute(program).await.unwrap();
2021        let body = get_var(&result, "body");
2022        let KclValue::Solid { value: body } = body else {
2023            panic!("expected `body` to be a solid");
2024        };
2025
2026        assert!(
2027            body.faces.is_empty(),
2028            "body faces should only be populated for tagged calls"
2029        );
2030    }
2031
2032    #[tokio::test(flavor = "multi_thread")]
2033    async fn revolve_tagged_body_gets_face_tags() {
2034        let program = r#"@settings(kclVersion = 2.0)
2035profile = sketch(on = XY) {
2036  side = line(start = [var 5mm, var 0mm], end = [var 5mm, var 10mm])
2037  line2 = line(start = [var 5mm, var 10mm], end = [var 6mm, var 10mm])
2038  line3 = line(start = [var 6mm, var 10mm], end = [var 6mm, var 0mm])
2039  line4 = line(start = [var 6mm, var 0mm], end = [var 5mm, var 0mm])
2040  coincident([side.end, line2.start])
2041  coincident([line2.end, line3.start])
2042  coincident([line3.end, line4.start])
2043  coincident([line4.end, side.start])
2044}
2045region1 = region(point = [5.5mm, 5mm], sketch = profile)
2046
2047body = revolve(region1, axis = Y, angle = 90deg, tagStart = $startCap, tagEnd = $endCap)
2048startFromBody = body.faces.startCap
2049endFromBody = body.faces.endCap
2050sideFromSketch = region1.tags.side
2051legacyStart = startCap
2052legacyEnd = endCap
2053"#;
2054
2055        let result = parse_execute(program).await.unwrap();
2056        assert_body_face_tags(&result, &["startCap", "endCap"], &["side"]);
2057        assert_vars_are_tags(
2058            &result,
2059            &[
2060                "startCap",
2061                "endCap",
2062                "startFromBody",
2063                "endFromBody",
2064                "sideFromSketch",
2065                "legacyStart",
2066                "legacyEnd",
2067            ],
2068        );
2069        assert_vars_are_missing(&result, &["side"]);
2070    }
2071
2072    #[tokio::test(flavor = "multi_thread")]
2073    async fn sweep_tagged_body_gets_face_tags() {
2074        let program = r#"@settings(kclVersion = 2.0)
2075profile = sketch(on = XZ) {
2076  edge1 = line(start = [var 0mm, var 0mm], end = [var 2mm, var 0mm])
2077  edge2 = line(start = [var 2mm, var 0mm], end = [var 2mm, var 2mm])
2078  edge3 = line(start = [var 2mm, var 2mm], end = [var 0mm, var 2mm])
2079  edge4 = line(start = [var 0mm, var 2mm], end = [var 0mm, var 0mm])
2080  coincident([edge1.end, edge2.start])
2081  coincident([edge2.end, edge3.start])
2082  coincident([edge3.end, edge4.start])
2083  coincident([edge4.end, edge1.start])
2084}
2085profileRegion = region(point = [1mm, 1mm], sketch = profile)
2086
2087pathSketch = sketch(on = offsetPlane(YZ, offset = -2mm)) {
2088  pathLine = line(start = [var 0mm, var 0mm], end = [var 0mm, var 5mm])
2089}
2090
2091body = sweep(profileRegion, path = pathSketch.pathLine, tagStart = $startCap, tagEnd = $endCap)
2092startFromBody = body.faces.startCap
2093endFromBody = body.faces.endCap
2094edgeFromSketch = profileRegion.tags.edge1
2095pathFromSketch = pathSketch.pathLine
2096legacyStart = startCap
2097legacyEnd = endCap
2098"#;
2099
2100        let result = parse_execute(program).await.unwrap();
2101        assert_body_face_tags(&result, &["startCap", "endCap"], &["edge1", "pathLine"]);
2102        assert_vars_are_tags(
2103            &result,
2104            &[
2105                "startCap",
2106                "endCap",
2107                "startFromBody",
2108                "endFromBody",
2109                "edgeFromSketch",
2110                "legacyStart",
2111                "legacyEnd",
2112            ],
2113        );
2114        assert_vars_are_missing(&result, &["edge1", "pathLine"]);
2115    }
2116
2117    #[tokio::test(flavor = "multi_thread")]
2118    async fn loft_tagged_body_gets_face_tags() {
2119        let program = r#"@settings(kclVersion = 2.0)
2120lowerProfile = sketch(on = XY) {
2121  edge1 = line(start = [var 0mm, var 0mm], end = [var 6mm, var 0mm])
2122  edge2 = line(start = [var 6mm, var 0mm], end = [var 6mm, var 4mm])
2123  edge3 = line(start = [var 6mm, var 4mm], end = [var 0mm, var 4mm])
2124  edge4 = line(start = [var 0mm, var 4mm], end = [var 0mm, var 0mm])
2125  coincident([edge1.end, edge2.start])
2126  coincident([edge2.end, edge3.start])
2127  coincident([edge3.end, edge4.start])
2128  coincident([edge4.end, edge1.start])
2129}
2130lowerRegion = region(point = [3mm, 2mm], sketch = lowerProfile)
2131
2132upperProfile = sketch(on = offsetPlane(XY, offset = 8mm)) {
2133  edge5 = line(start = [var 1mm, var 1mm], end = [var 5mm, var 1mm])
2134  edge6 = line(start = [var 5mm, var 1mm], end = [var 4mm, var 3mm])
2135  edge7 = line(start = [var 4mm, var 3mm], end = [var 2mm, var 3mm])
2136  edge8 = line(start = [var 2mm, var 3mm], end = [var 1mm, var 1mm])
2137  coincident([edge5.end, edge6.start])
2138  coincident([edge6.end, edge7.start])
2139  coincident([edge7.end, edge8.start])
2140  coincident([edge8.end, edge5.start])
2141}
2142upperRegion = region(point = [3mm, 2mm], sketch = upperProfile)
2143
2144body = loft([lowerRegion, upperRegion], tagStart = $startCap, tagEnd = $endCap)
2145startFromBody = body.faces.startCap
2146endFromBody = body.faces.endCap
2147edgeFromSketch = lowerRegion.tags.edge1
2148legacyStart = startCap
2149legacyEnd = endCap
2150"#;
2151
2152        let result = parse_execute(program).await.unwrap();
2153        assert_body_face_tags(&result, &["startCap", "endCap"], &["edge1"]);
2154        assert_vars_are_tags(
2155            &result,
2156            &[
2157                "startCap",
2158                "endCap",
2159                "startFromBody",
2160                "endFromBody",
2161                "edgeFromSketch",
2162                "legacyStart",
2163                "legacyEnd",
2164            ],
2165        );
2166        assert_vars_are_missing(&result, &["edge1"]);
2167    }
2168
2169    #[tokio::test(flavor = "multi_thread")]
2170    async fn chamfer_tagged_body_gets_face_tags() {
2171        let program = r#"@settings(kclVersion = 2.0)
2172profile = sketch(on = XY) {
2173  edge1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
2174  edge2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
2175  edge3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
2176  edge4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
2177  coincident([edge1.end, edge2.start])
2178  coincident([edge2.end, edge3.start])
2179  coincident([edge3.end, edge4.start])
2180  coincident([edge4.end, edge1.start])
2181}
2182profileRegion = region(point = [5mm, 5mm], sketch = profile)
2183
2184base = extrude(profileRegion, length = 5mm, tagEnd = $top)
2185body = chamfer(base, tags = getCommonEdge(faces = [profileRegion.tags.edge1, top]), length = 1mm, tag = $chamferFace)
2186chamferFromBody = body.faces.chamferFace
2187topFromBody = body.faces.top
2188edgeFromSketch = profileRegion.tags.edge1
2189legacyChamfer = chamferFace
2190legacyTop = top
2191"#;
2192
2193        let result = parse_execute(program).await.unwrap();
2194        assert_body_face_tags(&result, &["top", "chamferFace"], &["edge1"]);
2195        assert_vars_are_tags(
2196            &result,
2197            &[
2198                "top",
2199                "chamferFace",
2200                "chamferFromBody",
2201                "topFromBody",
2202                "edgeFromSketch",
2203                "legacyChamfer",
2204                "legacyTop",
2205            ],
2206        );
2207        assert_vars_are_missing(&result, &["edge1"]);
2208    }
2209
2210    #[tokio::test(flavor = "multi_thread")]
2211    async fn fillet_tagged_body_gets_face_tags() {
2212        let program = r#"@settings(kclVersion = 2.0)
2213profile = sketch(on = XY) {
2214  edge1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
2215  edge2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
2216  edge3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
2217  edge4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
2218  coincident([edge1.end, edge2.start])
2219  coincident([edge2.end, edge3.start])
2220  coincident([edge3.end, edge4.start])
2221  coincident([edge4.end, edge1.start])
2222}
2223profileRegion = region(point = [5mm, 5mm], sketch = profile)
2224
2225base = extrude(profileRegion, length = 5mm, tagEnd = $top)
2226body = fillet(base, tags = getCommonEdge(faces = [profileRegion.tags.edge1, top]), radius = 1mm, tag = $filletFace)
2227filletFromBody = body.faces.filletFace
2228topFromBody = body.faces.top
2229edgeFromSketch = profileRegion.tags.edge1
2230legacyFillet = filletFace
2231legacyTop = top
2232"#;
2233
2234        let result = parse_execute(program).await.unwrap();
2235        assert_body_face_tags(&result, &["top", "filletFace"], &["edge1"]);
2236        assert_vars_are_tags(
2237            &result,
2238            &[
2239                "top",
2240                "filletFace",
2241                "filletFromBody",
2242                "topFromBody",
2243                "edgeFromSketch",
2244                "legacyFillet",
2245                "legacyTop",
2246            ],
2247        );
2248        assert_vars_are_missing(&result, &["edge1"]);
2249    }
2250
2251    #[tokio::test(flavor = "multi_thread")]
2252    async fn accessing_body_tag_through_body_sketch_tags_warns() {
2253        let program = r#"@settings(kclVersion = 2.0)
2254profile = startSketchOn(XY)
2255  |> startProfile(at = [0, 0])
2256  |> line(end = [10, 0], tag = $line1)
2257  |> line(end = [0, 10])
2258  |> line(end = [-10, 0])
2259  |> close()
2260
2261body = extrude(profile, length = 5, tagEnd = $top)
2262topFromSketch = body.sketch.tags.top
2263topFromBody = body.faces.top
2264"#;
2265
2266        let result = parse_execute(program).await.unwrap();
2267        assert!(matches!(get_var(&result, "topFromSketch"), KclValue::TagIdentifier(_)));
2268        assert!(matches!(get_var(&result, "topFromBody"), KclValue::TagIdentifier(_)));
2269
2270        let warnings = deprecated_solid_tag_access_warnings(&result);
2271        assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
2272        assert_eq!(warnings[0].severity, Severity::Warning);
2273        assert!(warnings[0].message.contains("`top`"), "found {}", warnings[0].message);
2274        assert!(
2275            warnings[0].message.contains("Accessing solid-created face `top` through sketch tags is deprecated. Use the body's faces instead, e.g. `body.faces.top`."),
2276            "found {}",
2277            warnings[0].message
2278        );
2279    }
2280
2281    #[tokio::test(flavor = "multi_thread")]
2282    async fn accessing_sketch_path_tag_through_body_sketch_tags_does_not_warn() {
2283        let program = r#"@settings(kclVersion = 2.0)
2284profile = startSketchOn(XY)
2285  |> startProfile(at = [0, 0])
2286  |> line(end = [10, 0], tag = $line1)
2287  |> line(end = [0, 10])
2288  |> line(end = [-10, 0])
2289  |> close()
2290
2291body = extrude(profile, length = 5, tagEnd = $top)
2292lineFromSketch = body.sketch.tags.line1
2293"#;
2294
2295        let result = parse_execute(program).await.unwrap();
2296        assert!(matches!(get_var(&result, "lineFromSketch"), KclValue::TagIdentifier(_)));
2297        let warnings = deprecated_solid_tag_access_warnings(&result);
2298        assert!(
2299            warnings.is_empty(),
2300            "sketch path tags should not get body-tag deprecation warnings: {warnings:#?}"
2301        );
2302    }
2303
2304    #[tokio::test(flavor = "multi_thread")]
2305    async fn accessing_body_tag_through_sketch_block_region_tags_warns() {
2306        let program = r#"@settings(kclVersion = 2.0)
2307profile = sketch(on = XY) {
2308  line1 = line(start = [0, 0], end = [10, 0])
2309  line2 = line(start = [10, 0], end = [10, 10])
2310  line3 = line(start = [10, 10], end = [0, 10])
2311  line4 = line(start = [0, 10], end = [0, 0])
2312}
2313
2314profileRegion = region(point = [1, 1], sketch = profile)
2315body = extrude(profileRegion, length = 5, tagEnd = $top)
2316topFromRegion = profileRegion.tags.top
2317"#;
2318
2319        let result = parse_execute(program).await.unwrap();
2320        assert!(matches!(get_var(&result, "topFromRegion"), KclValue::TagIdentifier(_)));
2321
2322        let warnings = deprecated_solid_tag_access_warnings(&result);
2323        assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
2324        assert_eq!(warnings[0].severity, Severity::Warning);
2325        assert!(warnings[0].message.contains("`top`"), "found {}", warnings[0].message);
2326    }
2327
2328    fn deprecation_warnings(result: &ExecTestResults) -> Vec<&CompilationIssue> {
2329        result
2330            .exec_state
2331            .issues()
2332            .iter()
2333            .filter(|issue| issue.message.contains("is deprecated"))
2334            .collect()
2335    }
2336
2337    #[tokio::test(flavor = "multi_thread")]
2338    async fn passing_param_deprecated_for_all_versions_warns() {
2339        // `@(deprecated = true)` deprecates the parameter regardless of the KCL
2340        // version, so even on the latest version the call should warn.
2341        let program = r#"@settings(kclVersion = 2.0)
2342fn f(
2343  @a: number,
2344  @(deprecated = true)
2345  oldArg?: number,
2346) {
2347  return a
2348}
2349x = f(1, oldArg = 2)
2350"#;
2351
2352        let result = parse_execute(program).await.unwrap();
2353        let warnings = deprecation_warnings(&result);
2354        assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
2355        assert_eq!(warnings[0].severity, Severity::Warning);
2356        assert_eq!(warnings[0].tag, crate::errors::Tag::Deprecated);
2357        assert!(
2358            warnings[0].message.contains("`f(oldArg)` is deprecated"),
2359            "found {}",
2360            warnings[0].message
2361        );
2362    }
2363
2364    #[tokio::test(flavor = "multi_thread")]
2365    async fn not_passing_deprecated_param_does_not_warn() {
2366        let program = r#"fn f(
2367  @a: number,
2368  @(deprecated = true)
2369  oldArg?: number,
2370) {
2371  return a
2372}
2373x = f(1)
2374"#;
2375
2376        let result = parse_execute(program).await.unwrap();
2377        let warnings = deprecation_warnings(&result);
2378        assert!(
2379            warnings.is_empty(),
2380            "unused deprecated parameter should not warn: {warnings:#?}"
2381        );
2382    }
2383
2384    #[tokio::test(flavor = "multi_thread")]
2385    async fn deprecated_calls_inside_kcl_stdlib_do_not_warn() {
2386        let program = include_str!("../../tests/cube_with_hole/input.kcl");
2387
2388        let result = parse_execute(program).await.unwrap();
2389        let warnings = deprecation_warnings(&result);
2390        assert!(
2391            warnings.is_empty(),
2392            "KCL stdlib internals should not emit deprecation warnings: {warnings:#?}"
2393        );
2394    }
2395
2396    #[tokio::test(flavor = "multi_thread")]
2397    async fn deprecated_stdlib_call_from_user_code_still_warns() {
2398        let program = r#"@settings(kclVersion = 2.0)
2399plane = startSketchOn(XY)
2400"#;
2401
2402        let result = parse_execute(program).await.unwrap();
2403        let warnings = deprecation_warnings(&result);
2404        assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
2405        assert!(
2406            warnings[0].message.contains("`startSketchOn` is deprecated"),
2407            "found {}",
2408            warnings[0].message
2409        );
2410        assert_eq!(warnings[0].tag, crate::errors::Tag::Deprecated);
2411    }
2412
2413    #[tokio::test(flavor = "multi_thread")]
2414    async fn deprecated_since_warns_for_prerelease_kcl_version() {
2415        let program = r#"@settings(kclVersion = "3.0-preview")
2416plane = startSketchOn(XY)
2417"#;
2418
2419        let result = parse_execute(program).await.unwrap();
2420        let warnings = deprecation_warnings(&result);
2421        assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
2422        assert_eq!(warnings[0].severity, Severity::Warning);
2423        assert_eq!(warnings[0].tag, crate::errors::Tag::Deprecated);
2424        assert!(
2425            warnings[0]
2426                .message
2427                .contains("`startSketchOn` is deprecated as of KCL 2.0"),
2428            "found {}",
2429            warnings[0].message
2430        );
2431    }
2432
2433    #[tokio::test(flavor = "multi_thread")]
2434    async fn deprecation_version_override_does_not_change_program_version() {
2435        let program = crate::Program::parse_no_errs(
2436            r#"@settings(kclVersion = 1.0)
2437plane = startSketchOn(XY)
2438"#,
2439        )
2440        .unwrap();
2441        let exec_ctxt = ExecutorContext {
2442            engine: Arc::new(EngineManager::new_mock()),
2443            engine_batch: crate::engine::EngineBatchContext::default(),
2444            fs: crate::fs::new_file_system_handle(crate::fs::FileManager::new()),
2445            settings: Default::default(),
2446            context_type: ContextType::Mock,
2447            execution_callbacks: Default::default(),
2448            executor_kind: crate::execution::machine::ExecutorKind::resolve(),
2449            machine_call_depth_limit: crate::execution::machine::DEFAULT_MACHINE_CALL_DEPTH_LIMIT,
2450        };
2451        let mut exec_state = ExecState::new(&exec_ctxt);
2452        exec_state.set_deprecation_version_override(Some("2.0"));
2453
2454        exec_ctxt.run(&program, &mut exec_state).await.unwrap();
2455
2456        assert_eq!(exec_state.mod_local.settings.kcl_version, crate::KclVersion::V1);
2457        let warnings = exec_state
2458            .issues()
2459            .iter()
2460            .filter(|issue| issue.tag == crate::errors::Tag::Deprecated)
2461            .collect::<Vec<_>>();
2462        assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
2463    }
2464
2465    #[tokio::test(flavor = "multi_thread")]
2466    async fn deprecated_sketch_v1_warning_explains_sketch_solve() {
2467        // Sketch v1 deprecation warnings must be self-contained: they should
2468        // say what replaces the function and link the conversion docs so both
2469        // humans and AI agents can act on the warning alone.
2470        let program = r#"@settings(kclVersion = 2.0)
2471exampleSketch = startSketchOn(XZ)
2472  |> startProfile(at = [0, 0])
2473  |> line(end = [10, 0])
2474"#;
2475
2476        let result = parse_execute(program).await.unwrap();
2477        let warnings = deprecation_warnings(&result);
2478        assert_eq!(
2479            warnings.len(),
2480            3,
2481            "expected one warning per sketch v1 call, got {warnings:#?}"
2482        );
2483        for warning in warnings {
2484            assert!(
2485                warning.message.contains("sketch-solve"),
2486                "expected sketch-solve context in {}",
2487                warning.message
2488            );
2489            assert!(
2490                warning
2491                    .message
2492                    .contains("https://zoo.dev/docs/kcl-book/sketch2d_constraints.html"),
2493                "expected docs URL in {}",
2494                warning.message
2495            );
2496        }
2497    }
2498}