Skip to main content

kcl_lib/execution/
fn_call.rs

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