Skip to main content

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, Geometry, KclValue, KclValueControlFlow, Metadata, StatementKind,
9        TagEngineInfo, TagIdentifier, annotations,
10        cad_op::{Group, OpArg, OpKclValue, Operation},
11        control_continue,
12        kcl_value::{FunctionBody, FunctionSource, NamedParam},
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        // Warn if experimental arguments are used after desugaring.
279        for (label, arg) in &args.labeled {
280            if let Some(param) = self.named_args.get(label.as_str())
281                && param.experimental
282            {
283                exec_state.warn_experimental(
284                    &match &fn_name {
285                        Some(f) => format!("`{f}({label})`"),
286                        None => label.to_owned(),
287                    },
288                    arg.source_range,
289                );
290            }
291        }
292
293        // Don't early return until the stack frame is popped!
294        self.body.prep_mem(exec_state);
295
296        // Some function calls might get added to the feature tree.
297        // We do this by adding an "operation".
298
299        // Don't add operations if the KCL code being executed is
300        // just the KCL stdlib calling other KCL stdlib,
301        // because the stdlib internals aren't relevant to users,
302        // that would just be pointless noise.
303        //
304        // Do add operations if the KCL being executed is
305        // user-defined, or the calling code is user-defined,
306        // because that's relevant to the user.
307        let would_trace_stdlib_internals = exec_state.mod_local.inside_stdlib && self.is_std;
308        // self.include_in_feature_tree is set by the KCL annotation `@(feature_tree = true)`.
309        let should_track_operation = !would_trace_stdlib_internals && self.include_in_feature_tree;
310        let op = if should_track_operation {
311            let op_labeled_args = args
312                .labeled
313                .iter()
314                .map(|(k, arg)| (k.clone(), OpArg::new(OpKclValue::from(&arg.value), arg.source_range)))
315                .collect();
316
317            // If you're calling a stdlib function, track that call as an operation.
318            if self.is_std {
319                Some(Operation::StdLibCall {
320                    name: fn_name.clone().unwrap_or_else(|| "unknown function".to_owned()),
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                    node_path: NodePath::placeholder(),
326                    source_range: callsite,
327                    stdlib_entry_source_range: exec_state.mod_local.stdlib_entry_source_range,
328                    is_error: false,
329                })
330            } else {
331                // Otherwise, you're calling a user-defined function, track that call as an operation.
332                exec_state.push_op(Operation::GroupBegin {
333                    group: Group::FunctionCall {
334                        name: fn_name.clone(),
335                        function_source_range: self.ast.as_source_range(),
336                        unlabeled_arg: args
337                            .unlabeled_kw_arg_unconverted()
338                            .map(|arg| OpArg::new(OpKclValue::from(&arg.value), arg.source_range)),
339                        labeled_args: op_labeled_args,
340                    },
341                    node_path: NodePath::placeholder(),
342                    source_range: callsite,
343                });
344
345                None
346            }
347        } else {
348            None
349        };
350
351        let is_calling_into_stdlib = match &self.body {
352            FunctionBody::Rust(_) => true,
353            FunctionBody::Kcl(_) => self.is_std,
354        };
355        let is_crossing_into_stdlib = is_calling_into_stdlib && !exec_state.mod_local.inside_stdlib;
356        let is_crossing_out_of_stdlib = !is_calling_into_stdlib && exec_state.mod_local.inside_stdlib;
357        let stdlib_entry_source_range = if is_crossing_into_stdlib {
358            // When we're calling into the stdlib, for example calling hole(),
359            // track the location so that any further stdlib calls like
360            // subtract() can point to the hole() call. The frontend needs this.
361            Some(callsite)
362        } else if is_crossing_out_of_stdlib {
363            // When map() calls a user-defined function, and it calls extrude()
364            // for example, we want it to point the the extrude() call, not
365            // the map() call.
366            None
367        } else {
368            // When we're not crossing the stdlib boundary, keep the previous
369            // value.
370            exec_state.mod_local.stdlib_entry_source_range
371        };
372
373        let prev_inside_stdlib = std::mem::replace(&mut exec_state.mod_local.inside_stdlib, is_calling_into_stdlib);
374        let prev_stdlib_entry_source_range = std::mem::replace(
375            &mut exec_state.mod_local.stdlib_entry_source_range,
376            stdlib_entry_source_range,
377        );
378        // Do not early return via ? or something until we've
379        // - put this `prev_inside_stdlib` value back.
380        // - called the pop_env.
381        let result = match &self.body {
382            FunctionBody::Rust(f) => f(exec_state, args).await.map(Some),
383            FunctionBody::Kcl(_) => {
384                if let Err(e) = assign_args_to_params_kw(self, args, exec_state) {
385                    exec_state.mod_local.inside_stdlib = prev_inside_stdlib;
386                    exec_state.mut_stack().pop_env();
387                    return Err(e);
388                }
389
390                ctx.exec_block(&self.ast.body, exec_state, BodyType::Block)
391                    .await
392                    .map(|cf| {
393                        if let Some(cf) = cf
394                            && cf.is_some_return()
395                        {
396                            return Some(cf);
397                        }
398                        // Ignore the block's value and extract the return value
399                        // from memory.
400                        exec_state
401                            .stack()
402                            .get(memory::RETURN_NAME, self.ast.as_source_range())
403                            .ok()
404                            .cloned()
405                            .map(KclValue::continue_)
406                    })
407            }
408        };
409        exec_state.mod_local.inside_stdlib = prev_inside_stdlib;
410        exec_state.mod_local.stdlib_entry_source_range = prev_stdlib_entry_source_range;
411        exec_state.mut_stack().pop_env();
412
413        if should_track_operation {
414            if let Some(mut op) = op {
415                op.set_std_lib_call_is_error(result.is_err());
416                // Track call operation.  We do this after the call
417                // since things like patternTransform may call user code
418                // before running, and we will likely want to use the
419                // return value. The call takes ownership of the args,
420                // so we need to build the op before the call.
421                exec_state.push_op(op);
422            } else if !is_calling_into_stdlib {
423                exec_state.push_op(Operation::GroupEnd);
424            }
425        }
426
427        let mut result = match result {
428            Ok(Some(value)) => {
429                if value.is_some_return() {
430                    return Ok(Some(value));
431                } else {
432                    Ok(Some(value.into_value()))
433                }
434            }
435            Ok(None) => Ok(None),
436            Err(e) => Err(e),
437        };
438
439        if self.is_std
440            && let Ok(Some(result)) = &mut result
441        {
442            update_memory_for_tags_of_geometry(result, exec_state)?;
443        }
444
445        coerce_result_type(result, self, exec_state).map(|r| r.map(KclValue::continue_))
446    }
447}
448
449impl FunctionBody {
450    fn prep_mem(&self, exec_state: &mut ExecState) {
451        match self {
452            FunctionBody::Rust(_) => exec_state.mut_stack().push_new_root_env(true),
453            FunctionBody::Kcl(memory) => exec_state.mut_stack().push_new_env_for_call(*memory),
454        }
455    }
456}
457
458fn update_memory_for_tags_of_geometry(result: &mut KclValue, exec_state: &mut ExecState) -> Result<(), KclError> {
459    // If the return result is a sketch or solid, we want to update the
460    // memory for the tags of the group.
461    // TODO: This could probably be done in a better way, but as of now this was my only idea
462    // and it works.
463    match result {
464        KclValue::Sketch { value } => {
465            for (name, tag) in value.tags.iter() {
466                if exec_state.stack().cur_frame_contains(name) {
467                    exec_state.mut_stack().update(name, |v, _| {
468                        v.as_mut_tag().unwrap().merge_info(tag);
469                    });
470                } else {
471                    exec_state
472                        .mut_stack()
473                        .add(
474                            name.to_owned(),
475                            KclValue::TagIdentifier(Box::new(tag.clone())),
476                            SourceRange::default(),
477                        )
478                        .unwrap();
479                }
480            }
481        }
482        KclValue::Solid { value } => {
483            for v in &value.value {
484                let mut solid_copy = value.clone();
485                solid_copy.sketch.tags.clear(); // Avoid recursive tags.
486                if let Some(tag) = v.get_tag() {
487                    // Get the past tag and update it.
488                    let tag_id = if let Some(t) = value.sketch.tags.get(&tag.name) {
489                        let mut t = t.clone();
490                        let Some(info) = t.get_cur_info() else {
491                            return Err(KclError::new_internal(KclErrorDetails::new(
492                                format!("Tag {} does not have path info", tag.name),
493                                vec![tag.into()],
494                            )));
495                        };
496
497                        let mut info = info.clone();
498                        info.surface = Some(v.clone());
499                        info.geometry = Geometry::Solid(*solid_copy);
500                        t.info.push((exec_state.stack().current_epoch(), info));
501                        t
502                    } else {
503                        // It's probably a fillet or a chamfer.
504                        // Initialize it.
505                        TagIdentifier {
506                            value: tag.name.clone(),
507                            info: vec![(
508                                exec_state.stack().current_epoch(),
509                                TagEngineInfo {
510                                    id: v.get_id(),
511                                    surface: Some(v.clone()),
512                                    path: None,
513                                    geometry: Geometry::Solid(*solid_copy),
514                                },
515                            )],
516                            meta: vec![Metadata {
517                                source_range: tag.clone().into(),
518                            }],
519                        }
520                    };
521
522                    // update the sketch tags.
523                    value.sketch.merge_tags(Some(&tag_id).into_iter());
524
525                    if exec_state.stack().cur_frame_contains(&tag.name) {
526                        exec_state.mut_stack().update(&tag.name, |v, _| {
527                            v.as_mut_tag().unwrap().merge_info(&tag_id);
528                        });
529                    } else {
530                        exec_state
531                            .mut_stack()
532                            .add(
533                                tag.name.clone(),
534                                KclValue::TagIdentifier(Box::new(tag_id)),
535                                SourceRange::default(),
536                            )
537                            .unwrap();
538                    }
539                }
540            }
541
542            // Find the stale sketch in memory and update it.
543            if !value.sketch.tags.is_empty() {
544                let sketches_to_update: Vec<_> = exec_state
545                    .stack()
546                    .find_keys_in_current_env(|v| match v {
547                        KclValue::Sketch { value: sk } => sk.original_id == value.sketch.original_id,
548                        _ => false,
549                    })
550                    .cloned()
551                    .collect();
552
553                for k in sketches_to_update {
554                    exec_state.mut_stack().update(&k, |v, _| {
555                        let sketch = v.as_mut_sketch().unwrap();
556                        sketch.merge_tags(value.sketch.tags.values());
557                    });
558                }
559            }
560        }
561        KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
562            for v in value {
563                update_memory_for_tags_of_geometry(v, exec_state)?;
564            }
565        }
566        _ => {}
567    }
568    Ok(())
569}
570
571fn type_err_str(expected: &Type, found: &KclValue, source_range: &SourceRange, exec_state: &mut ExecState) -> String {
572    fn strip_backticks(s: &str) -> &str {
573        let mut result = s;
574        if s.starts_with('`') {
575            result = &result[1..]
576        }
577        if s.ends_with('`') {
578            result = &result[..result.len() - 1]
579        }
580        result
581    }
582
583    let expected_human = expected.human_friendly_type();
584    let expected_ty = expected.to_string();
585    let expected_str =
586        if expected_human == expected_ty || expected_human == format!("a value with type `{expected_ty}`") {
587            format!("a value with type `{expected_ty}`")
588        } else {
589            format!("{expected_human} (`{expected_ty}`)")
590        };
591    let found_human = found.human_friendly_type();
592    let found_ty = found.principal_type_string();
593    let found_str = if found_human == found_ty || found_human == format!("a {}", strip_backticks(&found_ty)) {
594        format!("a value with type {found_ty}")
595    } else {
596        format!("{found_human} (with type {found_ty})")
597    };
598
599    let mut result = format!("{expected_str}, but found {found_str}.");
600
601    if found.is_unknown_number() {
602        exec_state.clear_units_warnings(source_range);
603        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`.");
604    }
605
606    result
607}
608
609fn type_check_params_kw(
610    fn_name: Option<&str>,
611    fn_def: &FunctionSource,
612    mut args: Args<Sugary>,
613    exec_state: &mut ExecState,
614) -> Result<Args<Desugared>, KclError> {
615    let fn_name = fn_name.or(args.fn_name.as_deref());
616    let mut result = Args::new_no_args(
617        args.source_range,
618        args.ctx,
619        fn_name.map(|f| f.to_string()).or_else(|| args.fn_name.clone()),
620    );
621
622    // If it's possible the input arg was meant to be labelled and we probably don't want to use
623    // it as the input arg, then treat it as labelled.
624    if let Some((Some(label), _)) = args.unlabeled.first()
625        && args.unlabeled.len() == 1
626        && (fn_def.input_arg.is_none() || args.pipe_value.is_some())
627        && fn_def.named_args.iter().any(|p| p.0 == label)
628        && !args.labeled.contains_key(label)
629    {
630        let Some((label, arg)) = args.unlabeled.pop() else {
631            let message = "Expected unlabeled arg to be present".to_owned();
632            debug_assert!(false, "{}", &message);
633            return Err(KclError::new_internal(KclErrorDetails::new(
634                message,
635                vec![args.source_range],
636            )));
637        };
638        args.labeled.insert(label.unwrap(), arg);
639    }
640
641    // Apply the `a == a: a` shorthand by desugaring unlabeled args into labeled ones.
642    let (labeled_unlabeled, unlabeled_unlabeled) = args.unlabeled.into_iter().partition(|(l, _)| {
643        if let Some(l) = l
644            && fn_def.named_args.contains_key(l)
645            && !args.labeled.contains_key(l)
646        {
647            true
648        } else {
649            false
650        }
651    });
652    args.unlabeled = unlabeled_unlabeled;
653    for (l, arg) in labeled_unlabeled {
654        let previous = args.labeled.insert(l.unwrap(), arg);
655        debug_assert!(previous.is_none());
656    }
657
658    if let Some((name, ty)) = &fn_def.input_arg {
659        // Expecting an input arg
660
661        if args.unlabeled.is_empty() {
662            // No args provided
663
664            if let Some(pipe) = args.pipe_value {
665                // But there is a pipeline
666                result.unlabeled = vec![(None, pipe)];
667            } else if let Some(arg) = args.labeled.swap_remove(name) {
668                // Mistakenly labelled
669                exec_state.err(CompilationError::err(
670                    arg.source_range,
671                    format!(
672                        "{} expects an unlabeled first argument (`@{name}`), but it is labelled in the call. You might try removing the `{name} = `",
673                        fn_name
674                            .map(|n| format!("The function `{n}`"))
675                            .unwrap_or_else(|| "This function".to_owned()),
676                    ),
677                ));
678                result.unlabeled = vec![(Some(name.clone()), arg)];
679            } else {
680                // Just missing
681                return Err(KclError::new_argument(KclErrorDetails::new(
682                    "This function expects an unlabeled first parameter, but you haven't passed it one.".to_owned(),
683                    fn_def.ast.as_source_ranges(),
684                )));
685            }
686        } else if args.unlabeled.len() == 1
687            && let Some(unlabeled_arg) = args.unlabeled.pop()
688        {
689            let mut arg = unlabeled_arg.1;
690            if let Some(ty) = ty {
691                let rty = RuntimeType::from_parsed(ty.clone(), exec_state, arg.source_range, false)
692                    .map_err(|e| KclError::new_semantic(e.into()))?;
693                arg.value = arg.value.coerce(&rty, true, exec_state).map_err(|_| {
694                    KclError::new_argument(KclErrorDetails::new(
695                        format!(
696                            "The input argument of {} requires {}",
697                            fn_name
698                                .map(|n| format!("`{n}`"))
699                                .unwrap_or_else(|| "this function".to_owned()),
700                            type_err_str(ty, &arg.value, &arg.source_range, exec_state),
701                        ),
702                        vec![arg.source_range],
703                    ))
704                })?;
705            }
706            result.unlabeled = vec![(None, arg)]
707        } else {
708            // Multiple unlabelled args
709
710            // Try to un-spread args into an array
711            if let Some(Type::Array { len, .. }) = ty {
712                if len.satisfied(args.unlabeled.len(), false).is_none() {
713                    exec_state.err(CompilationError::err(
714                        args.source_range,
715                        format!(
716                            "{} expects an array input argument with {} elements",
717                            fn_name
718                                .map(|n| format!("The function `{n}`"))
719                                .unwrap_or_else(|| "This function".to_owned()),
720                            len.human_friendly_type(),
721                        ),
722                    ));
723                }
724
725                let source_range = SourceRange::merge(args.unlabeled.iter().map(|(_, a)| a.source_range));
726                exec_state.warn_experimental("array input arguments", source_range);
727                result.unlabeled = vec![(
728                    None,
729                    Arg {
730                        source_range,
731                        value: KclValue::HomArray {
732                            value: args.unlabeled.drain(..).map(|(_, a)| a.value).collect(),
733                            ty: RuntimeType::any(),
734                        },
735                    },
736                )]
737            }
738        }
739    }
740
741    // Either we didn't move the arg above, or we're not expecting one.
742    if !args.unlabeled.is_empty() {
743        // Not expecting an input arg, but found one or more
744        let actuals = args.labeled.keys();
745        let formals: Vec<_> = fn_def
746            .named_args
747            .keys()
748            .filter_map(|name| {
749                if actuals.clone().any(|a| a == name) {
750                    return None;
751                }
752
753                Some(format!("`{name}`"))
754            })
755            .collect();
756
757        let suggestion = if formals.is_empty() {
758            String::new()
759        } else {
760            format!("; suggested labels: {}", formals.join(", "))
761        };
762
763        let mut errors = args.unlabeled.iter().map(|(_, arg)| {
764            CompilationError::err(
765                arg.source_range,
766                format!("This argument needs a label, but it doesn't have one{suggestion}"),
767            )
768        });
769
770        let first = errors.next().unwrap();
771        errors.for_each(|e| exec_state.err(e));
772
773        return Err(KclError::new_argument(first.into()));
774    }
775
776    for (label, mut arg) in args.labeled {
777        match fn_def.named_args.get(&label) {
778            Some(NamedParam {
779                experimental: _,
780                default_value: def,
781                ty,
782            }) => {
783                // For optional args, passing None should be the same as not passing an arg.
784                if !(def.is_some() && matches!(arg.value, KclValue::KclNone { .. })) {
785                    if let Some(ty) = ty {
786                        let rty = RuntimeType::from_parsed(ty.clone(), exec_state, arg.source_range, false)
787                            .map_err(|e| KclError::new_semantic(e.into()))?;
788                        arg.value = arg
789                                .value
790                                .coerce(
791                                    &rty,
792                                    true,
793                                    exec_state,
794                                )
795                                .map_err(|e| {
796                                    let mut message = format!(
797                                        "{label} requires {}",
798                                        type_err_str(ty, &arg.value, &arg.source_range, exec_state),
799                                    );
800                                    if let Some(ty) = e.explicit_coercion {
801                                        // TODO if we have access to the AST for the argument we could choose which example to suggest.
802                                        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}`");
803                                    }
804                                    KclError::new_argument(KclErrorDetails::new(
805                                        message,
806                                        vec![arg.source_range],
807                                    ))
808                                })?;
809                    }
810                    result.labeled.insert(label, arg);
811                }
812            }
813            None => {
814                exec_state.err(CompilationError::err(
815                    arg.source_range,
816                    format!(
817                        "`{label}` is not an argument of {}",
818                        fn_name
819                            .map(|n| format!("`{n}`"))
820                            .unwrap_or_else(|| "this function".to_owned()),
821                    ),
822                ));
823            }
824        }
825    }
826
827    Ok(result)
828}
829
830fn assign_args_to_params_kw(
831    fn_def: &FunctionSource,
832    args: Args<Desugared>,
833    exec_state: &mut ExecState,
834) -> Result<(), KclError> {
835    // Add the arguments to the memory.  A new call frame should have already
836    // been created.
837    let source_ranges = fn_def.ast.as_source_ranges();
838
839    for (name, param) in fn_def.named_args.iter() {
840        let arg = args.labeled.get(name);
841        match arg {
842            Some(arg) => {
843                exec_state.mut_stack().add(
844                    name.clone(),
845                    arg.value.clone(),
846                    arg.source_ranges().pop().unwrap_or(SourceRange::synthetic()),
847                )?;
848            }
849            None => match &param.default_value {
850                Some(default_val) => {
851                    let value = KclValue::from_default_param(default_val.clone(), exec_state);
852                    exec_state
853                        .mut_stack()
854                        .add(name.clone(), value, default_val.source_range())?;
855                }
856                None => {
857                    return Err(KclError::new_argument(KclErrorDetails::new(
858                        format!("This function requires a parameter {name}, but you haven't passed it one."),
859                        source_ranges,
860                    )));
861                }
862            },
863        }
864    }
865
866    if let Some((param_name, _)) = &fn_def.input_arg {
867        let Some(unlabeled) = args.unlabeled_kw_arg_unconverted() else {
868            debug_assert!(false, "Bad args");
869            return Err(KclError::new_internal(KclErrorDetails::new(
870                "Desugared arguments are inconsistent".to_owned(),
871                source_ranges,
872            )));
873        };
874        exec_state.mut_stack().add(
875            param_name.clone(),
876            unlabeled.value.clone(),
877            unlabeled.source_ranges().pop().unwrap_or(SourceRange::synthetic()),
878        )?;
879    }
880
881    Ok(())
882}
883
884fn coerce_result_type(
885    result: Result<Option<KclValue>, KclError>,
886    fn_def: &FunctionSource,
887    exec_state: &mut ExecState,
888) -> Result<Option<KclValue>, KclError> {
889    if let Ok(Some(val)) = result {
890        if let Some(ret_ty) = &fn_def.return_type {
891            let ty = RuntimeType::from_parsed(ret_ty.inner.clone(), exec_state, ret_ty.as_source_range(), false)
892                .map_err(|e| KclError::new_semantic(e.into()))?;
893            let val = val.coerce(&ty, true, exec_state).map_err(|_| {
894                KclError::new_type(KclErrorDetails::new(
895                    format!(
896                        "This function requires its result to be {}",
897                        type_err_str(ret_ty, &val, &(&val).into(), exec_state)
898                    ),
899                    ret_ty.as_source_ranges(),
900                ))
901            })?;
902            Ok(Some(val))
903        } else {
904            Ok(Some(val))
905        }
906    } else {
907        result
908    }
909}
910
911#[cfg(test)]
912mod test {
913    use std::sync::Arc;
914
915    use super::*;
916    use crate::{
917        execution::{ContextType, EnvironmentRef, memory::Stack, parse_execute, types::NumericType},
918        parsing::ast::types::{DefaultParamVal, FunctionExpression, Identifier, Parameter, Program},
919    };
920
921    #[tokio::test(flavor = "multi_thread")]
922    async fn test_assign_args_to_params() {
923        // Set up a little framework for this test.
924        fn mem(number: usize) -> KclValue {
925            KclValue::Number {
926                value: number as f64,
927                ty: NumericType::count(),
928                meta: Default::default(),
929            }
930        }
931        fn ident(s: &'static str) -> Node<Identifier> {
932            Node::no_src(Identifier {
933                name: s.to_owned(),
934                digest: None,
935            })
936        }
937        fn opt_param(s: &'static str) -> Parameter {
938            Parameter {
939                experimental: false,
940                identifier: ident(s),
941                param_type: None,
942                default_value: Some(DefaultParamVal::none()),
943                labeled: true,
944                digest: None,
945            }
946        }
947        fn req_param(s: &'static str) -> Parameter {
948            Parameter {
949                experimental: false,
950                identifier: ident(s),
951                param_type: None,
952                default_value: None,
953                labeled: true,
954                digest: None,
955            }
956        }
957        fn additional_program_memory(items: &[(String, KclValue)]) -> Stack {
958            let mut program_memory = Stack::new_for_tests();
959            for (name, item) in items {
960                program_memory
961                    .add(name.clone(), item.clone(), SourceRange::default())
962                    .unwrap();
963            }
964            program_memory
965        }
966        // Declare the test cases.
967        for (test_name, params, args, expected) in [
968            ("empty", Vec::new(), Vec::new(), Ok(additional_program_memory(&[]))),
969            (
970                "all params required, and all given, should be OK",
971                vec![req_param("x")],
972                vec![("x", mem(1))],
973                Ok(additional_program_memory(&[("x".to_owned(), mem(1))])),
974            ),
975            (
976                "all params required, none given, should error",
977                vec![req_param("x")],
978                vec![],
979                Err(KclError::new_argument(KclErrorDetails::new(
980                    "This function requires a parameter x, but you haven't passed it one.".to_owned(),
981                    vec![SourceRange::default()],
982                ))),
983            ),
984            (
985                "all params optional, none given, should be OK",
986                vec![opt_param("x")],
987                vec![],
988                Ok(additional_program_memory(&[("x".to_owned(), KclValue::none())])),
989            ),
990            (
991                "mixed params, too few given",
992                vec![req_param("x"), opt_param("y")],
993                vec![],
994                Err(KclError::new_argument(KclErrorDetails::new(
995                    "This function requires a parameter x, but you haven't passed it one.".to_owned(),
996                    vec![SourceRange::default()],
997                ))),
998            ),
999            (
1000                "mixed params, minimum given, should be OK",
1001                vec![req_param("x"), opt_param("y")],
1002                vec![("x", mem(1))],
1003                Ok(additional_program_memory(&[
1004                    ("x".to_owned(), mem(1)),
1005                    ("y".to_owned(), KclValue::none()),
1006                ])),
1007            ),
1008            (
1009                "mixed params, maximum given, should be OK",
1010                vec![req_param("x"), opt_param("y")],
1011                vec![("x", mem(1)), ("y", mem(2))],
1012                Ok(additional_program_memory(&[
1013                    ("x".to_owned(), mem(1)),
1014                    ("y".to_owned(), mem(2)),
1015                ])),
1016            ),
1017        ] {
1018            // Run each test.
1019            let func_expr = Node::no_src(FunctionExpression {
1020                name: None,
1021                params,
1022                body: Program::empty(),
1023                return_type: None,
1024                digest: None,
1025            });
1026            let func_src = FunctionSource::kcl(
1027                Box::new(func_expr),
1028                EnvironmentRef::dummy(),
1029                crate::execution::kcl_value::KclFunctionSourceParams {
1030                    is_std: false,
1031                    experimental: false,
1032                    include_in_feature_tree: false,
1033                },
1034            );
1035            let labeled = args
1036                .iter()
1037                .map(|(name, value)| {
1038                    let arg = Arg::new(value.clone(), SourceRange::default());
1039                    ((*name).to_owned(), arg)
1040                })
1041                .collect::<IndexMap<_, _>>();
1042            let exec_ctxt = ExecutorContext {
1043                engine: Arc::new(Box::new(crate::engine::conn_mock::EngineConnection::new().unwrap())),
1044                fs: Arc::new(crate::fs::FileManager::new()),
1045                settings: Default::default(),
1046                context_type: ContextType::Mock,
1047            };
1048            let mut exec_state = ExecState::new(&exec_ctxt);
1049            exec_state.mod_local.stack = Stack::new_for_tests();
1050
1051            let args = Args {
1052                fn_name: Some("test".to_owned()),
1053                labeled,
1054                unlabeled: Vec::new(),
1055                source_range: SourceRange::default(),
1056                ctx: exec_ctxt,
1057                pipe_value: None,
1058                _status: std::marker::PhantomData,
1059            };
1060
1061            let actual = assign_args_to_params_kw(&func_src, args, &mut exec_state).map(|_| exec_state.mod_local.stack);
1062            assert_eq!(
1063                actual, expected,
1064                "failed test '{test_name}':\ngot {actual:?}\nbut expected\n{expected:?}"
1065            );
1066        }
1067    }
1068
1069    #[tokio::test(flavor = "multi_thread")]
1070    async fn type_check_user_args() {
1071        let program = r#"fn makeMessage(prefix: string, suffix: string) {
1072  return prefix + suffix
1073}
1074
1075msg1 = makeMessage(prefix = "world", suffix = " hello")
1076msg2 = makeMessage(prefix = 1, suffix = 3)"#;
1077        let err = parse_execute(program).await.unwrap_err();
1078        assert_eq!(
1079            err.message(),
1080            "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`."
1081        )
1082    }
1083
1084    #[tokio::test(flavor = "multi_thread")]
1085    async fn map_closure_error_mentions_fn_name() {
1086        let program = r#"
1087arr = ["hello"]
1088map(array = arr, f = fn(@item: number) { return item })
1089"#;
1090        let err = parse_execute(program).await.unwrap_err();
1091        assert!(
1092            err.message().contains("map closure"),
1093            "expected map closure errors to include the closure name, got: {}",
1094            err.message()
1095        );
1096    }
1097
1098    #[tokio::test(flavor = "multi_thread")]
1099    async fn array_input_arg() {
1100        let ast = r#"fn f(@input: [mm]) { return 1 }
1101f([1, 2, 3])
1102f(1, 2, 3)
1103"#;
1104        parse_execute(ast).await.unwrap();
1105    }
1106}