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