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},
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                let mut solid_copy = value.clone();
470                solid_copy.sketch.tags.clear(); // Avoid recursive tags.
471                if let Some(tag) = v.get_tag() {
472                    // Get the past tag and update it.
473                    let tag_id = if let Some(t) = value.sketch.tags.get(&tag.name) {
474                        let mut t = t.clone();
475                        let Some(info) = t.get_cur_info() else {
476                            return Err(KclError::new_internal(KclErrorDetails::new(
477                                format!("Tag {} does not have path info", tag.name),
478                                vec![tag.into()],
479                            )));
480                        };
481
482                        let mut info = info.clone();
483                        info.surface = Some(v.clone());
484                        info.geometry = Geometry::Solid(*solid_copy);
485                        t.info.push((exec_state.stack().current_epoch(), info));
486                        t
487                    } else {
488                        // It's probably a fillet or a chamfer.
489                        // Initialize it.
490                        TagIdentifier {
491                            value: tag.name.clone(),
492                            info: vec![(
493                                exec_state.stack().current_epoch(),
494                                TagEngineInfo {
495                                    id: v.get_id(),
496                                    surface: Some(v.clone()),
497                                    path: None,
498                                    geometry: Geometry::Solid(*solid_copy),
499                                },
500                            )],
501                            meta: vec![Metadata {
502                                source_range: tag.clone().into(),
503                            }],
504                        }
505                    };
506
507                    // update the sketch tags.
508                    value.sketch.merge_tags(Some(&tag_id).into_iter());
509
510                    if exec_state.stack().cur_frame_contains(&tag.name) {
511                        exec_state.mut_stack().update(&tag.name, |v, _| {
512                            v.as_mut_tag().unwrap().merge_info(&tag_id);
513                        });
514                    } else {
515                        exec_state
516                            .mut_stack()
517                            .add(
518                                tag.name.clone(),
519                                KclValue::TagIdentifier(Box::new(tag_id)),
520                                SourceRange::default(),
521                            )
522                            .unwrap();
523                    }
524                }
525            }
526
527            // Find the stale sketch in memory and update it.
528            if !value.sketch.tags.is_empty() {
529                let sketches_to_update: Vec<_> = exec_state
530                    .stack()
531                    .find_keys_in_current_env(|v| match v {
532                        KclValue::Sketch { value: sk } => sk.original_id == value.sketch.original_id,
533                        _ => false,
534                    })
535                    .cloned()
536                    .collect();
537
538                for k in sketches_to_update {
539                    exec_state.mut_stack().update(&k, |v, _| {
540                        let sketch = v.as_mut_sketch().unwrap();
541                        sketch.merge_tags(value.sketch.tags.values());
542                    });
543                }
544            }
545        }
546        KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
547            for v in value {
548                update_memory_for_tags_of_geometry(v, exec_state)?;
549            }
550        }
551        _ => {}
552    }
553    Ok(())
554}
555
556fn type_err_str(expected: &Type, found: &KclValue, source_range: &SourceRange, exec_state: &mut ExecState) -> String {
557    fn strip_backticks(s: &str) -> &str {
558        let mut result = s;
559        if s.starts_with('`') {
560            result = &result[1..]
561        }
562        if s.ends_with('`') {
563            result = &result[..result.len() - 1]
564        }
565        result
566    }
567
568    let expected_human = expected.human_friendly_type();
569    let expected_ty = expected.to_string();
570    let expected_str =
571        if expected_human == expected_ty || expected_human == format!("a value with type `{expected_ty}`") {
572            format!("a value with type `{expected_ty}`")
573        } else {
574            format!("{expected_human} (`{expected_ty}`)")
575        };
576    let found_human = found.human_friendly_type();
577    let found_ty = found.principal_type_string();
578    let found_str = if found_human == found_ty || found_human == format!("a {}", strip_backticks(&found_ty)) {
579        format!("a value with type {found_ty}")
580    } else {
581        format!("{found_human} (with type {found_ty})")
582    };
583
584    let mut result = format!("{expected_str}, but found {found_str}.");
585
586    if found.is_unknown_number() {
587        exec_state.clear_units_warnings(source_range);
588        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`.");
589    }
590
591    result
592}
593
594fn type_check_params_kw(
595    fn_name: Option<&str>,
596    fn_def: &FunctionSource,
597    mut args: Args<Sugary>,
598    exec_state: &mut ExecState,
599) -> Result<Args<Desugared>, KclError> {
600    let fn_name = fn_name.or(args.fn_name.as_deref());
601    let mut result = Args::new_no_args(
602        args.source_range,
603        args.ctx,
604        fn_name.map(|f| f.to_string()).or_else(|| args.fn_name.clone()),
605    );
606
607    // If it's possible the input arg was meant to be labelled and we probably don't want to use
608    // it as the input arg, then treat it as labelled.
609    if let Some((Some(label), _)) = args.unlabeled.first()
610        && args.unlabeled.len() == 1
611        && (fn_def.input_arg.is_none() || args.pipe_value.is_some())
612        && fn_def.named_args.iter().any(|p| p.0 == label)
613        && !args.labeled.contains_key(label)
614    {
615        let Some((label, arg)) = args.unlabeled.pop() else {
616            let message = "Expected unlabeled arg to be present".to_owned();
617            debug_assert!(false, "{}", &message);
618            return Err(KclError::new_internal(KclErrorDetails::new(
619                message,
620                vec![args.source_range],
621            )));
622        };
623        args.labeled.insert(label.unwrap(), arg);
624    }
625
626    // Apply the `a == a: a` shorthand by desugaring unlabeled args into labeled ones.
627    let (labeled_unlabeled, unlabeled_unlabeled) = args.unlabeled.into_iter().partition(|(l, _)| {
628        if let Some(l) = l
629            && fn_def.named_args.contains_key(l)
630            && !args.labeled.contains_key(l)
631        {
632            true
633        } else {
634            false
635        }
636    });
637    args.unlabeled = unlabeled_unlabeled;
638    for (l, arg) in labeled_unlabeled {
639        let previous = args.labeled.insert(l.unwrap(), arg);
640        debug_assert!(previous.is_none());
641    }
642
643    if let Some((name, ty)) = &fn_def.input_arg {
644        // Expecting an input arg
645
646        if args.unlabeled.is_empty() {
647            // No args provided
648
649            if let Some(pipe) = args.pipe_value {
650                // But there is a pipeline
651                result.unlabeled = vec![(None, pipe)];
652            } else if let Some(arg) = args.labeled.swap_remove(name) {
653                // Mistakenly labelled
654                exec_state.err(CompilationError::err(
655                    arg.source_range,
656                    format!(
657                        "{} expects an unlabeled first argument (`@{name}`), but it is labelled in the call. You might try removing the `{name} = `",
658                        fn_name
659                            .map(|n| format!("The function `{n}`"))
660                            .unwrap_or_else(|| "This function".to_owned()),
661                    ),
662                ));
663                result.unlabeled = vec![(Some(name.clone()), arg)];
664            } else {
665                // Just missing
666                return Err(KclError::new_argument(KclErrorDetails::new(
667                    "This function expects an unlabeled first parameter, but you haven't passed it one.".to_owned(),
668                    fn_def.ast.as_source_ranges(),
669                )));
670            }
671        } else if args.unlabeled.len() == 1
672            && let Some(unlabeled_arg) = args.unlabeled.pop()
673        {
674            let mut arg = unlabeled_arg.1;
675            if let Some(ty) = ty {
676                let rty = RuntimeType::from_parsed(ty.clone(), exec_state, arg.source_range, false)
677                    .map_err(|e| KclError::new_semantic(e.into()))?;
678                arg.value = arg.value.coerce(&rty, true, exec_state).map_err(|_| {
679                    KclError::new_argument(KclErrorDetails::new(
680                        format!(
681                            "The input argument of {} requires {}",
682                            fn_name
683                                .map(|n| format!("`{n}`"))
684                                .unwrap_or_else(|| "this function".to_owned()),
685                            type_err_str(ty, &arg.value, &arg.source_range, exec_state),
686                        ),
687                        vec![arg.source_range],
688                    ))
689                })?;
690            }
691            result.unlabeled = vec![(None, arg)]
692        } else {
693            // Multiple unlabelled args
694
695            // Try to un-spread args into an array
696            if let Some(Type::Array { len, .. }) = ty {
697                if len.satisfied(args.unlabeled.len(), false).is_none() {
698                    exec_state.err(CompilationError::err(
699                        args.source_range,
700                        format!(
701                            "{} expects an array input argument with {} elements",
702                            fn_name
703                                .map(|n| format!("The function `{n}`"))
704                                .unwrap_or_else(|| "This function".to_owned()),
705                            len.human_friendly_type(),
706                        ),
707                    ));
708                }
709
710                let source_range = SourceRange::merge(args.unlabeled.iter().map(|(_, a)| a.source_range));
711                exec_state.warn_experimental("array input arguments", source_range);
712                result.unlabeled = vec![(
713                    None,
714                    Arg {
715                        source_range,
716                        value: KclValue::HomArray {
717                            value: args.unlabeled.drain(..).map(|(_, a)| a.value).collect(),
718                            ty: RuntimeType::any(),
719                        },
720                    },
721                )]
722            }
723        }
724    }
725
726    // Either we didn't move the arg above, or we're not expecting one.
727    if !args.unlabeled.is_empty() {
728        // Not expecting an input arg, but found one or more
729        let actuals = args.labeled.keys();
730        let formals: Vec<_> = fn_def
731            .named_args
732            .keys()
733            .filter_map(|name| {
734                if actuals.clone().any(|a| a == name) {
735                    return None;
736                }
737
738                Some(format!("`{name}`"))
739            })
740            .collect();
741
742        let suggestion = if formals.is_empty() {
743            String::new()
744        } else {
745            format!("; suggested labels: {}", formals.join(", "))
746        };
747
748        let mut errors = args.unlabeled.iter().map(|(_, arg)| {
749            CompilationError::err(
750                arg.source_range,
751                format!("This argument needs a label, but it doesn't have one{suggestion}"),
752            )
753        });
754
755        let first = errors.next().unwrap();
756        errors.for_each(|e| exec_state.err(e));
757
758        return Err(KclError::new_argument(first.into()));
759    }
760
761    for (label, mut arg) in args.labeled {
762        match fn_def.named_args.get(&label) {
763            Some((def, ty)) => {
764                // For optional args, passing None should be the same as not passing an arg.
765                if !(def.is_some() && matches!(arg.value, KclValue::KclNone { .. })) {
766                    if let Some(ty) = ty {
767                        let rty = RuntimeType::from_parsed(ty.clone(), exec_state, arg.source_range, false)
768                            .map_err(|e| KclError::new_semantic(e.into()))?;
769                        arg.value = arg
770                                .value
771                                .coerce(
772                                    &rty,
773                                    true,
774                                    exec_state,
775                                )
776                                .map_err(|e| {
777                                    let mut message = format!(
778                                        "{label} requires {}",
779                                        type_err_str(ty, &arg.value, &arg.source_range, exec_state),
780                                    );
781                                    if let Some(ty) = e.explicit_coercion {
782                                        // TODO if we have access to the AST for the argument we could choose which example to suggest.
783                                        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}`");
784                                    }
785                                    KclError::new_argument(KclErrorDetails::new(
786                                        message,
787                                        vec![arg.source_range],
788                                    ))
789                                })?;
790                    }
791                    result.labeled.insert(label, arg);
792                }
793            }
794            None => {
795                exec_state.err(CompilationError::err(
796                    arg.source_range,
797                    format!(
798                        "`{label}` is not an argument of {}",
799                        fn_name
800                            .map(|n| format!("`{n}`"))
801                            .unwrap_or_else(|| "this function".to_owned()),
802                    ),
803                ));
804            }
805        }
806    }
807
808    Ok(result)
809}
810
811fn assign_args_to_params_kw(
812    fn_def: &FunctionSource,
813    args: Args<Desugared>,
814    exec_state: &mut ExecState,
815) -> Result<(), KclError> {
816    // Add the arguments to the memory.  A new call frame should have already
817    // been created.
818    let source_ranges = fn_def.ast.as_source_ranges();
819
820    for (name, (default, _)) in fn_def.named_args.iter() {
821        let arg = args.labeled.get(name);
822        match arg {
823            Some(arg) => {
824                exec_state.mut_stack().add(
825                    name.clone(),
826                    arg.value.clone(),
827                    arg.source_ranges().pop().unwrap_or(SourceRange::synthetic()),
828                )?;
829            }
830            None => match default {
831                Some(default_val) => {
832                    let value = KclValue::from_default_param(default_val.clone(), exec_state);
833                    exec_state
834                        .mut_stack()
835                        .add(name.clone(), value, default_val.source_range())?;
836                }
837                None => {
838                    return Err(KclError::new_argument(KclErrorDetails::new(
839                        format!("This function requires a parameter {name}, but you haven't passed it one."),
840                        source_ranges,
841                    )));
842                }
843            },
844        }
845    }
846
847    if let Some((param_name, _)) = &fn_def.input_arg {
848        let Some(unlabeled) = args.unlabeled_kw_arg_unconverted() else {
849            debug_assert!(false, "Bad args");
850            return Err(KclError::new_internal(KclErrorDetails::new(
851                "Desugared arguments are inconsistent".to_owned(),
852                source_ranges,
853            )));
854        };
855        exec_state.mut_stack().add(
856            param_name.clone(),
857            unlabeled.value.clone(),
858            unlabeled.source_ranges().pop().unwrap_or(SourceRange::synthetic()),
859        )?;
860    }
861
862    Ok(())
863}
864
865fn coerce_result_type(
866    result: Result<Option<KclValue>, KclError>,
867    fn_def: &FunctionSource,
868    exec_state: &mut ExecState,
869) -> Result<Option<KclValue>, KclError> {
870    if let Ok(Some(val)) = result {
871        if let Some(ret_ty) = &fn_def.return_type {
872            let ty = RuntimeType::from_parsed(ret_ty.inner.clone(), exec_state, ret_ty.as_source_range(), false)
873                .map_err(|e| KclError::new_semantic(e.into()))?;
874            let val = val.coerce(&ty, true, exec_state).map_err(|_| {
875                KclError::new_type(KclErrorDetails::new(
876                    format!(
877                        "This function requires its result to be {}",
878                        type_err_str(ret_ty, &val, &(&val).into(), exec_state)
879                    ),
880                    ret_ty.as_source_ranges(),
881                ))
882            })?;
883            Ok(Some(val))
884        } else {
885            Ok(Some(val))
886        }
887    } else {
888        result
889    }
890}
891
892#[cfg(test)]
893mod test {
894    use std::sync::Arc;
895
896    use super::*;
897    use crate::{
898        execution::{ContextType, EnvironmentRef, memory::Stack, parse_execute, types::NumericType},
899        parsing::ast::types::{DefaultParamVal, FunctionExpression, Identifier, Parameter, Program},
900    };
901
902    #[tokio::test(flavor = "multi_thread")]
903    async fn test_assign_args_to_params() {
904        // Set up a little framework for this test.
905        fn mem(number: usize) -> KclValue {
906            KclValue::Number {
907                value: number as f64,
908                ty: NumericType::count(),
909                meta: Default::default(),
910            }
911        }
912        fn ident(s: &'static str) -> Node<Identifier> {
913            Node::no_src(Identifier {
914                name: s.to_owned(),
915                digest: None,
916            })
917        }
918        fn opt_param(s: &'static str) -> Parameter {
919            Parameter {
920                identifier: ident(s),
921                param_type: None,
922                default_value: Some(DefaultParamVal::none()),
923                labeled: true,
924                digest: None,
925            }
926        }
927        fn req_param(s: &'static str) -> Parameter {
928            Parameter {
929                identifier: ident(s),
930                param_type: None,
931                default_value: None,
932                labeled: true,
933                digest: None,
934            }
935        }
936        fn additional_program_memory(items: &[(String, KclValue)]) -> Stack {
937            let mut program_memory = Stack::new_for_tests();
938            for (name, item) in items {
939                program_memory
940                    .add(name.clone(), item.clone(), SourceRange::default())
941                    .unwrap();
942            }
943            program_memory
944        }
945        // Declare the test cases.
946        for (test_name, params, args, expected) in [
947            ("empty", Vec::new(), Vec::new(), Ok(additional_program_memory(&[]))),
948            (
949                "all params required, and all given, should be OK",
950                vec![req_param("x")],
951                vec![("x", mem(1))],
952                Ok(additional_program_memory(&[("x".to_owned(), mem(1))])),
953            ),
954            (
955                "all params required, none given, should error",
956                vec![req_param("x")],
957                vec![],
958                Err(KclError::new_argument(KclErrorDetails::new(
959                    "This function requires a parameter x, but you haven't passed it one.".to_owned(),
960                    vec![SourceRange::default()],
961                ))),
962            ),
963            (
964                "all params optional, none given, should be OK",
965                vec![opt_param("x")],
966                vec![],
967                Ok(additional_program_memory(&[("x".to_owned(), KclValue::none())])),
968            ),
969            (
970                "mixed params, too few given",
971                vec![req_param("x"), opt_param("y")],
972                vec![],
973                Err(KclError::new_argument(KclErrorDetails::new(
974                    "This function requires a parameter x, but you haven't passed it one.".to_owned(),
975                    vec![SourceRange::default()],
976                ))),
977            ),
978            (
979                "mixed params, minimum given, should be OK",
980                vec![req_param("x"), opt_param("y")],
981                vec![("x", mem(1))],
982                Ok(additional_program_memory(&[
983                    ("x".to_owned(), mem(1)),
984                    ("y".to_owned(), KclValue::none()),
985                ])),
986            ),
987            (
988                "mixed params, maximum given, should be OK",
989                vec![req_param("x"), opt_param("y")],
990                vec![("x", mem(1)), ("y", mem(2))],
991                Ok(additional_program_memory(&[
992                    ("x".to_owned(), mem(1)),
993                    ("y".to_owned(), mem(2)),
994                ])),
995            ),
996        ] {
997            // Run each test.
998            let func_expr = Node::no_src(FunctionExpression {
999                name: None,
1000                params,
1001                body: Program::empty(),
1002                return_type: None,
1003                digest: None,
1004            });
1005            let func_src = FunctionSource::kcl(
1006                Box::new(func_expr),
1007                EnvironmentRef::dummy(),
1008                crate::execution::kcl_value::KclFunctionSourceParams {
1009                    is_std: false,
1010                    experimental: false,
1011                    include_in_feature_tree: false,
1012                },
1013            );
1014            let labeled = args
1015                .iter()
1016                .map(|(name, value)| {
1017                    let arg = Arg::new(value.clone(), SourceRange::default());
1018                    ((*name).to_owned(), arg)
1019                })
1020                .collect::<IndexMap<_, _>>();
1021            let exec_ctxt = ExecutorContext {
1022                engine: Arc::new(Box::new(crate::engine::conn_mock::EngineConnection::new().unwrap())),
1023                fs: Arc::new(crate::fs::FileManager::new()),
1024                settings: Default::default(),
1025                context_type: ContextType::Mock,
1026            };
1027            let mut exec_state = ExecState::new(&exec_ctxt);
1028            exec_state.mod_local.stack = Stack::new_for_tests();
1029
1030            let args = Args {
1031                fn_name: Some("test".to_owned()),
1032                labeled,
1033                unlabeled: Vec::new(),
1034                source_range: SourceRange::default(),
1035                ctx: exec_ctxt,
1036                pipe_value: None,
1037                _status: std::marker::PhantomData,
1038            };
1039
1040            let actual = assign_args_to_params_kw(&func_src, args, &mut exec_state).map(|_| exec_state.mod_local.stack);
1041            assert_eq!(
1042                actual, expected,
1043                "failed test '{test_name}':\ngot {actual:?}\nbut expected\n{expected:?}"
1044            );
1045        }
1046    }
1047
1048    #[tokio::test(flavor = "multi_thread")]
1049    async fn type_check_user_args() {
1050        let program = r#"fn makeMessage(prefix: string, suffix: string) {
1051  return prefix + suffix
1052}
1053
1054msg1 = makeMessage(prefix = "world", suffix = " hello")
1055msg2 = makeMessage(prefix = 1, suffix = 3)"#;
1056        let err = parse_execute(program).await.unwrap_err();
1057        assert_eq!(
1058            err.message(),
1059            "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`."
1060        )
1061    }
1062
1063    #[tokio::test(flavor = "multi_thread")]
1064    async fn map_closure_error_mentions_fn_name() {
1065        let program = r#"
1066arr = ["hello"]
1067map(array = arr, f = fn(@item: number) { return item })
1068"#;
1069        let err = parse_execute(program).await.unwrap_err();
1070        assert!(
1071            err.message().contains("map closure"),
1072            "expected map closure errors to include the closure name, got: {}",
1073            err.message()
1074        );
1075    }
1076
1077    #[tokio::test(flavor = "multi_thread")]
1078    async fn array_input_arg() {
1079        let ast = r#"fn f(@input: [mm]) { return 1 }
1080f([1, 2, 3])
1081f(1, 2, 3)
1082"#;
1083        parse_execute(ast).await.unwrap();
1084    }
1085}