kcl_lib/execution/
fn_call.rs

1use async_recursion::async_recursion;
2use indexmap::IndexMap;
3
4use crate::{
5    CompilationError, NodePath, SourceRange,
6    errors::{KclError, KclErrorDetails},
7    execution::{
8        BodyType, ExecState, ExecutorContext, KclValue, Metadata, StatementKind, TagEngineInfo, TagIdentifier,
9        annotations,
10        cad_op::{Group, OpArg, OpKclValue, Operation},
11        kcl_value::{FunctionBody, FunctionSource},
12        memory,
13        types::RuntimeType,
14    },
15    parsing::ast::types::{CallExpressionKw, Node, Type},
16};
17
18#[derive(Debug, Clone)]
19pub struct Args<Status: ArgsStatus = Desugared> {
20    /// Unlabeled keyword args. Currently only the first formal arg can be unlabeled.
21    /// If the argument was a local variable, then the first element of the tuple is its name
22    /// which may be used to treat this arg as a labelled arg.
23    pub unlabeled: Vec<(Option<String>, Arg)>,
24    /// Labeled args.
25    pub labeled: IndexMap<String, Arg>,
26    pub source_range: SourceRange,
27    pub ctx: ExecutorContext,
28    /// If this call happens inside a pipe (|>) expression, this holds the LHS of that |>.
29    /// Otherwise it's None.
30    pub pipe_value: Option<Arg>,
31    _status: std::marker::PhantomData<Status>,
32}
33
34pub trait ArgsStatus: std::fmt::Debug + Clone {}
35
36#[derive(Debug, Clone)]
37pub struct Sugary;
38impl ArgsStatus for Sugary {}
39
40// Invariants guaranteed by the `Desugared` status:
41// - There is either 0 or 1 unlabeled arguments
42// - Any lableled args are in the labeled map, and not the unlabeled Vec.
43// - The arguments match the type signature of the function exactly
44// - pipe_value.is_none()
45#[derive(Debug, Clone)]
46pub struct Desugared;
47impl ArgsStatus for Desugared {}
48
49impl Args<Sugary> {
50    /// Collect the given keyword arguments.
51    pub fn new(
52        labeled: IndexMap<String, Arg>,
53        unlabeled: Vec<(Option<String>, Arg)>,
54        source_range: SourceRange,
55        exec_state: &mut ExecState,
56        ctx: ExecutorContext,
57    ) -> Args<Sugary> {
58        Args {
59            labeled,
60            unlabeled,
61            source_range,
62            ctx,
63            pipe_value: exec_state.pipe_value().map(|v| Arg::new(v.clone(), source_range)),
64            _status: std::marker::PhantomData,
65        }
66    }
67}
68
69impl<Status: ArgsStatus> Args<Status> {
70    /// How many arguments are there?
71    pub fn len(&self) -> usize {
72        self.labeled.len() + self.unlabeled.len()
73    }
74
75    /// Are there no arguments?
76    pub fn is_empty(&self) -> bool {
77        self.labeled.is_empty() && self.unlabeled.is_empty()
78    }
79}
80
81impl Args<Desugared> {
82    pub fn new_no_args(source_range: SourceRange, ctx: ExecutorContext) -> Args {
83        Args {
84            unlabeled: Default::default(),
85            labeled: Default::default(),
86            source_range,
87            ctx,
88            pipe_value: None,
89            _status: std::marker::PhantomData,
90        }
91    }
92
93    /// Get the unlabeled keyword argument. If not set, returns None.
94    pub(crate) fn unlabeled_kw_arg_unconverted(&self) -> Option<&Arg> {
95        self.unlabeled.first().map(|(_, a)| a)
96    }
97}
98
99#[derive(Debug, Clone)]
100pub struct Arg {
101    /// The evaluated argument.
102    pub value: KclValue,
103    /// The source range of the unevaluated argument.
104    pub source_range: SourceRange,
105}
106
107impl Arg {
108    pub fn new(value: KclValue, source_range: SourceRange) -> Self {
109        Self { value, source_range }
110    }
111
112    pub fn synthetic(value: KclValue) -> Self {
113        Self {
114            value,
115            source_range: SourceRange::synthetic(),
116        }
117    }
118
119    pub fn source_ranges(&self) -> Vec<SourceRange> {
120        vec![self.source_range]
121    }
122}
123
124impl Node<CallExpressionKw> {
125    #[async_recursion]
126    pub async fn execute(&self, exec_state: &mut ExecState, ctx: &ExecutorContext) -> Result<KclValue, KclError> {
127        let fn_name = &self.callee;
128        let callsite: SourceRange = self.into();
129
130        // Clone the function so that we can use a mutable reference to
131        // exec_state.
132        let func: KclValue = fn_name.get_result(exec_state, ctx).await?.clone();
133
134        let Some(fn_src) = func.as_function() else {
135            return Err(KclError::new_semantic(KclErrorDetails::new(
136                "cannot call this because it isn't a function".to_string(),
137                vec![callsite],
138            )));
139        };
140
141        // Build a hashmap from argument labels to the final evaluated values.
142        let mut fn_args = IndexMap::with_capacity(self.arguments.len());
143        let mut unlabeled = Vec::new();
144
145        // Evaluate the unlabeled first param, if any exists.
146        if let Some(ref arg_expr) = self.unlabeled {
147            let source_range = SourceRange::from(arg_expr.clone());
148            let metadata = Metadata { source_range };
149            let value = ctx
150                .execute_expr(arg_expr, exec_state, &metadata, &[], StatementKind::Expression)
151                .await?;
152
153            let label = arg_expr.ident_name().map(str::to_owned);
154
155            unlabeled.push((label, Arg::new(value, source_range)))
156        }
157
158        for arg_expr in &self.arguments {
159            let source_range = SourceRange::from(arg_expr.arg.clone());
160            let metadata = Metadata { source_range };
161            let value = ctx
162                .execute_expr(&arg_expr.arg, exec_state, &metadata, &[], StatementKind::Expression)
163                .await?;
164            let arg = Arg::new(value, source_range);
165            match &arg_expr.label {
166                Some(l) => {
167                    fn_args.insert(l.name.clone(), arg);
168                }
169                None => {
170                    unlabeled.push((arg_expr.arg.ident_name().map(str::to_owned), arg));
171                }
172            }
173        }
174
175        let args = Args::new(fn_args, unlabeled, callsite, exec_state, ctx.clone());
176
177        let return_value = fn_src
178            .call_kw(Some(fn_name.to_string()), exec_state, ctx, args, callsite)
179            .await
180            .map_err(|e| {
181                // Add the call expression to the source ranges.
182                //
183                // TODO: Use the name that the function was defined
184                // with, not the identifier it was used with.
185                e.add_unwind_location(Some(fn_name.name.name.clone()), callsite)
186            })?;
187
188        let result = return_value.ok_or_else(move || {
189            let mut source_ranges: Vec<SourceRange> = vec![callsite];
190            // We want to send the source range of the original function.
191            if let KclValue::Function { meta, .. } = func {
192                source_ranges = meta.iter().map(|m| m.source_range).collect();
193            };
194            KclError::new_undefined_value(
195                KclErrorDetails::new(
196                    format!("Result of user-defined function {fn_name} is undefined"),
197                    source_ranges,
198                ),
199                None,
200            )
201        })?;
202
203        Ok(result)
204    }
205}
206
207impl FunctionSource {
208    pub async fn call_kw(
209        &self,
210        fn_name: Option<String>,
211        exec_state: &mut ExecState,
212        ctx: &ExecutorContext,
213        args: Args<Sugary>,
214        callsite: SourceRange,
215    ) -> Result<Option<KclValue>, KclError> {
216        if self.deprecated {
217            exec_state.warn(
218                CompilationError::err(
219                    callsite,
220                    format!(
221                        "{} is deprecated, see the docs for a recommended replacement",
222                        match &fn_name {
223                            Some(n) => format!("`{n}`"),
224                            None => "This function".to_owned(),
225                        }
226                    ),
227                ),
228                annotations::WARN_DEPRECATED,
229            );
230        }
231        if self.experimental {
232            exec_state.warn_experimental(
233                &match &fn_name {
234                    Some(n) => format!("`{n}`"),
235                    None => "This function".to_owned(),
236                },
237                callsite,
238            );
239        }
240
241        let args = type_check_params_kw(fn_name.as_deref(), self, args, exec_state)?;
242
243        // Don't early return until the stack frame is popped!
244        self.body.prep_mem(exec_state);
245
246        let op = if self.include_in_feature_tree {
247            let op_labeled_args = args
248                .labeled
249                .iter()
250                .map(|(k, arg)| (k.clone(), OpArg::new(OpKclValue::from(&arg.value), arg.source_range)))
251                .collect();
252
253            if self.is_std {
254                Some(Operation::StdLibCall {
255                    name: fn_name.clone().unwrap_or_else(|| "unknown function".to_owned()),
256                    unlabeled_arg: args
257                        .unlabeled_kw_arg_unconverted()
258                        .map(|arg| OpArg::new(OpKclValue::from(&arg.value), arg.source_range)),
259                    labeled_args: op_labeled_args,
260                    node_path: NodePath::placeholder(),
261                    source_range: callsite,
262                    is_error: false,
263                })
264            } else {
265                exec_state.push_op(Operation::GroupBegin {
266                    group: Group::FunctionCall {
267                        name: fn_name.clone(),
268                        function_source_range: self.ast.as_source_range(),
269                        unlabeled_arg: args
270                            .unlabeled_kw_arg_unconverted()
271                            .map(|arg| OpArg::new(OpKclValue::from(&arg.value), arg.source_range)),
272                        labeled_args: op_labeled_args,
273                    },
274                    node_path: NodePath::placeholder(),
275                    source_range: callsite,
276                });
277
278                None
279            }
280        } else {
281            None
282        };
283
284        let mut result = match &self.body {
285            FunctionBody::Rust(f) => f(exec_state, args).await.map(Some),
286            FunctionBody::Kcl(_) => {
287                if let Err(e) = assign_args_to_params_kw(self, args, exec_state) {
288                    exec_state.mut_stack().pop_env();
289                    return Err(e);
290                }
291
292                ctx.exec_block(&self.ast.body, exec_state, BodyType::Block)
293                    .await
294                    .map(|_| {
295                        exec_state
296                            .stack()
297                            .get(memory::RETURN_NAME, self.ast.as_source_range())
298                            .ok()
299                            .cloned()
300                    })
301            }
302        };
303
304        exec_state.mut_stack().pop_env();
305
306        if let Some(mut op) = op {
307            op.set_std_lib_call_is_error(result.is_err());
308            // Track call operation.  We do this after the call
309            // since things like patternTransform may call user code
310            // before running, and we will likely want to use the
311            // return value. The call takes ownership of the args,
312            // so we need to build the op before the call.
313            exec_state.push_op(op);
314        } else if !self.is_std {
315            exec_state.push_op(Operation::GroupEnd);
316        }
317
318        if self.is_std
319            && let Ok(Some(result)) = &mut result
320        {
321            update_memory_for_tags_of_geometry(result, exec_state)?;
322        }
323
324        coerce_result_type(result, self, exec_state)
325    }
326}
327
328impl FunctionBody {
329    fn prep_mem(&self, exec_state: &mut ExecState) {
330        match self {
331            FunctionBody::Rust(_) => exec_state.mut_stack().push_new_root_env(true),
332            FunctionBody::Kcl(memory) => exec_state.mut_stack().push_new_env_for_call(*memory),
333        }
334    }
335}
336
337fn update_memory_for_tags_of_geometry(result: &mut KclValue, exec_state: &mut ExecState) -> Result<(), KclError> {
338    // If the return result is a sketch or solid, we want to update the
339    // memory for the tags of the group.
340    // TODO: This could probably be done in a better way, but as of now this was my only idea
341    // and it works.
342    match result {
343        KclValue::Sketch { value } => {
344            for (name, tag) in value.tags.iter() {
345                if exec_state.stack().cur_frame_contains(name) {
346                    exec_state.mut_stack().update(name, |v, _| {
347                        v.as_mut_tag().unwrap().merge_info(tag);
348                    });
349                } else {
350                    exec_state
351                        .mut_stack()
352                        .add(
353                            name.to_owned(),
354                            KclValue::TagIdentifier(Box::new(tag.clone())),
355                            SourceRange::default(),
356                        )
357                        .unwrap();
358                }
359            }
360        }
361        KclValue::Solid { value } => {
362            for v in &value.value {
363                if let Some(tag) = v.get_tag() {
364                    // Get the past tag and update it.
365                    let tag_id = if let Some(t) = value.sketch.tags.get(&tag.name) {
366                        let mut t = t.clone();
367                        let Some(info) = t.get_cur_info() else {
368                            return Err(KclError::new_internal(KclErrorDetails::new(
369                                format!("Tag {} does not have path info", tag.name),
370                                vec![tag.into()],
371                            )));
372                        };
373
374                        let mut info = info.clone();
375                        info.surface = Some(v.clone());
376                        info.sketch = value.id;
377                        t.info.push((exec_state.stack().current_epoch(), info));
378                        t
379                    } else {
380                        // It's probably a fillet or a chamfer.
381                        // Initialize it.
382                        TagIdentifier {
383                            value: tag.name.clone(),
384                            info: vec![(
385                                exec_state.stack().current_epoch(),
386                                TagEngineInfo {
387                                    id: v.get_id(),
388                                    surface: Some(v.clone()),
389                                    path: None,
390                                    sketch: value.id,
391                                },
392                            )],
393                            meta: vec![Metadata {
394                                source_range: tag.clone().into(),
395                            }],
396                        }
397                    };
398
399                    // update the sketch tags.
400                    value.sketch.merge_tags(Some(&tag_id).into_iter());
401
402                    if exec_state.stack().cur_frame_contains(&tag.name) {
403                        exec_state.mut_stack().update(&tag.name, |v, _| {
404                            v.as_mut_tag().unwrap().merge_info(&tag_id);
405                        });
406                    } else {
407                        exec_state
408                            .mut_stack()
409                            .add(
410                                tag.name.clone(),
411                                KclValue::TagIdentifier(Box::new(tag_id)),
412                                SourceRange::default(),
413                            )
414                            .unwrap();
415                    }
416                }
417            }
418
419            // Find the stale sketch in memory and update it.
420            if !value.sketch.tags.is_empty() {
421                let sketches_to_update: Vec<_> = exec_state
422                    .stack()
423                    .find_keys_in_current_env(|v| match v {
424                        KclValue::Sketch { value: sk } => sk.original_id == value.sketch.original_id,
425                        _ => false,
426                    })
427                    .cloned()
428                    .collect();
429
430                for k in sketches_to_update {
431                    exec_state.mut_stack().update(&k, |v, _| {
432                        let sketch = v.as_mut_sketch().unwrap();
433                        sketch.merge_tags(value.sketch.tags.values());
434                    });
435                }
436            }
437        }
438        KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
439            for v in value {
440                update_memory_for_tags_of_geometry(v, exec_state)?;
441            }
442        }
443        _ => {}
444    }
445    Ok(())
446}
447
448fn type_err_str(expected: &Type, found: &KclValue, source_range: &SourceRange, exec_state: &mut ExecState) -> String {
449    fn strip_backticks(s: &str) -> &str {
450        let mut result = s;
451        if s.starts_with('`') {
452            result = &result[1..]
453        }
454        if s.ends_with('`') {
455            result = &result[..result.len() - 1]
456        }
457        result
458    }
459
460    let expected_human = expected.human_friendly_type();
461    let expected_ty = expected.to_string();
462    let expected_str =
463        if expected_human == expected_ty || expected_human == format!("a value with type `{expected_ty}`") {
464            format!("a value with type `{expected_ty}`")
465        } else {
466            format!("{expected_human} (`{expected_ty}`)")
467        };
468    let found_human = found.human_friendly_type();
469    let found_ty = found.principal_type_string();
470    let found_str = if found_human == found_ty || found_human == format!("a {}", strip_backticks(&found_ty)) {
471        format!("a value with type {found_ty}")
472    } else {
473        format!("{found_human} (with type {found_ty})")
474    };
475
476    let mut result = format!("{expected_str}, but found {found_str}.");
477
478    if found.is_unknown_number() {
479        exec_state.clear_units_warnings(source_range);
480        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`.");
481    }
482
483    result
484}
485
486fn type_check_params_kw(
487    fn_name: Option<&str>,
488    fn_def: &FunctionSource,
489    mut args: Args<Sugary>,
490    exec_state: &mut ExecState,
491) -> Result<Args<Desugared>, KclError> {
492    let mut result = Args::new_no_args(args.source_range, args.ctx);
493
494    // If it's possible the input arg was meant to be labelled and we probably don't want to use
495    // it as the input arg, then treat it as labelled.
496    if let Some((Some(label), _)) = args.unlabeled.first()
497        && args.unlabeled.len() == 1
498        && (fn_def.input_arg.is_none() || args.pipe_value.is_some())
499        && fn_def.named_args.iter().any(|p| p.0 == label)
500        && !args.labeled.contains_key(label)
501    {
502        let (label, arg) = args.unlabeled.pop().unwrap();
503        args.labeled.insert(label.unwrap(), arg);
504    }
505
506    // Apply the `a == a: a` shorthand by desugaring unlabeled args into labeled ones.
507    let (labeled_unlabeled, unlabeled_unlabeled) = args.unlabeled.into_iter().partition(|(l, _)| {
508        if let Some(l) = l
509            && fn_def.named_args.contains_key(l)
510            && !args.labeled.contains_key(l)
511        {
512            true
513        } else {
514            false
515        }
516    });
517    args.unlabeled = unlabeled_unlabeled;
518    for (l, arg) in labeled_unlabeled {
519        let previous = args.labeled.insert(l.unwrap(), arg);
520        debug_assert!(previous.is_none());
521    }
522
523    if let Some((name, ty)) = &fn_def.input_arg {
524        // Expecting an input arg
525
526        if args.unlabeled.is_empty() {
527            // No args provided
528
529            if let Some(pipe) = args.pipe_value {
530                // But there is a pipeline
531                result.unlabeled = vec![(None, pipe)];
532            } else if let Some(arg) = args.labeled.swap_remove(name) {
533                // Mistakenly labelled
534                exec_state.err(CompilationError::err(
535                    arg.source_range,
536                    format!(
537                        "{} expects an unlabeled first argument (`@{name}`), but it is labelled in the call. You might try removing the `{name} = `",
538                        fn_name
539                            .map(|n| format!("The function `{n}`"))
540                            .unwrap_or_else(|| "This function".to_owned()),
541                    ),
542                ));
543                result.unlabeled = vec![(Some(name.clone()), arg)];
544            } else {
545                // Just missing
546                return Err(KclError::new_argument(KclErrorDetails::new(
547                    "This function expects an unlabeled first parameter, but you haven't passed it one.".to_owned(),
548                    fn_def.ast.as_source_ranges(),
549                )));
550            }
551        } else if args.unlabeled.len() == 1 {
552            let mut arg = args.unlabeled.pop().unwrap().1;
553            if let Some(ty) = ty {
554                let rty = RuntimeType::from_parsed(ty.clone(), exec_state, arg.source_range, false)
555                    .map_err(|e| KclError::new_semantic(e.into()))?;
556                arg.value = arg.value.coerce(&rty, true, exec_state).map_err(|_| {
557                    KclError::new_argument(KclErrorDetails::new(
558                        format!(
559                            "The input argument of {} requires {}",
560                            fn_name
561                                .map(|n| format!("`{n}`"))
562                                .unwrap_or_else(|| "this function".to_owned()),
563                            type_err_str(ty, &arg.value, &arg.source_range, exec_state),
564                        ),
565                        vec![arg.source_range],
566                    ))
567                })?;
568            }
569            result.unlabeled = vec![(None, arg)]
570        } else {
571            // Multiple unlabelled args
572
573            // Try to un-spread args into an array
574            if let Some(Type::Array { len, .. }) = ty {
575                if len.satisfied(args.unlabeled.len(), false).is_none() {
576                    exec_state.err(CompilationError::err(
577                        args.source_range,
578                        format!(
579                            "{} expects an array input argument with {} elements",
580                            fn_name
581                                .map(|n| format!("The function `{n}`"))
582                                .unwrap_or_else(|| "This function".to_owned()),
583                            len.human_friendly_type(),
584                        ),
585                    ));
586                }
587
588                let source_range = SourceRange::merge(args.unlabeled.iter().map(|(_, a)| a.source_range));
589                exec_state.warn_experimental("array input arguments", source_range);
590                result.unlabeled = vec![(
591                    None,
592                    Arg {
593                        source_range,
594                        value: KclValue::HomArray {
595                            value: args.unlabeled.drain(..).map(|(_, a)| a.value).collect(),
596                            ty: RuntimeType::any(),
597                        },
598                    },
599                )]
600            }
601        }
602    }
603
604    // Either we didn't move the arg above, or we're not expecting one.
605    if !args.unlabeled.is_empty() {
606        // Not expecting an input arg, but found one or more
607        let actuals = args.labeled.keys();
608        let formals: Vec<_> = fn_def
609            .named_args
610            .keys()
611            .filter_map(|name| {
612                if actuals.clone().any(|a| a == name) {
613                    return None;
614                }
615
616                Some(format!("`{name}`"))
617            })
618            .collect();
619
620        let suggestion = if formals.is_empty() {
621            String::new()
622        } else {
623            format!("; suggested labels: {}", formals.join(", "))
624        };
625
626        let mut errors = args.unlabeled.iter().map(|(_, arg)| {
627            CompilationError::err(
628                arg.source_range,
629                format!("This argument needs a label, but it doesn't have one{suggestion}"),
630            )
631        });
632
633        let first = errors.next().unwrap();
634        errors.for_each(|e| exec_state.err(e));
635
636        return Err(KclError::new_argument(first.into()));
637    }
638
639    for (label, mut arg) in args.labeled {
640        match fn_def.named_args.get(&label) {
641            Some((def, ty)) => {
642                // For optional args, passing None should be the same as not passing an arg.
643                if !(def.is_some() && matches!(arg.value, KclValue::KclNone { .. })) {
644                    if let Some(ty) = ty {
645                        let rty = RuntimeType::from_parsed(ty.clone(), exec_state, arg.source_range, false)
646                            .map_err(|e| KclError::new_semantic(e.into()))?;
647                        arg.value = arg
648                                .value
649                                .coerce(
650                                    &rty,
651                                    true,
652                                    exec_state,
653                                )
654                                .map_err(|e| {
655                                    let mut message = format!(
656                                        "{label} requires {}",
657                                        type_err_str(ty, &arg.value, &arg.source_range, exec_state),
658                                    );
659                                    if let Some(ty) = e.explicit_coercion {
660                                        // TODO if we have access to the AST for the argument we could choose which example to suggest.
661                                        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}`");
662                                    }
663                                    KclError::new_argument(KclErrorDetails::new(
664                                        message,
665                                        vec![arg.source_range],
666                                    ))
667                                })?;
668                    }
669                    result.labeled.insert(label, arg);
670                }
671            }
672            None => {
673                exec_state.err(CompilationError::err(
674                    arg.source_range,
675                    format!(
676                        "`{label}` is not an argument of {}",
677                        fn_name
678                            .map(|n| format!("`{n}`"))
679                            .unwrap_or_else(|| "this function".to_owned()),
680                    ),
681                ));
682            }
683        }
684    }
685
686    Ok(result)
687}
688
689fn assign_args_to_params_kw(
690    fn_def: &FunctionSource,
691    args: Args<Desugared>,
692    exec_state: &mut ExecState,
693) -> Result<(), KclError> {
694    // Add the arguments to the memory.  A new call frame should have already
695    // been created.
696    let source_ranges = fn_def.ast.as_source_ranges();
697
698    for (name, (default, _)) in fn_def.named_args.iter() {
699        let arg = args.labeled.get(name);
700        match arg {
701            Some(arg) => {
702                exec_state.mut_stack().add(
703                    name.clone(),
704                    arg.value.clone(),
705                    arg.source_ranges().pop().unwrap_or(SourceRange::synthetic()),
706                )?;
707            }
708            None => match default {
709                Some(default_val) => {
710                    let value = KclValue::from_default_param(default_val.clone(), exec_state);
711                    exec_state
712                        .mut_stack()
713                        .add(name.clone(), value, default_val.source_range())?;
714                }
715                None => {
716                    return Err(KclError::new_argument(KclErrorDetails::new(
717                        format!("This function requires a parameter {name}, but you haven't passed it one."),
718                        source_ranges,
719                    )));
720                }
721            },
722        }
723    }
724
725    if let Some((param_name, _)) = &fn_def.input_arg {
726        let Some(unlabeled) = args.unlabeled_kw_arg_unconverted() else {
727            debug_assert!(false, "Bad args");
728            return Err(KclError::new_internal(KclErrorDetails::new(
729                "Desugared arguments are inconsistent".to_owned(),
730                source_ranges,
731            )));
732        };
733        exec_state.mut_stack().add(
734            param_name.clone(),
735            unlabeled.value.clone(),
736            unlabeled.source_ranges().pop().unwrap_or(SourceRange::synthetic()),
737        )?;
738    }
739
740    Ok(())
741}
742
743fn coerce_result_type(
744    result: Result<Option<KclValue>, KclError>,
745    fn_def: &FunctionSource,
746    exec_state: &mut ExecState,
747) -> Result<Option<KclValue>, KclError> {
748    if let Ok(Some(val)) = result {
749        if let Some(ret_ty) = &fn_def.return_type {
750            let ty = RuntimeType::from_parsed(ret_ty.inner.clone(), exec_state, ret_ty.as_source_range(), false)
751                .map_err(|e| KclError::new_semantic(e.into()))?;
752            let val = val.coerce(&ty, true, exec_state).map_err(|_| {
753                KclError::new_type(KclErrorDetails::new(
754                    format!(
755                        "This function requires its result to be {}",
756                        type_err_str(ret_ty, &val, &(&val).into(), exec_state)
757                    ),
758                    ret_ty.as_source_ranges(),
759                ))
760            })?;
761            Ok(Some(val))
762        } else {
763            Ok(Some(val))
764        }
765    } else {
766        result
767    }
768}
769
770#[cfg(test)]
771mod test {
772    use std::sync::Arc;
773
774    use super::*;
775    use crate::{
776        execution::{ContextType, EnvironmentRef, memory::Stack, parse_execute, types::NumericType},
777        parsing::ast::types::{DefaultParamVal, FunctionExpression, Identifier, Parameter, Program},
778    };
779
780    #[tokio::test(flavor = "multi_thread")]
781    async fn test_assign_args_to_params() {
782        // Set up a little framework for this test.
783        fn mem(number: usize) -> KclValue {
784            KclValue::Number {
785                value: number as f64,
786                ty: NumericType::count(),
787                meta: Default::default(),
788            }
789        }
790        fn ident(s: &'static str) -> Node<Identifier> {
791            Node::no_src(Identifier {
792                name: s.to_owned(),
793                digest: None,
794            })
795        }
796        fn opt_param(s: &'static str) -> Parameter {
797            Parameter {
798                identifier: ident(s),
799                param_type: None,
800                default_value: Some(DefaultParamVal::none()),
801                labeled: true,
802                digest: None,
803            }
804        }
805        fn req_param(s: &'static str) -> Parameter {
806            Parameter {
807                identifier: ident(s),
808                param_type: None,
809                default_value: None,
810                labeled: true,
811                digest: None,
812            }
813        }
814        fn additional_program_memory(items: &[(String, KclValue)]) -> Stack {
815            let mut program_memory = Stack::new_for_tests();
816            for (name, item) in items {
817                program_memory
818                    .add(name.clone(), item.clone(), SourceRange::default())
819                    .unwrap();
820            }
821            program_memory
822        }
823        // Declare the test cases.
824        for (test_name, params, args, expected) in [
825            ("empty", Vec::new(), Vec::new(), Ok(additional_program_memory(&[]))),
826            (
827                "all params required, and all given, should be OK",
828                vec![req_param("x")],
829                vec![("x", mem(1))],
830                Ok(additional_program_memory(&[("x".to_owned(), mem(1))])),
831            ),
832            (
833                "all params required, none given, should error",
834                vec![req_param("x")],
835                vec![],
836                Err(KclError::new_argument(KclErrorDetails::new(
837                    "This function requires a parameter x, but you haven't passed it one.".to_owned(),
838                    vec![SourceRange::default()],
839                ))),
840            ),
841            (
842                "all params optional, none given, should be OK",
843                vec![opt_param("x")],
844                vec![],
845                Ok(additional_program_memory(&[("x".to_owned(), KclValue::none())])),
846            ),
847            (
848                "mixed params, too few given",
849                vec![req_param("x"), opt_param("y")],
850                vec![],
851                Err(KclError::new_argument(KclErrorDetails::new(
852                    "This function requires a parameter x, but you haven't passed it one.".to_owned(),
853                    vec![SourceRange::default()],
854                ))),
855            ),
856            (
857                "mixed params, minimum given, should be OK",
858                vec![req_param("x"), opt_param("y")],
859                vec![("x", mem(1))],
860                Ok(additional_program_memory(&[
861                    ("x".to_owned(), mem(1)),
862                    ("y".to_owned(), KclValue::none()),
863                ])),
864            ),
865            (
866                "mixed params, maximum given, should be OK",
867                vec![req_param("x"), opt_param("y")],
868                vec![("x", mem(1)), ("y", mem(2))],
869                Ok(additional_program_memory(&[
870                    ("x".to_owned(), mem(1)),
871                    ("y".to_owned(), mem(2)),
872                ])),
873            ),
874        ] {
875            // Run each test.
876            let func_expr = Node::no_src(FunctionExpression {
877                params,
878                body: Program::empty(),
879                return_type: None,
880                digest: None,
881            });
882            let func_src = FunctionSource::kcl(Box::new(func_expr), EnvironmentRef::dummy(), false);
883            let labeled = args
884                .iter()
885                .map(|(name, value)| {
886                    let arg = Arg::new(value.clone(), SourceRange::default());
887                    ((*name).to_owned(), arg)
888                })
889                .collect::<IndexMap<_, _>>();
890            let exec_ctxt = ExecutorContext {
891                engine: Arc::new(Box::new(
892                    crate::engine::conn_mock::EngineConnection::new().await.unwrap(),
893                )),
894                fs: Arc::new(crate::fs::FileManager::new()),
895                settings: Default::default(),
896                context_type: ContextType::Mock,
897            };
898            let mut exec_state = ExecState::new(&exec_ctxt);
899            exec_state.mod_local.stack = Stack::new_for_tests();
900
901            let args = Args {
902                labeled,
903                unlabeled: Vec::new(),
904                source_range: SourceRange::default(),
905                ctx: exec_ctxt,
906                pipe_value: None,
907                _status: std::marker::PhantomData,
908            };
909
910            let actual = assign_args_to_params_kw(&func_src, args, &mut exec_state).map(|_| exec_state.mod_local.stack);
911            assert_eq!(
912                actual, expected,
913                "failed test '{test_name}':\ngot {actual:?}\nbut expected\n{expected:?}"
914            );
915        }
916    }
917
918    #[tokio::test(flavor = "multi_thread")]
919    async fn type_check_user_args() {
920        let program = r#"fn makeMessage(prefix: string, suffix: string) {
921  return prefix + suffix
922}
923
924msg1 = makeMessage(prefix = "world", suffix = " hello")
925msg2 = makeMessage(prefix = 1, suffix = 3)"#;
926        let err = parse_execute(program).await.unwrap_err();
927        assert_eq!(
928            err.message(),
929            "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`."
930        )
931    }
932
933    #[tokio::test(flavor = "multi_thread")]
934    async fn array_input_arg() {
935        let ast = r#"fn f(@input: [mm]) { return 1 }
936f([1, 2, 3])
937f(1, 2, 3)
938"#;
939        parse_execute(ast).await.unwrap();
940    }
941}