Skip to main content

kcl_lib/execution/
fn_call.rs

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