Skip to main content

kcl_lib/execution/
fn_call.rs

1use async_recursion::async_recursion;
2use indexmap::IndexMap;
3use kcl_api::Group;
4use kcl_api::OpArg;
5
6use crate::CompilationIssue;
7use crate::NodePath;
8use crate::NodePathExt;
9use crate::SourceRange;
10use crate::errors::KclError;
11use crate::errors::KclErrorDetails;
12use crate::execution::BodyType;
13use crate::execution::ExecState;
14use crate::execution::ExecutorContext;
15use crate::execution::Geometry;
16use crate::execution::KclValue;
17use crate::execution::KclValueControlFlow;
18use crate::execution::Metadata;
19use crate::execution::Solid;
20use crate::execution::StatementKind;
21use crate::execution::TagEngineInfo;
22use crate::execution::TagIdentifier;
23use crate::execution::annotations;
24use crate::execution::cad_op::Operation;
25use crate::execution::cad_op::op_from_kcl_value;
26use crate::execution::control_continue;
27use crate::execution::kcl_value::FunctionBody;
28use crate::execution::kcl_value::FunctionSource;
29use crate::execution::kcl_value::NamedParam;
30use crate::execution::memory;
31use crate::execution::types::RuntimeType;
32use crate::parsing::ast::types::CallExpressionKw;
33use crate::parsing::ast::types::Node;
34use crate::parsing::ast::types::Type;
35use crate::std::ConsumedSolidArgCheck;
36use crate::std::solid_consumption::validate_value_not_consumed;
37use crate::std::solid_consumption::warn_if_value_consumed_for_deprecated_call;
38
39#[derive(Debug, Clone)]
40pub struct Args<Status: ArgsStatus = Desugared> {
41    /// Name of the function these args are being passed into.
42    pub fn_name: Option<String>,
43    /// Unlabeled keyword args. Currently only the first formal arg can be unlabeled.
44    /// If the argument was a local variable, then the first element of the tuple is its name
45    /// which may be used to treat this arg as a labelled arg.
46    pub unlabeled: Vec<(Option<String>, Arg)>,
47    /// Labeled args.
48    pub labeled: IndexMap<String, Arg>,
49    pub source_range: SourceRange,
50    pub node_path: Option<NodePath>,
51    pub ctx: ExecutorContext,
52    /// If this call happens inside a pipe (|>) expression, this holds the LHS of that |>.
53    /// Otherwise it's None.
54    pub pipe_value: Option<Arg>,
55    _status: std::marker::PhantomData<Status>,
56}
57
58pub trait ArgsStatus: std::fmt::Debug + Clone {}
59
60#[derive(Debug, Clone)]
61pub struct Sugary;
62impl ArgsStatus for Sugary {}
63
64// Invariants guaranteed by the `Desugared` status:
65// - There is either 0 or 1 unlabeled arguments
66// - Any lableled args are in the labeled map, and not the unlabeled Vec.
67// - The arguments match the type signature of the function exactly
68// - pipe_value.is_none()
69#[derive(Debug, Clone)]
70pub struct Desugared;
71impl ArgsStatus for Desugared {}
72
73impl Args<Sugary> {
74    /// Collect the given keyword arguments.
75    pub fn new(
76        labeled: IndexMap<String, Arg>,
77        unlabeled: Vec<(Option<String>, Arg)>,
78        source_range: SourceRange,
79        node_path: Option<NodePath>,
80        exec_state: &mut ExecState,
81        ctx: ExecutorContext,
82        fn_name: Option<String>,
83    ) -> Args<Sugary> {
84        Args {
85            fn_name,
86            labeled,
87            unlabeled,
88            source_range,
89            node_path,
90            ctx,
91            pipe_value: exec_state.pipe_value().map(|v| Arg::new(v.clone(), source_range)),
92            _status: std::marker::PhantomData,
93        }
94    }
95}
96
97impl<Status: ArgsStatus> Args<Status> {
98    /// How many arguments are there?
99    pub fn len(&self) -> usize {
100        self.labeled.len() + self.unlabeled.len()
101    }
102
103    /// Are there no arguments?
104    pub fn is_empty(&self) -> bool {
105        self.labeled.is_empty() && self.unlabeled.is_empty()
106    }
107}
108
109impl Args<Desugared> {
110    pub fn new_no_args(
111        source_range: SourceRange,
112        node_path: Option<NodePath>,
113        ctx: ExecutorContext,
114        fn_name: Option<String>,
115    ) -> Args {
116        Args {
117            fn_name,
118            unlabeled: Default::default(),
119            labeled: Default::default(),
120            source_range,
121            node_path,
122            ctx,
123            pipe_value: None,
124            _status: std::marker::PhantomData,
125        }
126    }
127
128    /// Get the unlabeled keyword argument. If not set, returns None.
129    pub(crate) fn unlabeled_kw_arg_unconverted(&self) -> Option<&Arg> {
130        self.unlabeled.first().map(|(_, a)| a)
131    }
132}
133
134#[derive(Debug, Clone)]
135pub struct Arg {
136    /// The evaluated argument.
137    pub value: KclValue,
138    /// The source range of the unevaluated argument.
139    pub source_range: SourceRange,
140}
141
142impl Arg {
143    pub fn new(value: KclValue, source_range: SourceRange) -> Self {
144        Self { value, source_range }
145    }
146
147    pub fn synthetic(value: KclValue) -> Self {
148        Self {
149            value,
150            source_range: SourceRange::synthetic(),
151        }
152    }
153
154    pub fn source_ranges(&self) -> Vec<SourceRange> {
155        vec![self.source_range]
156    }
157}
158
159impl Node<CallExpressionKw> {
160    #[async_recursion]
161    pub(super) async fn execute(
162        &self,
163        exec_state: &mut ExecState,
164        ctx: &ExecutorContext,
165    ) -> Result<KclValueControlFlow, KclError> {
166        let fn_name = &self.callee;
167        let callsite: SourceRange = self.into();
168
169        // Resolve the function before evaluating arguments so calls can mutate
170        // exec_state without holding a memory borrow.
171        let func: KclValue = fn_name.get_result(exec_state, ctx).await?;
172
173        let Some(fn_src) = func.as_function() else {
174            return Err(KclError::new_semantic(KclErrorDetails::new(
175                "cannot call this because it isn't a function".to_string(),
176                vec![callsite],
177            )));
178        };
179
180        // Build a hashmap from argument labels to the final evaluated values.
181        let mut fn_args = IndexMap::with_capacity(self.arguments.len());
182        let mut unlabeled = Vec::new();
183
184        // Evaluate the unlabeled first param, if any exists.
185        if let Some(ref arg_expr) = self.unlabeled {
186            let source_range = SourceRange::from(arg_expr.clone());
187            let metadata = Metadata { source_range };
188            let value_cf = ctx
189                .execute_expr(arg_expr, exec_state, &metadata, &[], StatementKind::Expression)
190                .await?;
191            let value = control_continue!(value_cf);
192
193            let label = arg_expr.ident_name().map(str::to_owned);
194
195            unlabeled.push((label, Arg::new(value, source_range)))
196        }
197
198        for arg_expr in &self.arguments {
199            let source_range = SourceRange::from(arg_expr.arg.clone());
200            let metadata = Metadata { source_range };
201            let value_cf = ctx
202                .execute_expr(&arg_expr.arg, exec_state, &metadata, &[], StatementKind::Expression)
203                .await?;
204            let value = control_continue!(value_cf);
205            let arg = Arg::new(value, source_range);
206            match &arg_expr.label {
207                Some(l) => {
208                    fn_args.insert(l.name.clone(), arg);
209                }
210                None => {
211                    unlabeled.push((arg_expr.arg.ident_name().map(str::to_owned), arg));
212                }
213            }
214        }
215
216        let args = Args::new(
217            fn_args,
218            unlabeled,
219            callsite,
220            self.node_path.clone(),
221            exec_state,
222            ctx.clone(),
223            Some(fn_name.name.name.clone()),
224        );
225
226        let return_value = fn_src
227            .call_kw(Some(fn_name.to_string()), exec_state, ctx, args, callsite)
228            .await
229            .map_err(|e| {
230                // Add the call expression to the source ranges.
231                //
232                // TODO: Use the name that the function was defined
233                // with, not the identifier it was used with.
234                e.add_unwind_location(Some(fn_name.name.name.clone()), callsite)
235            })?;
236
237        let result = return_value.ok_or_else(move || {
238            let mut source_ranges: Vec<SourceRange> = vec![callsite];
239            // We want to send the source range of the original function.
240            if let KclValue::Function { meta, .. } = func {
241                source_ranges = meta.iter().map(|m| m.source_range).collect();
242            };
243            KclError::new_undefined_value(
244                KclErrorDetails::new(
245                    format!("Result of user-defined function {fn_name} is undefined"),
246                    source_ranges,
247                ),
248                None,
249            )
250        })?;
251
252        Ok(result)
253    }
254}
255
256impl FunctionSource {
257    pub(crate) async fn call_kw(
258        &self,
259        fn_name: Option<String>,
260        exec_state: &mut ExecState,
261        ctx: &ExecutorContext,
262        args: Args<Sugary>,
263        callsite: SourceRange,
264    ) -> Result<Option<KclValueControlFlow>, KclError> {
265        exec_state.inc_call_stack_size(callsite)?;
266
267        let result = self.inner_call_kw(fn_name, exec_state, ctx, args, callsite).await;
268
269        exec_state.dec_call_stack_size(callsite)?;
270        result
271    }
272
273    async fn inner_call_kw(
274        &self,
275        fn_name: Option<String>,
276        exec_state: &mut ExecState,
277        ctx: &ExecutorContext,
278        args: Args<Sugary>,
279        callsite: SourceRange,
280    ) -> Result<Option<KclValueControlFlow>, KclError> {
281        if self.deprecated {
282            exec_state.warn(
283                CompilationIssue::err(
284                    callsite,
285                    format!(
286                        "{} is deprecated, see the docs for a recommended replacement",
287                        match &fn_name {
288                            Some(n) => format!("`{n}`"),
289                            None => "This function".to_owned(),
290                        }
291                    ),
292                ),
293                annotations::WARN_DEPRECATED,
294            );
295        } else if let Some(since) = &self.deprecated_since
296            && annotations::version_ge(&exec_state.mod_local.settings.kcl_version, since)
297        {
298            exec_state.warn(
299                CompilationIssue::err(
300                    callsite,
301                    format!(
302                        "{} is deprecated as of KCL {since}. See the docs for a recommended replacement.",
303                        match &fn_name {
304                            Some(n) => format!("`{n}`"),
305                            None => "This function".to_owned(),
306                        }
307                    ),
308                ),
309                annotations::WARN_DEPRECATED,
310            );
311        }
312        if self.experimental {
313            exec_state.warn_experimental(
314                &match &fn_name {
315                    Some(n) => format!("`{n}`"),
316                    None => "This function".to_owned(),
317                },
318                callsite,
319            );
320        }
321
322        let args = type_check_params_kw(fn_name.as_deref(), self, args, exec_state)?;
323        let face_tag_names = face_tag_names_for_call(self, &args);
324
325        // Warn if experimental or deprecated arguments are used after desugaring.
326        for (label, arg) in &args.labeled {
327            let Some(param) = self.named_args.get(label.as_str()) else {
328                continue;
329            };
330            if param.experimental {
331                exec_state.warn_experimental(
332                    &match &fn_name {
333                        Some(f) => format!("`{f}({label})`"),
334                        None => label.to_owned(),
335                    },
336                    arg.source_range,
337                );
338            }
339            // `deprecated` deprecates the parameter for all versions, whereas
340            // `deprecated_since` only deprecates it at or after a given version.
341            let deprecation_suffix = if param.deprecated {
342                Some("is deprecated, see the docs for a recommended replacement".to_owned())
343            } else if let Some(since) = &param.deprecated_since
344                && annotations::version_ge(&exec_state.mod_local.settings.kcl_version, since)
345            {
346                Some(format!(
347                    "is deprecated as of KCL {since}. See the docs for a recommended replacement."
348                ))
349            } else {
350                None
351            };
352            if let Some(suffix) = deprecation_suffix {
353                let qualified = match &fn_name {
354                    Some(f) => format!("`{f}({label})`"),
355                    None => format!("`{label}`"),
356                };
357                exec_state.warn(
358                    CompilationIssue::err(arg.source_range, format!("{qualified} {suffix}")),
359                    annotations::WARN_DEPRECATED,
360                );
361            }
362        }
363
364        // Don't early return until the stack frame is popped!
365        self.body.prep_mem(exec_state)?;
366
367        // Some function calls might get added to the feature tree.
368        // We do this by adding an "operation".
369
370        // Don't add operations if the KCL code being executed is
371        // just the KCL stdlib calling other KCL stdlib,
372        // because the stdlib internals aren't relevant to users,
373        // that would just be pointless noise.
374        //
375        // Do add operations if the KCL being executed is
376        // user-defined, or the calling code is user-defined,
377        // because that's relevant to the user.
378        let would_trace_stdlib_internals = exec_state.mod_local.inside_stdlib && self.is_std();
379        // self.include_in_feature_tree is set by the KCL annotation `@(feature_tree = true)`.
380        let should_track_operation = !would_trace_stdlib_internals && self.include_in_feature_tree;
381        let op = if should_track_operation {
382            let op_labeled_args = args
383                .labeled
384                .iter()
385                .map(|(k, arg)| (k.clone(), OpArg::new(op_from_kcl_value(&arg.value), arg.source_range)))
386                .collect();
387
388            // If you're calling a stdlib function, track that call as an operation.
389            if self.is_std() {
390                Some(Operation::StdLibCall {
391                    name: fn_name.clone().unwrap_or_else(|| "unknown function".to_owned()),
392                    unlabeled_arg: args
393                        .unlabeled_kw_arg_unconverted()
394                        .map(|arg| OpArg::new(op_from_kcl_value(&arg.value), arg.source_range)),
395                    labeled_args: op_labeled_args,
396                    node_path: NodePath::placeholder(),
397                    source_range: callsite,
398                    stdlib_entry_source_range: exec_state.mod_local.stdlib_entry_source_range,
399                    is_error: false,
400                })
401            } else {
402                // Otherwise, you're calling a user-defined function, track that call as an operation.
403                exec_state.push_op(Operation::GroupBegin {
404                    group: Group::FunctionCall {
405                        name: fn_name.clone(),
406                        function_source_range: self.ast.as_source_range(),
407                        unlabeled_arg: args
408                            .unlabeled_kw_arg_unconverted()
409                            .map(|arg| OpArg::new(op_from_kcl_value(&arg.value), arg.source_range)),
410                        labeled_args: op_labeled_args,
411                    },
412                    node_path: NodePath::placeholder(),
413                    source_range: callsite,
414                });
415
416                None
417            }
418        } else {
419            None
420        };
421
422        let is_calling_into_stdlib = match &self.body {
423            FunctionBody::Rust(_) => true,
424            FunctionBody::Kcl(_) => self.is_std(),
425        };
426        let is_crossing_into_stdlib = is_calling_into_stdlib && !exec_state.mod_local.inside_stdlib;
427        let is_crossing_out_of_stdlib = !is_calling_into_stdlib && exec_state.mod_local.inside_stdlib;
428        let stdlib_entry_source_range = if is_crossing_into_stdlib {
429            // When we're calling into the stdlib, for example calling hole(),
430            // track the location so that any further stdlib calls like
431            // subtract() can point to the hole() call. The frontend needs this.
432            Some(callsite)
433        } else if is_crossing_out_of_stdlib {
434            // When map() calls a user-defined function, and it calls extrude()
435            // for example, we want it to point the the extrude() call, not
436            // the map() call.
437            None
438        } else {
439            // When we're not crossing the stdlib boundary, keep the previous
440            // value.
441            exec_state.mod_local.stdlib_entry_source_range
442        };
443
444        let prev_inside_stdlib = std::mem::replace(&mut exec_state.mod_local.inside_stdlib, is_calling_into_stdlib);
445        let prev_stdlib_entry_source_range = std::mem::replace(
446            &mut exec_state.mod_local.stdlib_entry_source_range,
447            stdlib_entry_source_range,
448        );
449        // Do not early return via ? or something until we've
450        // - put this `prev_inside_stdlib` value back.
451        // - called the pop_env.
452        let result = match &self.body {
453            FunctionBody::Rust(f) => f(exec_state, args).await.map(Some),
454            FunctionBody::Kcl(_) => {
455                if let Err(e) = assign_args_to_params_kw(self, args, exec_state) {
456                    exec_state.mod_local.inside_stdlib = prev_inside_stdlib;
457                    exec_state.mut_stack().pop_env()?;
458                    return Err(e);
459                }
460
461                ctx.exec_block(&self.ast.body, exec_state, BodyType::Block)
462                    .await
463                    .map(|cf| {
464                        if let Some(cf) = cf
465                            && cf.is_some_return()
466                        {
467                            return Some(cf);
468                        }
469                        // Ignore the block's value and extract the return value
470                        // from memory.
471                        exec_state
472                            .stack()
473                            .get(memory::RETURN_NAME, self.ast.as_source_range())
474                            .ok()
475                            .map(KclValue::continue_)
476                    })
477            }
478        };
479        exec_state.mod_local.inside_stdlib = prev_inside_stdlib;
480        exec_state.mod_local.stdlib_entry_source_range = prev_stdlib_entry_source_range;
481        exec_state.mut_stack().pop_env()?;
482
483        if should_track_operation {
484            if let Some(mut op) = op {
485                op.set_std_lib_call_is_error(result.is_err());
486                // Track call operation.  We do this after the call
487                // since things like patternTransform may call user code
488                // before running, and we will likely want to use the
489                // return value. The call takes ownership of the args,
490                // so we need to build the op before the call.
491                exec_state.push_op(op);
492            } else if !is_calling_into_stdlib {
493                exec_state.push_op(Operation::GroupEnd);
494            }
495        }
496
497        let mut result = match result {
498            Ok(Some(value)) => {
499                if value.is_some_return() {
500                    return Ok(Some(value));
501                } else {
502                    Ok(Some(value.into_value()))
503                }
504            }
505            Ok(None) => Ok(None),
506            Err(e) => Err(e),
507        };
508
509        if self.is_std()
510            && let Ok(Some(result)) = &mut result
511        {
512            update_memory_for_tags_of_geometry(result, exec_state)?;
513            if !face_tag_names.is_empty() {
514                attach_face_tags_to_geometry(result, exec_state, &face_tag_names);
515            }
516        }
517
518        coerce_result_type(result, self, exec_state).map(|r| r.map(KclValue::continue_))
519    }
520}
521
522impl FunctionBody {
523    fn prep_mem(&self, exec_state: &mut ExecState) -> Result<(), KclError> {
524        match self {
525            FunctionBody::Rust(_) => exec_state.mut_stack().push_new_root_env(true),
526            FunctionBody::Kcl(memory) => exec_state.mut_stack().push_new_env_for_call(*memory),
527        }
528    }
529}
530
531fn originates_from_sketch_block(value: &KclValue) -> bool {
532    match value {
533        KclValue::Uuid { .. } => false,
534        KclValue::Bool { .. } => false,
535        KclValue::Number { .. } => false,
536        KclValue::String { .. } => false,
537        KclValue::SketchVar { .. } => true,
538        KclValue::SketchConstraint { .. } => true,
539        KclValue::Tuple { value, .. } => value.iter().all(originates_from_sketch_block),
540        KclValue::HomArray { value, .. } => value.iter().all(originates_from_sketch_block),
541        // TODO: sketch block result should return true.
542        KclValue::Object { value, .. } => value.values().all(originates_from_sketch_block),
543        KclValue::TagIdentifier(_) => false,
544        KclValue::TagDeclarator(_) => false,
545        KclValue::GdtAnnotation { .. } => false,
546        KclValue::Plane { .. } => false,
547        KclValue::Face { .. } => false,
548        KclValue::BoundedEdge { .. } => false,
549        KclValue::Segment { .. } => true,
550        KclValue::Sketch { value: sketch } => sketch.origin_sketch_id.is_some(),
551        KclValue::Solid { value: solid } => solid
552            .sketch()
553            .map(|sketch| sketch.origin_sketch_id.is_some())
554            .unwrap_or(false),
555        KclValue::Helix { .. } => false,
556        KclValue::ImportedGeometry(_) => false,
557        KclValue::Function { .. } => false,
558        KclValue::Module { .. } => false,
559        KclValue::Type { .. } => false,
560        KclValue::KclNone { .. } => false,
561    }
562}
563
564fn face_tag_names_for_call(fn_def: &FunctionSource, args: &Args<Desugared>) -> Vec<String> {
565    let Some(std_props) = &fn_def.std_props else {
566        return Vec::new();
567    };
568
569    if !std_function_allows_face_tags(&std_props.name) {
570        return Vec::new();
571    }
572
573    args.labeled
574        .iter()
575        .filter(|(label, _)| matches!(label.as_str(), "tag" | "tagStart" | "tagEnd"))
576        .filter_map(|(_, arg)| match &arg.value {
577            KclValue::TagDeclarator(tag) => Some(tag.name.clone()),
578            _ => None,
579        })
580        .collect()
581}
582
583fn std_function_allows_face_tags(std_fn_name: &str) -> bool {
584    matches!(
585        std_fn_name,
586        "std::sketch::extrude"
587            | "std::solid::chamfer"
588            | "std::solid::fillet"
589            | "std::sketch::sweep"
590            | "std::sketch::loft"
591            | "std::sketch::revolve"
592    )
593}
594
595fn attach_face_tags_to_geometry(result: &mut KclValue, exec_state: &ExecState, tag_names: &[String]) {
596    match result {
597        KclValue::Solid { value } => attach_face_tags_to_solid(value, exec_state, tag_names),
598        KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
599            for v in value {
600                attach_face_tags_to_geometry(v, exec_state, tag_names);
601            }
602        }
603        _ => {}
604    }
605}
606
607fn attach_face_tags_to_solid(solid: &mut Solid, exec_state: &ExecState, tag_names: &[String]) {
608    let surfaces = solid.value.clone();
609    for surface in surfaces {
610        let Some(tag) = surface.get_tag() else {
611            continue;
612        };
613        if !tag_names.iter().any(|tag_name| tag_name == &tag.name) {
614            continue;
615        }
616
617        let tag_id = solid
618            .sketch()
619            .and_then(|sketch| sketch.tags.get(&tag.name))
620            .cloned()
621            .unwrap_or_else(|| {
622                let mut solid_copy = solid.clone();
623                clear_tags_from_solid_copy(&mut solid_copy);
624                TagIdentifier {
625                    value: tag.name.clone(),
626                    info: vec![(
627                        exec_state.stack().current_epoch(),
628                        TagEngineInfo {
629                            id: surface.get_id(),
630                            surface: Some(surface.clone()),
631                            path: None,
632                            geometry: Geometry::Solid(solid_copy),
633                        },
634                    )],
635                    meta: vec![Metadata {
636                        source_range: tag.clone().into(),
637                    }],
638                }
639            });
640
641        match solid.faces.get_mut(&tag.name) {
642            Some(existing_tag) => existing_tag.merge_info(&tag_id),
643            None => {
644                solid.faces.insert(tag.name.clone(), tag_id);
645            }
646        }
647    }
648}
649
650fn clear_tags_from_solid_copy(solid: &mut Solid) {
651    if let Some(sketch) = solid.sketch_mut() {
652        sketch.tags.clear(); // Avoid recursive tags.
653    }
654    solid.faces.clear();
655}
656
657fn update_memory_for_tags_of_geometry(result: &mut KclValue, exec_state: &mut ExecState) -> Result<(), KclError> {
658    let is_sketch_block = originates_from_sketch_block(&*result);
659    // If the return result is a sketch or solid, we want to update the
660    // memory for the tags of the group.
661    // TODO: This could probably be done in a better way, but as of now this was my only idea
662    // and it works.
663    match result {
664        KclValue::Sketch { value } if !is_sketch_block => {
665            for (name, tag) in value.tags.iter() {
666                if exec_state.stack().cur_frame_contains(name)? {
667                    exec_state.mut_stack().update(name, |v, _| {
668                        if let Some(existing_tag) = v.as_mut_tag() {
669                            existing_tag.merge_info(tag);
670                        }
671                    })?;
672                } else {
673                    exec_state.mut_stack().add(
674                        name.to_owned(),
675                        KclValue::TagIdentifier(Box::new(tag.clone())),
676                        SourceRange::default(),
677                    )?;
678                }
679            }
680        }
681        KclValue::Solid { value } => {
682            let surfaces = value.value.clone();
683            if value.sketch_mut().is_none() {
684                // If the solid isn't based on a sketch, then it doesn't have a tag container,
685                // so there's nothing to do here.
686                return Ok(());
687            };
688            // Now that we know there's work to do (because there's a tag container),
689            // run some clones.
690            let solid_copies: Vec<Box<Solid>> = surfaces.iter().map(|_| value.clone()).collect();
691            // Get the tag container. We expect it to always succeed because we already checked
692            // for a tag container above.
693            let Some(sketch) = value.sketch_mut() else {
694                return Ok(());
695            };
696            for (v, mut solid_copy) in surfaces.iter().zip(solid_copies) {
697                clear_tags_from_solid_copy(&mut solid_copy);
698                if let Some(tag) = v.get_tag() {
699                    // Get the past tag and update it.
700                    let mut is_part_of_sketch = false;
701                    let tag_id = if let Some(t) = sketch.tags.get(&tag.name) {
702                        is_part_of_sketch = true;
703                        let mut t = t.clone();
704                        let Some(info) = t.get_cur_info() else {
705                            return Err(KclError::new_internal(KclErrorDetails::new(
706                                format!("Tag {} does not have path info", tag.name),
707                                vec![tag.into()],
708                            )));
709                        };
710
711                        let mut info = info.clone();
712                        info.id = v.get_id();
713                        info.surface = Some(v.clone());
714                        info.geometry = Geometry::Solid(*solid_copy);
715                        t.info.push((exec_state.stack().current_epoch(), info));
716                        t
717                    } else {
718                        // It's probably a fillet or a chamfer.
719                        // Initialize it.
720                        TagIdentifier {
721                            value: tag.name.clone(),
722                            info: vec![(
723                                exec_state.stack().current_epoch(),
724                                TagEngineInfo {
725                                    id: v.get_id(),
726                                    surface: Some(v.clone()),
727                                    path: None,
728                                    geometry: Geometry::Solid(*solid_copy),
729                                },
730                            )],
731                            meta: vec![Metadata {
732                                source_range: tag.clone().into(),
733                            }],
734                        }
735                    };
736
737                    // update the sketch tags.
738                    sketch.merge_tags(Some(&tag_id).into_iter());
739
740                    if exec_state.stack().cur_frame_contains(&tag.name)? {
741                        exec_state.mut_stack().update(&tag.name, |v, _| {
742                            if let Some(existing_tag) = v.as_mut_tag() {
743                                existing_tag.merge_info(&tag_id);
744                            }
745                        })?;
746                    } else if !is_sketch_block || !is_part_of_sketch {
747                        // The above condition is saying that we add a tag to
748                        // the stack in either of these cases:
749                        //
750                        // 1. It originates from a legacy sketch v1.
751                        //
752                        // 2. It originates from a sketch block and it's not
753                        // part of the sketch. Instead, it's part of the solid,
754                        // as in tagging a cap face `extrude(tagEnd, tagStart)`
755                        // or chamfer face `chamfer(tag)`.
756                        exec_state.mut_stack().add(
757                            tag.name.clone(),
758                            KclValue::TagIdentifier(Box::new(tag_id)),
759                            SourceRange::default(),
760                        )?;
761                    }
762                }
763            }
764
765            // Find the stale sketch in memory and update it.
766            if let Some(sketch) = value.sketch() {
767                if sketch.tags.is_empty() {
768                    return Ok(());
769                }
770                let sketch_tags: Vec<_> = sketch.tags.values().cloned().collect();
771                let sketches_to_update: Vec<_> = exec_state.stack().find_keys_in_current_env(|v| match v {
772                    KclValue::Sketch { value: sk } => sk.original_id == sketch.original_id,
773                    _ => false,
774                })?;
775
776                for k in sketches_to_update {
777                    exec_state.mut_stack().update(&k, |v, _| {
778                        if let Some(sketch) = v.as_mut_sketch() {
779                            sketch.merge_tags(sketch_tags.iter());
780                        }
781                    })?;
782                }
783            }
784        }
785        KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
786            for v in value {
787                update_memory_for_tags_of_geometry(v, exec_state)?;
788            }
789        }
790        _ => {}
791    }
792    Ok(())
793}
794
795fn type_err_str(expected: &Type, found: &KclValue, source_range: &SourceRange, exec_state: &mut ExecState) -> String {
796    fn strip_backticks(s: &str) -> &str {
797        let mut result = s;
798        if s.starts_with('`') {
799            result = &result[1..]
800        }
801        if s.ends_with('`') {
802            result = &result[..result.len() - 1]
803        }
804        result
805    }
806
807    let expected_human = expected.human_friendly_type();
808    let expected_ty = expected.to_string();
809    let expected_str =
810        if expected_human == expected_ty || expected_human == format!("a value with type `{expected_ty}`") {
811            format!("a value with type `{expected_ty}`")
812        } else {
813            format!("{expected_human} (`{expected_ty}`)")
814        };
815    let found_human = found.human_friendly_type();
816    let found_ty = found.principal_type_string();
817    let found_str = if found_human == found_ty || found_human == format!("a {}", strip_backticks(&found_ty)) {
818        format!("a value with type {found_ty}")
819    } else {
820        format!("{found_human} (with type {found_ty})")
821    };
822
823    let mut result = format!("{expected_str}, but found {found_str}.");
824
825    if found.is_unknown_number() {
826        exec_state.clear_units_warnings(source_range);
827        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`.");
828    }
829
830    result
831}
832
833/// Build the error message for a labeled argument whose label doesn't match any
834/// parameter of the callee. Shared between keyword function calls and sketch
835/// blocks so the wording stays consistent.
836pub(crate) fn unexpected_kw_arg_message(label: &str, callee_name: Option<&str>) -> String {
837    format!(
838        "`{label}` is not an argument of {}",
839        callee_name
840            .map(|n| format!("`{n}`"))
841            .unwrap_or_else(|| "this function".to_owned()),
842    )
843}
844
845fn type_check_params_kw(
846    fn_name: Option<&str>,
847    fn_def: &FunctionSource,
848    mut args: Args<Sugary>,
849    exec_state: &mut ExecState,
850) -> Result<Args<Desugared>, KclError> {
851    let fn_name = fn_name.or(args.fn_name.as_deref());
852    let mut result = Args::new_no_args(
853        args.source_range,
854        args.node_path.clone(),
855        args.ctx,
856        fn_name.map(|f| f.to_string()).or_else(|| args.fn_name.clone()),
857    );
858
859    // If it's possible the input arg was meant to be labelled and we probably don't want to use
860    // it as the input arg, then treat it as labelled.
861    if let Some((Some(label), _)) = args.unlabeled.first()
862        && args.unlabeled.len() == 1
863        && (fn_def.input_arg.is_none() || args.pipe_value.is_some())
864        && fn_def.named_args.iter().any(|p| p.0 == label)
865        && !args.labeled.contains_key(label)
866    {
867        let Some((label, arg)) = args.unlabeled.pop() else {
868            let message = "Expected unlabeled arg to be present".to_owned();
869            debug_assert!(false, "{}", &message);
870            return Err(KclError::new_internal(KclErrorDetails::new(
871                message,
872                vec![args.source_range],
873            )));
874        };
875        args.labeled.insert(label.unwrap(), arg);
876    }
877
878    // Apply the `a == a: a` shorthand by desugaring unlabeled args into labeled ones.
879    let (labeled_unlabeled, unlabeled_unlabeled) = args.unlabeled.into_iter().partition(|(l, _)| {
880        if let Some(l) = l
881            && fn_def.named_args.contains_key(l)
882            && !args.labeled.contains_key(l)
883        {
884            true
885        } else {
886            false
887        }
888    });
889    args.unlabeled = unlabeled_unlabeled;
890    for (l, arg) in labeled_unlabeled {
891        let previous = args.labeled.insert(l.unwrap(), arg);
892        debug_assert!(previous.is_none());
893    }
894
895    if let Some((name, ty)) = &fn_def.input_arg {
896        // Expecting an input arg
897
898        if args.unlabeled.is_empty() {
899            // No args provided
900
901            if let Some(pipe) = args.pipe_value {
902                // But there is a pipeline
903                result.unlabeled = vec![(None, pipe)];
904            } else if let Some(arg) = args.labeled.swap_remove(name) {
905                // Mistakenly labelled
906                exec_state.err(CompilationIssue::err(
907                    arg.source_range,
908                    format!(
909                        "{} expects an unlabeled first argument (`@{name}`), but it is labelled in the call. You might try removing the `{name} = `",
910                        fn_name
911                            .map(|n| format!("The function `{n}`"))
912                            .unwrap_or_else(|| "This function".to_owned()),
913                    ),
914                ));
915                result.unlabeled = vec![(Some(name.clone()), arg)];
916            } else {
917                // Just missing
918                return Err(KclError::new_argument(KclErrorDetails::new(
919                    "This function expects an unlabeled first parameter, but you haven't passed it one.".to_owned(),
920                    fn_def.ast.as_source_ranges(),
921                )));
922            }
923        } else if args.unlabeled.len() == 1
924            && let Some(unlabeled_arg) = args.unlabeled.pop()
925        {
926            let mut arg = unlabeled_arg.1;
927            if let Some(ty) = ty {
928                // Suppress warnings about types because they should only be
929                // warned about once for the function definition.
930                let rty = RuntimeType::from_parsed(ty.clone(), exec_state, arg.source_range, false, true)
931                    .map_err(|e| KclError::new_semantic(e.into()))?;
932                arg.value = arg.value.coerce(&rty, true, exec_state).map_err(|_| {
933                    KclError::new_argument(KclErrorDetails::new(
934                        format!(
935                            "The input argument of {} requires {}",
936                            fn_name
937                                .map(|n| format!("`{n}`"))
938                                .unwrap_or_else(|| "this function".to_owned()),
939                            type_err_str(ty, &arg.value, &arg.source_range, exec_state),
940                        ),
941                        vec![arg.source_range],
942                    ))
943                })?;
944            }
945            result.unlabeled = vec![(None, arg)]
946        } else {
947            // Multiple unlabelled args
948
949            // Try to un-spread args into an array
950            if let Some(Type::Array { len, .. }) = ty {
951                if len.satisfied(args.unlabeled.len(), false).is_none() {
952                    exec_state.err(CompilationIssue::err(
953                        args.source_range,
954                        format!(
955                            "{} expects an array input argument with {} elements",
956                            fn_name
957                                .map(|n| format!("The function `{n}`"))
958                                .unwrap_or_else(|| "This function".to_owned()),
959                            len.human_friendly_type(),
960                        ),
961                    ));
962                }
963
964                let source_range = SourceRange::merge(args.unlabeled.iter().map(|(_, a)| a.source_range));
965                exec_state.warn_experimental("array input arguments", source_range);
966                result.unlabeled = vec![(
967                    None,
968                    Arg {
969                        source_range,
970                        value: KclValue::HomArray {
971                            value: args.unlabeled.drain(..).map(|(_, a)| a.value).collect(),
972                            ty: RuntimeType::any(),
973                        },
974                    },
975                )]
976            }
977        }
978    }
979
980    // Either we didn't move the arg above, or we're not expecting one.
981    if !args.unlabeled.is_empty() {
982        // Not expecting an input arg, but found one or more
983        let actuals = args.labeled.keys();
984        let formals: Vec<_> = fn_def
985            .named_args
986            .keys()
987            .filter_map(|name| {
988                if actuals.clone().any(|a| a == name) {
989                    return None;
990                }
991
992                Some(format!("`{name}`"))
993            })
994            .collect();
995
996        let suggestion = if formals.is_empty() {
997            String::new()
998        } else {
999            format!("; suggested labels: {}", formals.join(", "))
1000        };
1001
1002        let mut errors = args.unlabeled.iter().map(|(_, arg)| {
1003            CompilationIssue::err(
1004                arg.source_range,
1005                format!("This argument needs a label, but it doesn't have one{suggestion}"),
1006            )
1007        });
1008
1009        let first = errors.next().unwrap();
1010        errors.for_each(|e| exec_state.err(e));
1011
1012        return Err(KclError::new_argument(first.into()));
1013    }
1014
1015    for (label, mut arg) in args.labeled {
1016        match fn_def.named_args.get(&label) {
1017            Some(NamedParam {
1018                experimental: _,
1019                deprecated: _,
1020                deprecated_since: _,
1021                default_value: def,
1022                ty,
1023            }) => {
1024                // For optional args, passing None should be the same as not passing an arg.
1025                if !(def.is_some() && matches!(arg.value, KclValue::KclNone { .. })) {
1026                    if let Some(ty) = ty {
1027                        // Suppress warnings about types because they should
1028                        // only be warned about once for the function
1029                        // definition.
1030                        let rty = RuntimeType::from_parsed(ty.clone(), exec_state, arg.source_range, false, true)
1031                            .map_err(|e| KclError::new_semantic(e.into()))?;
1032                        arg.value = arg
1033                                .value
1034                                .coerce(
1035                                    &rty,
1036                                    true,
1037                                    exec_state,
1038                                )
1039                                .map_err(|e| {
1040                                    let mut message = format!(
1041                                        "{label} requires {}",
1042                                        type_err_str(ty, &arg.value, &arg.source_range, exec_state),
1043                                    );
1044                                    if let Some(ty) = e.explicit_coercion {
1045                                        // TODO if we have access to the AST for the argument we could choose which example to suggest.
1046                                        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}`");
1047                                    }
1048                                    KclError::new_argument(KclErrorDetails::new(
1049                                        message,
1050                                        vec![arg.source_range],
1051                                    ))
1052                                })?;
1053                    }
1054                    result.labeled.insert(label, arg);
1055                }
1056            }
1057            None => {
1058                exec_state.err(CompilationIssue::err(
1059                    arg.source_range,
1060                    unexpected_kw_arg_message(&label, fn_name),
1061                ));
1062            }
1063        }
1064    }
1065
1066    let consumed_solid_arg_check = fn_def
1067        .std_props
1068        .as_ref()
1069        .map_or(ConsumedSolidArgCheck::Error, |props| props.consumed_solid_arg_check);
1070    match consumed_solid_arg_check {
1071        ConsumedSolidArgCheck::Error => {
1072            result
1073                .unlabeled
1074                .iter()
1075                .map(|(_, arg)| arg)
1076                .chain(result.labeled.values())
1077                .try_for_each(|arg| validate_value_not_consumed(&arg.value, exec_state, arg.source_range))?;
1078        }
1079        ConsumedSolidArgCheck::WarnDeprecated => {
1080            let std_fn_name = fn_def
1081                .std_props
1082                .as_ref()
1083                .map(|props| props.name.as_str())
1084                .unwrap_or("function");
1085            for arg in result
1086                .unlabeled
1087                .iter()
1088                .map(|(_, arg)| arg)
1089                .chain(result.labeled.values())
1090            {
1091                warn_if_value_consumed_for_deprecated_call(&arg.value, exec_state, arg.source_range, std_fn_name)?;
1092            }
1093        }
1094    }
1095
1096    Ok(result)
1097}
1098
1099fn assign_args_to_params_kw(
1100    fn_def: &FunctionSource,
1101    args: Args<Desugared>,
1102    exec_state: &mut ExecState,
1103) -> Result<(), KclError> {
1104    // Add the arguments to the memory.  A new call frame should have already
1105    // been created.
1106    let source_ranges = fn_def.ast.as_source_ranges();
1107
1108    for (name, param) in fn_def.named_args.iter() {
1109        let arg = args.labeled.get(name);
1110        match arg {
1111            Some(arg) => {
1112                exec_state.mut_stack().add(
1113                    name.clone(),
1114                    arg.value.clone(),
1115                    arg.source_ranges().pop().unwrap_or(SourceRange::synthetic()),
1116                )?;
1117            }
1118            None => match &param.default_value {
1119                Some(default_val) => {
1120                    let value = KclValue::from_default_param(default_val.clone(), exec_state);
1121                    exec_state
1122                        .mut_stack()
1123                        .add(name.clone(), value, default_val.source_range())?;
1124                }
1125                None => {
1126                    return Err(KclError::new_argument(KclErrorDetails::new(
1127                        format!("This function requires a parameter {name}, but you haven't passed it one."),
1128                        source_ranges,
1129                    )));
1130                }
1131            },
1132        }
1133    }
1134
1135    if let Some((param_name, _)) = &fn_def.input_arg {
1136        let Some(unlabeled) = args.unlabeled_kw_arg_unconverted() else {
1137            debug_assert!(false, "Bad args");
1138            return Err(KclError::new_internal(KclErrorDetails::new(
1139                "Desugared arguments are inconsistent".to_owned(),
1140                source_ranges,
1141            )));
1142        };
1143        exec_state.mut_stack().add(
1144            param_name.clone(),
1145            unlabeled.value.clone(),
1146            unlabeled.source_ranges().pop().unwrap_or(SourceRange::synthetic()),
1147        )?;
1148    }
1149
1150    Ok(())
1151}
1152
1153fn coerce_result_type(
1154    result: Result<Option<KclValue>, KclError>,
1155    fn_def: &FunctionSource,
1156    exec_state: &mut ExecState,
1157) -> Result<Option<KclValue>, KclError> {
1158    if let Ok(Some(val)) = result {
1159        if let Some(ret_ty) = &fn_def.return_type {
1160            // Suppress warnings about types because they should only be warned
1161            // about once for the function definition.
1162            let ty = RuntimeType::from_parsed(ret_ty.inner.clone(), exec_state, ret_ty.as_source_range(), false, true)
1163                .map_err(|e| KclError::new_semantic(e.into()))?;
1164            let val = val.coerce(&ty, true, exec_state).map_err(|_| {
1165                KclError::new_type(KclErrorDetails::new(
1166                    format!(
1167                        "This function requires its result to be {}",
1168                        type_err_str(ret_ty, &val, &(&val).into(), exec_state)
1169                    ),
1170                    ret_ty.as_source_ranges(),
1171                ))
1172            })?;
1173            Ok(Some(val))
1174        } else {
1175            Ok(Some(val))
1176        }
1177    } else {
1178        result
1179    }
1180}
1181
1182#[cfg(test)]
1183mod test {
1184    use std::sync::Arc;
1185
1186    use super::*;
1187    use crate::engine::engine_manager::EngineManager;
1188    use crate::errors::Severity;
1189    use crate::execution::ContextType;
1190    use crate::execution::EnvironmentRef;
1191    use crate::execution::ExecTestResults;
1192    use crate::execution::memory::Stack;
1193    use crate::execution::parse_execute;
1194    use crate::execution::types::NumericType;
1195    use crate::execution::types::NumericTypeExt;
1196    use crate::parsing::ast::types::DefaultParamVal;
1197    use crate::parsing::ast::types::FunctionExpression;
1198    use crate::parsing::ast::types::Identifier;
1199    use crate::parsing::ast::types::Parameter;
1200    use crate::parsing::ast::types::Program;
1201
1202    fn get_var(result: &ExecTestResults, name: &str) -> KclValue {
1203        result
1204            .exec_state
1205            .stack()
1206            .memory
1207            .get_from_owned(name, result.mem_env, SourceRange::default(), 0)
1208            .unwrap_or_else(|err| panic!("expected variable `{name}` to exist: {err:?}"))
1209    }
1210
1211    fn var_exists(result: &ExecTestResults, name: &str) -> bool {
1212        result
1213            .exec_state
1214            .stack()
1215            .memory
1216            .get_from_owned(name, result.mem_env, SourceRange::default(), 0)
1217            .is_ok()
1218    }
1219
1220    fn assert_vars_are_tags(result: &ExecTestResults, names: &[&str]) {
1221        for name in names {
1222            assert!(
1223                matches!(get_var(result, name), KclValue::TagIdentifier(_)),
1224                "expected variable `{name}` to be a tag identifier"
1225            );
1226        }
1227    }
1228
1229    fn assert_vars_are_missing(result: &ExecTestResults, names: &[&str]) {
1230        for name in names {
1231            assert!(!var_exists(result, name), "expected variable `{name}` to be absent");
1232        }
1233    }
1234
1235    fn assert_body_face_tags(result: &ExecTestResults, expected: &[&str], unexpected: &[&str]) {
1236        let body = get_var(result, "body");
1237        let KclValue::Solid { value: body } = body else {
1238            panic!("expected `body` to be a solid");
1239        };
1240
1241        for tag in expected {
1242            assert!(body.faces.contains_key(*tag), "expected body.faces to contain `{tag}`");
1243        }
1244
1245        for tag in unexpected {
1246            assert!(
1247                !body.faces.contains_key(*tag),
1248                "expected body.faces not to contain sketch tag `{tag}`"
1249            );
1250        }
1251    }
1252
1253    fn deprecated_solid_tag_access_warnings(result: &ExecTestResults) -> Vec<&CompilationIssue> {
1254        result
1255            .exec_state
1256            .issues()
1257            .iter()
1258            .filter(|issue| issue.message.contains("Accessing solid-created face"))
1259            .collect()
1260    }
1261
1262    #[tokio::test(flavor = "multi_thread")]
1263    async fn test_assign_args_to_params() {
1264        // Set up a little framework for this test.
1265        fn mem(number: usize) -> KclValue {
1266            KclValue::Number {
1267                value: number as f64,
1268                ty: NumericType::count(),
1269                meta: Default::default(),
1270            }
1271        }
1272        fn ident(s: &'static str) -> Node<Identifier> {
1273            Node::no_src(Identifier {
1274                name: s.to_owned(),
1275                digest: None,
1276            })
1277        }
1278        fn opt_param(s: &'static str) -> Parameter {
1279            Parameter {
1280                experimental: false,
1281                deprecated: false,
1282                deprecated_since: None,
1283                identifier: ident(s),
1284                param_type: None,
1285                default_value: Some(DefaultParamVal::none()),
1286                labeled: true,
1287                digest: None,
1288            }
1289        }
1290        fn req_param(s: &'static str) -> Parameter {
1291            Parameter {
1292                experimental: false,
1293                deprecated: false,
1294                deprecated_since: None,
1295                identifier: ident(s),
1296                param_type: None,
1297                default_value: None,
1298                labeled: true,
1299                digest: None,
1300            }
1301        }
1302        fn additional_program_memory(items: &[(String, KclValue)]) -> Stack {
1303            let mut program_memory = Stack::new_for_tests();
1304            for (name, item) in items {
1305                program_memory
1306                    .add(name.clone(), item.clone(), SourceRange::default())
1307                    .unwrap();
1308            }
1309            program_memory
1310        }
1311        // Declare the test cases.
1312        for (test_name, params, args, expected) in [
1313            ("empty", Vec::new(), Vec::new(), Ok(additional_program_memory(&[]))),
1314            (
1315                "all params required, and all given, should be OK",
1316                vec![req_param("x")],
1317                vec![("x", mem(1))],
1318                Ok(additional_program_memory(&[("x".to_owned(), mem(1))])),
1319            ),
1320            (
1321                "all params required, none given, should error",
1322                vec![req_param("x")],
1323                vec![],
1324                Err(KclError::new_argument(KclErrorDetails::new(
1325                    "This function requires a parameter x, but you haven't passed it one.".to_owned(),
1326                    vec![SourceRange::default()],
1327                ))),
1328            ),
1329            (
1330                "all params optional, none given, should be OK",
1331                vec![opt_param("x")],
1332                vec![],
1333                Ok(additional_program_memory(&[("x".to_owned(), KclValue::none())])),
1334            ),
1335            (
1336                "mixed params, too few given",
1337                vec![req_param("x"), opt_param("y")],
1338                vec![],
1339                Err(KclError::new_argument(KclErrorDetails::new(
1340                    "This function requires a parameter x, but you haven't passed it one.".to_owned(),
1341                    vec![SourceRange::default()],
1342                ))),
1343            ),
1344            (
1345                "mixed params, minimum given, should be OK",
1346                vec![req_param("x"), opt_param("y")],
1347                vec![("x", mem(1))],
1348                Ok(additional_program_memory(&[
1349                    ("x".to_owned(), mem(1)),
1350                    ("y".to_owned(), KclValue::none()),
1351                ])),
1352            ),
1353            (
1354                "mixed params, maximum given, should be OK",
1355                vec![req_param("x"), opt_param("y")],
1356                vec![("x", mem(1)), ("y", mem(2))],
1357                Ok(additional_program_memory(&[
1358                    ("x".to_owned(), mem(1)),
1359                    ("y".to_owned(), mem(2)),
1360                ])),
1361            ),
1362        ] {
1363            // Run each test.
1364            let func_expr = Node::no_src(FunctionExpression {
1365                name: None,
1366                params,
1367                body: Program::empty(),
1368                return_type: None,
1369                digest: None,
1370            });
1371            let func_src = FunctionSource::kcl(
1372                Box::new(func_expr),
1373                EnvironmentRef::dummy(),
1374                crate::execution::kcl_value::KclFunctionSourceParams {
1375                    std_props: None,
1376                    experimental: false,
1377                    include_in_feature_tree: false,
1378                },
1379            );
1380            let labeled = args
1381                .iter()
1382                .map(|(name, value)| {
1383                    let arg = Arg::new(value.clone(), SourceRange::default());
1384                    ((*name).to_owned(), arg)
1385                })
1386                .collect::<IndexMap<_, _>>();
1387            let exec_ctxt = ExecutorContext {
1388                engine: Arc::new(EngineManager::new_mock()),
1389                engine_batch: crate::engine::EngineBatchContext::default(),
1390                fs: crate::fs::new_file_system_handle(crate::fs::FileManager::new()),
1391                settings: Default::default(),
1392                context_type: ContextType::Mock,
1393                execution_callbacks: Default::default(),
1394            };
1395            let mut exec_state = ExecState::new(&exec_ctxt);
1396            exec_state.mod_local.stack = Stack::new_for_tests();
1397
1398            let args = Args {
1399                fn_name: Some("test".to_owned()),
1400                labeled,
1401                unlabeled: Vec::new(),
1402                source_range: SourceRange::default(),
1403                node_path: None,
1404                ctx: exec_ctxt,
1405                pipe_value: None,
1406                _status: std::marker::PhantomData,
1407            };
1408
1409            let actual = assign_args_to_params_kw(&func_src, args, &mut exec_state).map(|_| exec_state.mod_local.stack);
1410            assert_eq!(
1411                actual, expected,
1412                "failed test '{test_name}':\ngot {actual:?}\nbut expected\n{expected:?}"
1413            );
1414        }
1415    }
1416
1417    #[tokio::test(flavor = "multi_thread")]
1418    async fn type_check_user_args() {
1419        let program = r#"fn makeMessage(prefix: string, suffix: string) {
1420  return prefix + suffix
1421}
1422
1423msg1 = makeMessage(prefix = "world", suffix = " hello")
1424msg2 = makeMessage(prefix = 1, suffix = 3)"#;
1425        let err = parse_execute(program).await.unwrap_err();
1426        assert_eq!(
1427            err.message(),
1428            "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`."
1429        )
1430    }
1431
1432    #[tokio::test(flavor = "multi_thread")]
1433    async fn map_closure_error_mentions_fn_name() {
1434        let program = r#"
1435arr = ["hello"]
1436map(array = arr, f = fn(@item: number) { return item })
1437"#;
1438        let err = parse_execute(program).await.unwrap_err();
1439        assert!(
1440            err.message().contains("map closure"),
1441            "expected map closure errors to include the closure name, got: {}",
1442            err.message()
1443        );
1444    }
1445
1446    #[tokio::test(flavor = "multi_thread")]
1447    async fn array_input_arg() {
1448        let ast = r#"fn f(@input: [mm]) { return 1 }
1449f([1, 2, 3])
1450f(1, 2, 3)
1451"#;
1452        parse_execute(ast).await.unwrap();
1453    }
1454
1455    #[tokio::test(flavor = "multi_thread")]
1456    async fn extrude_tagged_body_gets_face_tags_and_keeps_legacy_bindings() {
1457        let program = r#"@settings(kclVersion = 2.0)
1458profile = sketch(on = XY) {
1459  line1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
1460  line2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
1461  line3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
1462  line4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
1463  coincident([line1.end, line2.start])
1464  coincident([line2.end, line3.start])
1465  coincident([line3.end, line4.start])
1466  coincident([line4.end, line1.start])
1467}
1468region1 = region(point = [5mm, 5mm], sketch = profile)
1469
1470body = extrude(region1, length = 5mm, tagStart = $bottom, tagEnd = $top)
1471bottomFromBody = body.faces.bottom
1472topFromBody = body.faces.top
1473lineFromSketch = region1.tags.line1
1474legacyBottom = bottom
1475legacyTop = top
1476"#;
1477
1478        let result = parse_execute(program).await.unwrap();
1479        assert_body_face_tags(&result, &["bottom", "top"], &["line1"]);
1480        assert_vars_are_tags(
1481            &result,
1482            &[
1483                "bottom",
1484                "top",
1485                "bottomFromBody",
1486                "topFromBody",
1487                "lineFromSketch",
1488                "legacyBottom",
1489                "legacyTop",
1490            ],
1491        );
1492        assert_vars_are_missing(&result, &["line1"]);
1493    }
1494
1495    #[tokio::test(flavor = "multi_thread")]
1496    async fn extrude_without_tag_arguments_does_not_get_face_tags() {
1497        let program = r#"@settings(kclVersion = 2.0)
1498profile = sketch(on = XY) {
1499  line1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
1500  line2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
1501  line3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
1502  line4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
1503  coincident([line1.end, line2.start])
1504  coincident([line2.end, line3.start])
1505  coincident([line3.end, line4.start])
1506  coincident([line4.end, line1.start])
1507}
1508region1 = region(point = [5mm, 5mm], sketch = profile)
1509
1510body = extrude(region1, length = 5mm)
1511"#;
1512
1513        let result = parse_execute(program).await.unwrap();
1514        let body = get_var(&result, "body");
1515        let KclValue::Solid { value: body } = body else {
1516            panic!("expected `body` to be a solid");
1517        };
1518
1519        assert!(
1520            body.faces.is_empty(),
1521            "body faces should only be populated for tagged calls"
1522        );
1523    }
1524
1525    #[tokio::test(flavor = "multi_thread")]
1526    async fn revolve_tagged_body_gets_face_tags() {
1527        let program = r#"@settings(kclVersion = 2.0)
1528profile = sketch(on = XY) {
1529  side = line(start = [var 5mm, var 0mm], end = [var 5mm, var 10mm])
1530  line2 = line(start = [var 5mm, var 10mm], end = [var 6mm, var 10mm])
1531  line3 = line(start = [var 6mm, var 10mm], end = [var 6mm, var 0mm])
1532  line4 = line(start = [var 6mm, var 0mm], end = [var 5mm, var 0mm])
1533  coincident([side.end, line2.start])
1534  coincident([line2.end, line3.start])
1535  coincident([line3.end, line4.start])
1536  coincident([line4.end, side.start])
1537}
1538region1 = region(point = [5.5mm, 5mm], sketch = profile)
1539
1540body = revolve(region1, axis = Y, angle = 90deg, tagStart = $startCap, tagEnd = $endCap)
1541startFromBody = body.faces.startCap
1542endFromBody = body.faces.endCap
1543sideFromSketch = region1.tags.side
1544legacyStart = startCap
1545legacyEnd = endCap
1546"#;
1547
1548        let result = parse_execute(program).await.unwrap();
1549        assert_body_face_tags(&result, &["startCap", "endCap"], &["side"]);
1550        assert_vars_are_tags(
1551            &result,
1552            &[
1553                "startCap",
1554                "endCap",
1555                "startFromBody",
1556                "endFromBody",
1557                "sideFromSketch",
1558                "legacyStart",
1559                "legacyEnd",
1560            ],
1561        );
1562        assert_vars_are_missing(&result, &["side"]);
1563    }
1564
1565    #[tokio::test(flavor = "multi_thread")]
1566    async fn sweep_tagged_body_gets_face_tags() {
1567        let program = r#"@settings(kclVersion = 2.0)
1568profile = sketch(on = XZ) {
1569  edge1 = line(start = [var 0mm, var 0mm], end = [var 2mm, var 0mm])
1570  edge2 = line(start = [var 2mm, var 0mm], end = [var 2mm, var 2mm])
1571  edge3 = line(start = [var 2mm, var 2mm], end = [var 0mm, var 2mm])
1572  edge4 = line(start = [var 0mm, var 2mm], end = [var 0mm, var 0mm])
1573  coincident([edge1.end, edge2.start])
1574  coincident([edge2.end, edge3.start])
1575  coincident([edge3.end, edge4.start])
1576  coincident([edge4.end, edge1.start])
1577}
1578profileRegion = region(point = [1mm, 1mm], sketch = profile)
1579
1580pathSketch = sketch(on = offsetPlane(YZ, offset = -2mm)) {
1581  pathLine = line(start = [var 0mm, var 0mm], end = [var 0mm, var 5mm])
1582}
1583
1584body = sweep(profileRegion, path = pathSketch.pathLine, tagStart = $startCap, tagEnd = $endCap)
1585startFromBody = body.faces.startCap
1586endFromBody = body.faces.endCap
1587edgeFromSketch = profileRegion.tags.edge1
1588pathFromSketch = pathSketch.pathLine
1589legacyStart = startCap
1590legacyEnd = endCap
1591"#;
1592
1593        let result = parse_execute(program).await.unwrap();
1594        assert_body_face_tags(&result, &["startCap", "endCap"], &["edge1", "pathLine"]);
1595        assert_vars_are_tags(
1596            &result,
1597            &[
1598                "startCap",
1599                "endCap",
1600                "startFromBody",
1601                "endFromBody",
1602                "edgeFromSketch",
1603                "legacyStart",
1604                "legacyEnd",
1605            ],
1606        );
1607        assert_vars_are_missing(&result, &["edge1", "pathLine"]);
1608    }
1609
1610    #[tokio::test(flavor = "multi_thread")]
1611    async fn loft_tagged_body_gets_face_tags() {
1612        let program = r#"@settings(kclVersion = 2.0)
1613lowerProfile = sketch(on = XY) {
1614  edge1 = line(start = [var 0mm, var 0mm], end = [var 6mm, var 0mm])
1615  edge2 = line(start = [var 6mm, var 0mm], end = [var 6mm, var 4mm])
1616  edge3 = line(start = [var 6mm, var 4mm], end = [var 0mm, var 4mm])
1617  edge4 = line(start = [var 0mm, var 4mm], end = [var 0mm, var 0mm])
1618  coincident([edge1.end, edge2.start])
1619  coincident([edge2.end, edge3.start])
1620  coincident([edge3.end, edge4.start])
1621  coincident([edge4.end, edge1.start])
1622}
1623lowerRegion = region(point = [3mm, 2mm], sketch = lowerProfile)
1624
1625upperProfile = sketch(on = offsetPlane(XY, offset = 8mm)) {
1626  edge5 = line(start = [var 1mm, var 1mm], end = [var 5mm, var 1mm])
1627  edge6 = line(start = [var 5mm, var 1mm], end = [var 4mm, var 3mm])
1628  edge7 = line(start = [var 4mm, var 3mm], end = [var 2mm, var 3mm])
1629  edge8 = line(start = [var 2mm, var 3mm], end = [var 1mm, var 1mm])
1630  coincident([edge5.end, edge6.start])
1631  coincident([edge6.end, edge7.start])
1632  coincident([edge7.end, edge8.start])
1633  coincident([edge8.end, edge5.start])
1634}
1635upperRegion = region(point = [3mm, 2mm], sketch = upperProfile)
1636
1637body = loft([lowerRegion, upperRegion], tagStart = $startCap, tagEnd = $endCap)
1638startFromBody = body.faces.startCap
1639endFromBody = body.faces.endCap
1640edgeFromSketch = lowerRegion.tags.edge1
1641legacyStart = startCap
1642legacyEnd = endCap
1643"#;
1644
1645        let result = parse_execute(program).await.unwrap();
1646        assert_body_face_tags(&result, &["startCap", "endCap"], &["edge1"]);
1647        assert_vars_are_tags(
1648            &result,
1649            &[
1650                "startCap",
1651                "endCap",
1652                "startFromBody",
1653                "endFromBody",
1654                "edgeFromSketch",
1655                "legacyStart",
1656                "legacyEnd",
1657            ],
1658        );
1659        assert_vars_are_missing(&result, &["edge1"]);
1660    }
1661
1662    #[tokio::test(flavor = "multi_thread")]
1663    async fn chamfer_tagged_body_gets_face_tags() {
1664        let program = r#"@settings(kclVersion = 2.0)
1665profile = sketch(on = XY) {
1666  edge1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
1667  edge2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
1668  edge3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
1669  edge4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
1670  coincident([edge1.end, edge2.start])
1671  coincident([edge2.end, edge3.start])
1672  coincident([edge3.end, edge4.start])
1673  coincident([edge4.end, edge1.start])
1674}
1675profileRegion = region(point = [5mm, 5mm], sketch = profile)
1676
1677base = extrude(profileRegion, length = 5mm, tagEnd = $top)
1678body = chamfer(base, tags = getCommonEdge(faces = [profileRegion.tags.edge1, top]), length = 1mm, tag = $chamferFace)
1679chamferFromBody = body.faces.chamferFace
1680topFromBody = body.faces.top
1681edgeFromSketch = profileRegion.tags.edge1
1682legacyChamfer = chamferFace
1683legacyTop = top
1684"#;
1685
1686        let result = parse_execute(program).await.unwrap();
1687        assert_body_face_tags(&result, &["top", "chamferFace"], &["edge1"]);
1688        assert_vars_are_tags(
1689            &result,
1690            &[
1691                "top",
1692                "chamferFace",
1693                "chamferFromBody",
1694                "topFromBody",
1695                "edgeFromSketch",
1696                "legacyChamfer",
1697                "legacyTop",
1698            ],
1699        );
1700        assert_vars_are_missing(&result, &["edge1"]);
1701    }
1702
1703    #[tokio::test(flavor = "multi_thread")]
1704    async fn fillet_tagged_body_gets_face_tags() {
1705        let program = r#"@settings(kclVersion = 2.0)
1706profile = sketch(on = XY) {
1707  edge1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
1708  edge2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
1709  edge3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
1710  edge4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
1711  coincident([edge1.end, edge2.start])
1712  coincident([edge2.end, edge3.start])
1713  coincident([edge3.end, edge4.start])
1714  coincident([edge4.end, edge1.start])
1715}
1716profileRegion = region(point = [5mm, 5mm], sketch = profile)
1717
1718base = extrude(profileRegion, length = 5mm, tagEnd = $top)
1719body = fillet(base, tags = getCommonEdge(faces = [profileRegion.tags.edge1, top]), radius = 1mm, tag = $filletFace)
1720filletFromBody = body.faces.filletFace
1721topFromBody = body.faces.top
1722edgeFromSketch = profileRegion.tags.edge1
1723legacyFillet = filletFace
1724legacyTop = top
1725"#;
1726
1727        let result = parse_execute(program).await.unwrap();
1728        assert_body_face_tags(&result, &["top", "filletFace"], &["edge1"]);
1729        assert_vars_are_tags(
1730            &result,
1731            &[
1732                "top",
1733                "filletFace",
1734                "filletFromBody",
1735                "topFromBody",
1736                "edgeFromSketch",
1737                "legacyFillet",
1738                "legacyTop",
1739            ],
1740        );
1741        assert_vars_are_missing(&result, &["edge1"]);
1742    }
1743
1744    #[tokio::test(flavor = "multi_thread")]
1745    async fn accessing_body_tag_through_body_sketch_tags_warns() {
1746        let program = r#"@settings(kclVersion = 2.0)
1747profile = startSketchOn(XY)
1748  |> startProfile(at = [0, 0])
1749  |> line(end = [10, 0], tag = $line1)
1750  |> line(end = [0, 10])
1751  |> line(end = [-10, 0])
1752  |> close()
1753
1754body = extrude(profile, length = 5, tagEnd = $top)
1755topFromSketch = body.sketch.tags.top
1756topFromBody = body.faces.top
1757"#;
1758
1759        let result = parse_execute(program).await.unwrap();
1760        assert!(matches!(get_var(&result, "topFromSketch"), KclValue::TagIdentifier(_)));
1761        assert!(matches!(get_var(&result, "topFromBody"), KclValue::TagIdentifier(_)));
1762
1763        let warnings = deprecated_solid_tag_access_warnings(&result);
1764        assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
1765        assert_eq!(warnings[0].severity, Severity::Warning);
1766        assert!(warnings[0].message.contains("`top`"), "found {}", warnings[0].message);
1767        assert!(
1768            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`."),
1769            "found {}",
1770            warnings[0].message
1771        );
1772    }
1773
1774    #[tokio::test(flavor = "multi_thread")]
1775    async fn accessing_sketch_path_tag_through_body_sketch_tags_does_not_warn() {
1776        let program = r#"@settings(kclVersion = 2.0)
1777profile = startSketchOn(XY)
1778  |> startProfile(at = [0, 0])
1779  |> line(end = [10, 0], tag = $line1)
1780  |> line(end = [0, 10])
1781  |> line(end = [-10, 0])
1782  |> close()
1783
1784body = extrude(profile, length = 5, tagEnd = $top)
1785lineFromSketch = body.sketch.tags.line1
1786"#;
1787
1788        let result = parse_execute(program).await.unwrap();
1789        assert!(matches!(get_var(&result, "lineFromSketch"), KclValue::TagIdentifier(_)));
1790        let warnings = deprecated_solid_tag_access_warnings(&result);
1791        assert!(
1792            warnings.is_empty(),
1793            "sketch path tags should not get body-tag deprecation warnings: {warnings:#?}"
1794        );
1795    }
1796
1797    #[tokio::test(flavor = "multi_thread")]
1798    async fn accessing_body_tag_through_sketch_block_region_tags_warns() {
1799        let program = r#"@settings(kclVersion = 2.0)
1800profile = sketch(on = XY) {
1801  line1 = line(start = [0, 0], end = [10, 0])
1802  line2 = line(start = [10, 0], end = [10, 10])
1803  line3 = line(start = [10, 10], end = [0, 10])
1804  line4 = line(start = [0, 10], end = [0, 0])
1805}
1806
1807profileRegion = region(point = [1, 1], sketch = profile)
1808body = extrude(profileRegion, length = 5, tagEnd = $top)
1809topFromRegion = profileRegion.tags.top
1810"#;
1811
1812        let result = parse_execute(program).await.unwrap();
1813        assert!(matches!(get_var(&result, "topFromRegion"), KclValue::TagIdentifier(_)));
1814
1815        let warnings = deprecated_solid_tag_access_warnings(&result);
1816        assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
1817        assert_eq!(warnings[0].severity, Severity::Warning);
1818        assert!(warnings[0].message.contains("`top`"), "found {}", warnings[0].message);
1819    }
1820
1821    fn deprecation_warnings(result: &ExecTestResults) -> Vec<&CompilationIssue> {
1822        result
1823            .exec_state
1824            .issues()
1825            .iter()
1826            .filter(|issue| issue.message.contains("is deprecated"))
1827            .collect()
1828    }
1829
1830    #[tokio::test(flavor = "multi_thread")]
1831    async fn passing_param_deprecated_for_all_versions_warns() {
1832        // `@(deprecated = true)` deprecates the parameter regardless of the KCL
1833        // version, so even on the latest version the call should warn.
1834        let program = r#"@settings(kclVersion = 2.0)
1835fn f(
1836  @a: number,
1837  @(deprecated = true)
1838  oldArg?: number,
1839) {
1840  return a
1841}
1842x = f(1, oldArg = 2)
1843"#;
1844
1845        let result = parse_execute(program).await.unwrap();
1846        let warnings = deprecation_warnings(&result);
1847        assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
1848        assert_eq!(warnings[0].severity, Severity::Warning);
1849        assert!(
1850            warnings[0].message.contains("`f(oldArg)` is deprecated"),
1851            "found {}",
1852            warnings[0].message
1853        );
1854    }
1855
1856    #[tokio::test(flavor = "multi_thread")]
1857    async fn not_passing_deprecated_param_does_not_warn() {
1858        let program = r#"fn f(
1859  @a: number,
1860  @(deprecated = true)
1861  oldArg?: number,
1862) {
1863  return a
1864}
1865x = f(1)
1866"#;
1867
1868        let result = parse_execute(program).await.unwrap();
1869        let warnings = deprecation_warnings(&result);
1870        assert!(
1871            warnings.is_empty(),
1872            "unused deprecated parameter should not warn: {warnings:#?}"
1873        );
1874    }
1875}