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