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        // Clone the function so that we can use a mutable reference to
169        // exec_state.
170        let func: KclValue = fn_name.get_result(exec_state, ctx).await?.clone();
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                            .cloned()
468                            .map(KclValue::continue_)
469                    })
470            }
471        };
472        exec_state.mod_local.inside_stdlib = prev_inside_stdlib;
473        exec_state.mod_local.stdlib_entry_source_range = prev_stdlib_entry_source_range;
474        exec_state.mut_stack().pop_env();
475
476        if should_track_operation {
477            if let Some(mut op) = op {
478                op.set_std_lib_call_is_error(result.is_err());
479                // Track call operation.  We do this after the call
480                // since things like patternTransform may call user code
481                // before running, and we will likely want to use the
482                // return value. The call takes ownership of the args,
483                // so we need to build the op before the call.
484                exec_state.push_op(op);
485            } else if !is_calling_into_stdlib {
486                exec_state.push_op(Operation::GroupEnd);
487            }
488        }
489
490        let mut result = match result {
491            Ok(Some(value)) => {
492                if value.is_some_return() {
493                    return Ok(Some(value));
494                } else {
495                    Ok(Some(value.into_value()))
496                }
497            }
498            Ok(None) => Ok(None),
499            Err(e) => Err(e),
500        };
501
502        if self.is_std()
503            && let Ok(Some(result)) = &mut result
504        {
505            update_memory_for_tags_of_geometry(result, exec_state)?;
506        }
507
508        coerce_result_type(result, self, exec_state).map(|r| r.map(KclValue::continue_))
509    }
510}
511
512impl FunctionBody {
513    fn prep_mem(&self, exec_state: &mut ExecState) {
514        match self {
515            FunctionBody::Rust(_) => exec_state.mut_stack().push_new_root_env(true),
516            FunctionBody::Kcl(memory) => exec_state.mut_stack().push_new_env_for_call(*memory),
517        }
518    }
519}
520
521fn originates_from_sketch_block(value: &KclValue) -> bool {
522    match value {
523        KclValue::Uuid { .. } => false,
524        KclValue::Bool { .. } => false,
525        KclValue::Number { .. } => false,
526        KclValue::String { .. } => false,
527        KclValue::SketchVar { .. } => true,
528        KclValue::SketchConstraint { .. } => true,
529        KclValue::Tuple { value, .. } => value.iter().all(originates_from_sketch_block),
530        KclValue::HomArray { value, .. } => value.iter().all(originates_from_sketch_block),
531        // TODO: sketch block result should return true.
532        KclValue::Object { value, .. } => value.values().all(originates_from_sketch_block),
533        KclValue::TagIdentifier(_) => false,
534        KclValue::TagDeclarator(_) => false,
535        KclValue::GdtAnnotation { .. } => false,
536        KclValue::Plane { .. } => false,
537        KclValue::Face { .. } => false,
538        KclValue::BoundedEdge { .. } => false,
539        KclValue::Segment { .. } => true,
540        KclValue::Sketch { value: sketch } => sketch.origin_sketch_id.is_some(),
541        KclValue::Solid { value: solid } => solid
542            .sketch()
543            .map(|sketch| sketch.origin_sketch_id.is_some())
544            .unwrap_or(false),
545        KclValue::Helix { .. } => false,
546        KclValue::ImportedGeometry(_) => false,
547        KclValue::Function { .. } => false,
548        KclValue::Module { .. } => false,
549        KclValue::Type { .. } => false,
550        KclValue::KclNone { .. } => false,
551    }
552}
553
554fn update_memory_for_tags_of_geometry(result: &mut KclValue, exec_state: &mut ExecState) -> Result<(), KclError> {
555    let is_sketch_block = originates_from_sketch_block(&*result);
556    // If the return result is a sketch or solid, we want to update the
557    // memory for the tags of the group.
558    // TODO: This could probably be done in a better way, but as of now this was my only idea
559    // and it works.
560    match result {
561        KclValue::Sketch { value } if !is_sketch_block => {
562            for (name, tag) in value.tags.iter() {
563                if exec_state.stack().cur_frame_contains(name) {
564                    exec_state.mut_stack().update(name, |v, _| {
565                        if let Some(existing_tag) = v.as_mut_tag() {
566                            existing_tag.merge_info(tag);
567                        }
568                    });
569                } else {
570                    exec_state
571                        .mut_stack()
572                        .add(
573                            name.to_owned(),
574                            KclValue::TagIdentifier(Box::new(tag.clone())),
575                            SourceRange::default(),
576                        )
577                        .unwrap();
578                }
579            }
580        }
581        KclValue::Solid { value } => {
582            let surfaces = value.value.clone();
583            if value.sketch_mut().is_none() {
584                // If the solid isn't based on a sketch, then it doesn't have a tag container,
585                // so there's nothing to do here.
586                return Ok(());
587            };
588            // Now that we know there's work to do (because there's a tag container),
589            // run some clones.
590            let solid_copies: Vec<Box<Solid>> = surfaces.iter().map(|_| value.clone()).collect();
591            // Get the tag container. We expect it to always succeed because we already checked
592            // for a tag container above.
593            let Some(sketch) = value.sketch_mut() else {
594                return Ok(());
595            };
596            for (v, mut solid_copy) in surfaces.iter().zip(solid_copies) {
597                if let Some(sketch) = solid_copy.sketch_mut() {
598                    sketch.tags.clear(); // Avoid recursive tags.
599                }
600                if let Some(tag) = v.get_tag() {
601                    // Get the past tag and update it.
602                    let mut is_part_of_sketch = false;
603                    let tag_id = if let Some(t) = sketch.tags.get(&tag.name) {
604                        is_part_of_sketch = true;
605                        let mut t = t.clone();
606                        let Some(info) = t.get_cur_info() else {
607                            return Err(KclError::new_internal(KclErrorDetails::new(
608                                format!("Tag {} does not have path info", tag.name),
609                                vec![tag.into()],
610                            )));
611                        };
612
613                        let mut info = info.clone();
614                        info.id = v.get_id();
615                        info.surface = Some(v.clone());
616                        info.geometry = Geometry::Solid(*solid_copy);
617                        t.info.push((exec_state.stack().current_epoch(), info));
618                        t
619                    } else {
620                        // It's probably a fillet or a chamfer.
621                        // Initialize it.
622                        TagIdentifier {
623                            value: tag.name.clone(),
624                            info: vec![(
625                                exec_state.stack().current_epoch(),
626                                TagEngineInfo {
627                                    id: v.get_id(),
628                                    surface: Some(v.clone()),
629                                    path: None,
630                                    geometry: Geometry::Solid(*solid_copy),
631                                },
632                            )],
633                            meta: vec![Metadata {
634                                source_range: tag.clone().into(),
635                            }],
636                        }
637                    };
638
639                    // update the sketch tags.
640                    sketch.merge_tags(Some(&tag_id).into_iter());
641
642                    if exec_state.stack().cur_frame_contains(&tag.name) {
643                        exec_state.mut_stack().update(&tag.name, |v, _| {
644                            if let Some(existing_tag) = v.as_mut_tag() {
645                                existing_tag.merge_info(&tag_id);
646                            }
647                        });
648                    } else if !is_sketch_block || !is_part_of_sketch {
649                        // The above condition is saying that we add a tag to
650                        // the stack in either of these cases:
651                        //
652                        // 1. It originates from a legacy sketch v1.
653                        //
654                        // 2. It originates from a sketch block and it's not
655                        // part of the sketch. Instead, it's part of the solid,
656                        // as in tagging a cap face `extrude(tagEnd, tagStart)`
657                        // or chamfer face `chamfer(tag)`.
658                        exec_state
659                            .mut_stack()
660                            .add(
661                                tag.name.clone(),
662                                KclValue::TagIdentifier(Box::new(tag_id)),
663                                SourceRange::default(),
664                            )
665                            .unwrap();
666                    }
667                }
668            }
669
670            // Find the stale sketch in memory and update it.
671            if let Some(sketch) = value.sketch() {
672                if sketch.tags.is_empty() {
673                    return Ok(());
674                }
675                let sketch_tags: Vec<_> = sketch.tags.values().cloned().collect();
676                let sketches_to_update: Vec<_> = exec_state
677                    .stack()
678                    .find_keys_in_current_env(|v| match v {
679                        KclValue::Sketch { value: sk } => sk.original_id == sketch.original_id,
680                        _ => false,
681                    })
682                    .cloned()
683                    .collect();
684
685                for k in sketches_to_update {
686                    exec_state.mut_stack().update(&k, |v, _| {
687                        let sketch = v.as_mut_sketch().unwrap();
688                        sketch.merge_tags(sketch_tags.iter());
689                    });
690                }
691            }
692        }
693        KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
694            for v in value {
695                update_memory_for_tags_of_geometry(v, exec_state)?;
696            }
697        }
698        _ => {}
699    }
700    Ok(())
701}
702
703fn type_err_str(expected: &Type, found: &KclValue, source_range: &SourceRange, exec_state: &mut ExecState) -> String {
704    fn strip_backticks(s: &str) -> &str {
705        let mut result = s;
706        if s.starts_with('`') {
707            result = &result[1..]
708        }
709        if s.ends_with('`') {
710            result = &result[..result.len() - 1]
711        }
712        result
713    }
714
715    let expected_human = expected.human_friendly_type();
716    let expected_ty = expected.to_string();
717    let expected_str =
718        if expected_human == expected_ty || expected_human == format!("a value with type `{expected_ty}`") {
719            format!("a value with type `{expected_ty}`")
720        } else {
721            format!("{expected_human} (`{expected_ty}`)")
722        };
723    let found_human = found.human_friendly_type();
724    let found_ty = found.principal_type_string();
725    let found_str = if found_human == found_ty || found_human == format!("a {}", strip_backticks(&found_ty)) {
726        format!("a value with type {found_ty}")
727    } else {
728        format!("{found_human} (with type {found_ty})")
729    };
730
731    let mut result = format!("{expected_str}, but found {found_str}.");
732
733    if found.is_unknown_number() {
734        exec_state.clear_units_warnings(source_range);
735        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`.");
736    }
737
738    result
739}
740
741fn type_check_params_kw(
742    fn_name: Option<&str>,
743    fn_def: &FunctionSource,
744    mut args: Args<Sugary>,
745    exec_state: &mut ExecState,
746) -> Result<Args<Desugared>, KclError> {
747    let fn_name = fn_name.or(args.fn_name.as_deref());
748    let mut result = Args::new_no_args(
749        args.source_range,
750        args.node_path.clone(),
751        args.ctx,
752        fn_name.map(|f| f.to_string()).or_else(|| args.fn_name.clone()),
753    );
754
755    // If it's possible the input arg was meant to be labelled and we probably don't want to use
756    // it as the input arg, then treat it as labelled.
757    if let Some((Some(label), _)) = args.unlabeled.first()
758        && args.unlabeled.len() == 1
759        && (fn_def.input_arg.is_none() || args.pipe_value.is_some())
760        && fn_def.named_args.iter().any(|p| p.0 == label)
761        && !args.labeled.contains_key(label)
762    {
763        let Some((label, arg)) = args.unlabeled.pop() else {
764            let message = "Expected unlabeled arg to be present".to_owned();
765            debug_assert!(false, "{}", &message);
766            return Err(KclError::new_internal(KclErrorDetails::new(
767                message,
768                vec![args.source_range],
769            )));
770        };
771        args.labeled.insert(label.unwrap(), arg);
772    }
773
774    // Apply the `a == a: a` shorthand by desugaring unlabeled args into labeled ones.
775    let (labeled_unlabeled, unlabeled_unlabeled) = args.unlabeled.into_iter().partition(|(l, _)| {
776        if let Some(l) = l
777            && fn_def.named_args.contains_key(l)
778            && !args.labeled.contains_key(l)
779        {
780            true
781        } else {
782            false
783        }
784    });
785    args.unlabeled = unlabeled_unlabeled;
786    for (l, arg) in labeled_unlabeled {
787        let previous = args.labeled.insert(l.unwrap(), arg);
788        debug_assert!(previous.is_none());
789    }
790
791    if let Some((name, ty)) = &fn_def.input_arg {
792        // Expecting an input arg
793
794        if args.unlabeled.is_empty() {
795            // No args provided
796
797            if let Some(pipe) = args.pipe_value {
798                // But there is a pipeline
799                result.unlabeled = vec![(None, pipe)];
800            } else if let Some(arg) = args.labeled.swap_remove(name) {
801                // Mistakenly labelled
802                exec_state.err(CompilationIssue::err(
803                    arg.source_range,
804                    format!(
805                        "{} expects an unlabeled first argument (`@{name}`), but it is labelled in the call. You might try removing the `{name} = `",
806                        fn_name
807                            .map(|n| format!("The function `{n}`"))
808                            .unwrap_or_else(|| "This function".to_owned()),
809                    ),
810                ));
811                result.unlabeled = vec![(Some(name.clone()), arg)];
812            } else {
813                // Just missing
814                return Err(KclError::new_argument(KclErrorDetails::new(
815                    "This function expects an unlabeled first parameter, but you haven't passed it one.".to_owned(),
816                    fn_def.ast.as_source_ranges(),
817                )));
818            }
819        } else if args.unlabeled.len() == 1
820            && let Some(unlabeled_arg) = args.unlabeled.pop()
821        {
822            let mut arg = unlabeled_arg.1;
823            if let Some(ty) = ty {
824                // Suppress warnings about types because they should only be
825                // warned about once for the function 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.value.coerce(&rty, true, exec_state).map_err(|_| {
829                    KclError::new_argument(KclErrorDetails::new(
830                        format!(
831                            "The input argument of {} requires {}",
832                            fn_name
833                                .map(|n| format!("`{n}`"))
834                                .unwrap_or_else(|| "this function".to_owned()),
835                            type_err_str(ty, &arg.value, &arg.source_range, exec_state),
836                        ),
837                        vec![arg.source_range],
838                    ))
839                })?;
840            }
841            result.unlabeled = vec![(None, arg)]
842        } else {
843            // Multiple unlabelled args
844
845            // Try to un-spread args into an array
846            if let Some(Type::Array { len, .. }) = ty {
847                if len.satisfied(args.unlabeled.len(), false).is_none() {
848                    exec_state.err(CompilationIssue::err(
849                        args.source_range,
850                        format!(
851                            "{} expects an array input argument with {} elements",
852                            fn_name
853                                .map(|n| format!("The function `{n}`"))
854                                .unwrap_or_else(|| "This function".to_owned()),
855                            len.human_friendly_type(),
856                        ),
857                    ));
858                }
859
860                let source_range = SourceRange::merge(args.unlabeled.iter().map(|(_, a)| a.source_range));
861                exec_state.warn_experimental("array input arguments", source_range);
862                result.unlabeled = vec![(
863                    None,
864                    Arg {
865                        source_range,
866                        value: KclValue::HomArray {
867                            value: args.unlabeled.drain(..).map(|(_, a)| a.value).collect(),
868                            ty: RuntimeType::any(),
869                        },
870                    },
871                )]
872            }
873        }
874    }
875
876    // Either we didn't move the arg above, or we're not expecting one.
877    if !args.unlabeled.is_empty() {
878        // Not expecting an input arg, but found one or more
879        let actuals = args.labeled.keys();
880        let formals: Vec<_> = fn_def
881            .named_args
882            .keys()
883            .filter_map(|name| {
884                if actuals.clone().any(|a| a == name) {
885                    return None;
886                }
887
888                Some(format!("`{name}`"))
889            })
890            .collect();
891
892        let suggestion = if formals.is_empty() {
893            String::new()
894        } else {
895            format!("; suggested labels: {}", formals.join(", "))
896        };
897
898        let mut errors = args.unlabeled.iter().map(|(_, arg)| {
899            CompilationIssue::err(
900                arg.source_range,
901                format!("This argument needs a label, but it doesn't have one{suggestion}"),
902            )
903        });
904
905        let first = errors.next().unwrap();
906        errors.for_each(|e| exec_state.err(e));
907
908        return Err(KclError::new_argument(first.into()));
909    }
910
911    for (label, mut arg) in args.labeled {
912        match fn_def.named_args.get(&label) {
913            Some(NamedParam {
914                experimental: _,
915                deprecated_since: _,
916                default_value: def,
917                ty,
918            }) => {
919                // For optional args, passing None should be the same as not passing an arg.
920                if !(def.is_some() && matches!(arg.value, KclValue::KclNone { .. })) {
921                    if let Some(ty) = ty {
922                        // Suppress warnings about types because they should
923                        // only be warned about once for the function
924                        // definition.
925                        let rty = RuntimeType::from_parsed(ty.clone(), exec_state, arg.source_range, false, true)
926                            .map_err(|e| KclError::new_semantic(e.into()))?;
927                        arg.value = arg
928                                .value
929                                .coerce(
930                                    &rty,
931                                    true,
932                                    exec_state,
933                                )
934                                .map_err(|e| {
935                                    let mut message = format!(
936                                        "{label} requires {}",
937                                        type_err_str(ty, &arg.value, &arg.source_range, exec_state),
938                                    );
939                                    if let Some(ty) = e.explicit_coercion {
940                                        // TODO if we have access to the AST for the argument we could choose which example to suggest.
941                                        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}`");
942                                    }
943                                    KclError::new_argument(KclErrorDetails::new(
944                                        message,
945                                        vec![arg.source_range],
946                                    ))
947                                })?;
948                    }
949                    result.labeled.insert(label, arg);
950                }
951            }
952            None => {
953                exec_state.err(CompilationIssue::err(
954                    arg.source_range,
955                    format!(
956                        "`{label}` is not an argument of {}",
957                        fn_name
958                            .map(|n| format!("`{n}`"))
959                            .unwrap_or_else(|| "this function".to_owned()),
960                    ),
961                ));
962            }
963        }
964    }
965
966    let consumed_solid_arg_check = fn_def
967        .std_props
968        .as_ref()
969        .map_or(ConsumedSolidArgCheck::Error, |props| props.consumed_solid_arg_check);
970    match consumed_solid_arg_check {
971        ConsumedSolidArgCheck::Error => {
972            result
973                .unlabeled
974                .iter()
975                .map(|(_, arg)| arg)
976                .chain(result.labeled.values())
977                .try_for_each(|arg| validate_value_not_consumed(&arg.value, exec_state, arg.source_range))?;
978        }
979        ConsumedSolidArgCheck::WarnDeprecated => {
980            let std_fn_name = fn_def
981                .std_props
982                .as_ref()
983                .map(|props| props.name.as_str())
984                .unwrap_or("function");
985            for arg in result
986                .unlabeled
987                .iter()
988                .map(|(_, arg)| arg)
989                .chain(result.labeled.values())
990            {
991                warn_if_value_consumed_for_deprecated_call(&arg.value, exec_state, arg.source_range, std_fn_name);
992            }
993        }
994    }
995
996    Ok(result)
997}
998
999fn assign_args_to_params_kw(
1000    fn_def: &FunctionSource,
1001    args: Args<Desugared>,
1002    exec_state: &mut ExecState,
1003) -> Result<(), KclError> {
1004    // Add the arguments to the memory.  A new call frame should have already
1005    // been created.
1006    let source_ranges = fn_def.ast.as_source_ranges();
1007
1008    for (name, param) in fn_def.named_args.iter() {
1009        let arg = args.labeled.get(name);
1010        match arg {
1011            Some(arg) => {
1012                exec_state.mut_stack().add(
1013                    name.clone(),
1014                    arg.value.clone(),
1015                    arg.source_ranges().pop().unwrap_or(SourceRange::synthetic()),
1016                )?;
1017            }
1018            None => match &param.default_value {
1019                Some(default_val) => {
1020                    let value = KclValue::from_default_param(default_val.clone(), exec_state);
1021                    exec_state
1022                        .mut_stack()
1023                        .add(name.clone(), value, default_val.source_range())?;
1024                }
1025                None => {
1026                    return Err(KclError::new_argument(KclErrorDetails::new(
1027                        format!("This function requires a parameter {name}, but you haven't passed it one."),
1028                        source_ranges,
1029                    )));
1030                }
1031            },
1032        }
1033    }
1034
1035    if let Some((param_name, _)) = &fn_def.input_arg {
1036        let Some(unlabeled) = args.unlabeled_kw_arg_unconverted() else {
1037            debug_assert!(false, "Bad args");
1038            return Err(KclError::new_internal(KclErrorDetails::new(
1039                "Desugared arguments are inconsistent".to_owned(),
1040                source_ranges,
1041            )));
1042        };
1043        exec_state.mut_stack().add(
1044            param_name.clone(),
1045            unlabeled.value.clone(),
1046            unlabeled.source_ranges().pop().unwrap_or(SourceRange::synthetic()),
1047        )?;
1048    }
1049
1050    Ok(())
1051}
1052
1053fn coerce_result_type(
1054    result: Result<Option<KclValue>, KclError>,
1055    fn_def: &FunctionSource,
1056    exec_state: &mut ExecState,
1057) -> Result<Option<KclValue>, KclError> {
1058    if let Ok(Some(val)) = result {
1059        if let Some(ret_ty) = &fn_def.return_type {
1060            // Suppress warnings about types because they should only be warned
1061            // about once for the function definition.
1062            let ty = RuntimeType::from_parsed(ret_ty.inner.clone(), exec_state, ret_ty.as_source_range(), false, true)
1063                .map_err(|e| KclError::new_semantic(e.into()))?;
1064            let val = val.coerce(&ty, true, exec_state).map_err(|_| {
1065                KclError::new_type(KclErrorDetails::new(
1066                    format!(
1067                        "This function requires its result to be {}",
1068                        type_err_str(ret_ty, &val, &(&val).into(), exec_state)
1069                    ),
1070                    ret_ty.as_source_ranges(),
1071                ))
1072            })?;
1073            Ok(Some(val))
1074        } else {
1075            Ok(Some(val))
1076        }
1077    } else {
1078        result
1079    }
1080}
1081
1082#[cfg(test)]
1083mod test {
1084    use std::sync::Arc;
1085
1086    use super::*;
1087    use crate::execution::ContextType;
1088    use crate::execution::EnvironmentRef;
1089    use crate::execution::memory::Stack;
1090    use crate::execution::parse_execute;
1091    use crate::execution::types::NumericType;
1092    use crate::parsing::ast::types::DefaultParamVal;
1093    use crate::parsing::ast::types::FunctionExpression;
1094    use crate::parsing::ast::types::Identifier;
1095    use crate::parsing::ast::types::Parameter;
1096    use crate::parsing::ast::types::Program;
1097
1098    #[tokio::test(flavor = "multi_thread")]
1099    async fn test_assign_args_to_params() {
1100        // Set up a little framework for this test.
1101        fn mem(number: usize) -> KclValue {
1102            KclValue::Number {
1103                value: number as f64,
1104                ty: NumericType::count(),
1105                meta: Default::default(),
1106            }
1107        }
1108        fn ident(s: &'static str) -> Node<Identifier> {
1109            Node::no_src(Identifier {
1110                name: s.to_owned(),
1111                digest: None,
1112            })
1113        }
1114        fn opt_param(s: &'static str) -> Parameter {
1115            Parameter {
1116                experimental: false,
1117                deprecated_since: None,
1118                identifier: ident(s),
1119                param_type: None,
1120                default_value: Some(DefaultParamVal::none()),
1121                labeled: true,
1122                digest: None,
1123            }
1124        }
1125        fn req_param(s: &'static str) -> Parameter {
1126            Parameter {
1127                experimental: false,
1128                deprecated_since: None,
1129                identifier: ident(s),
1130                param_type: None,
1131                default_value: None,
1132                labeled: true,
1133                digest: None,
1134            }
1135        }
1136        fn additional_program_memory(items: &[(String, KclValue)]) -> Stack {
1137            let mut program_memory = Stack::new_for_tests();
1138            for (name, item) in items {
1139                program_memory
1140                    .add(name.clone(), item.clone(), SourceRange::default())
1141                    .unwrap();
1142            }
1143            program_memory
1144        }
1145        // Declare the test cases.
1146        for (test_name, params, args, expected) in [
1147            ("empty", Vec::new(), Vec::new(), Ok(additional_program_memory(&[]))),
1148            (
1149                "all params required, and all given, should be OK",
1150                vec![req_param("x")],
1151                vec![("x", mem(1))],
1152                Ok(additional_program_memory(&[("x".to_owned(), mem(1))])),
1153            ),
1154            (
1155                "all params required, none given, should error",
1156                vec![req_param("x")],
1157                vec![],
1158                Err(KclError::new_argument(KclErrorDetails::new(
1159                    "This function requires a parameter x, but you haven't passed it one.".to_owned(),
1160                    vec![SourceRange::default()],
1161                ))),
1162            ),
1163            (
1164                "all params optional, none given, should be OK",
1165                vec![opt_param("x")],
1166                vec![],
1167                Ok(additional_program_memory(&[("x".to_owned(), KclValue::none())])),
1168            ),
1169            (
1170                "mixed params, too few given",
1171                vec![req_param("x"), opt_param("y")],
1172                vec![],
1173                Err(KclError::new_argument(KclErrorDetails::new(
1174                    "This function requires a parameter x, but you haven't passed it one.".to_owned(),
1175                    vec![SourceRange::default()],
1176                ))),
1177            ),
1178            (
1179                "mixed params, minimum given, should be OK",
1180                vec![req_param("x"), opt_param("y")],
1181                vec![("x", mem(1))],
1182                Ok(additional_program_memory(&[
1183                    ("x".to_owned(), mem(1)),
1184                    ("y".to_owned(), KclValue::none()),
1185                ])),
1186            ),
1187            (
1188                "mixed params, maximum given, should be OK",
1189                vec![req_param("x"), opt_param("y")],
1190                vec![("x", mem(1)), ("y", mem(2))],
1191                Ok(additional_program_memory(&[
1192                    ("x".to_owned(), mem(1)),
1193                    ("y".to_owned(), mem(2)),
1194                ])),
1195            ),
1196        ] {
1197            // Run each test.
1198            let func_expr = Node::no_src(FunctionExpression {
1199                name: None,
1200                params,
1201                body: Program::empty(),
1202                return_type: None,
1203                digest: None,
1204            });
1205            let func_src = FunctionSource::kcl(
1206                Box::new(func_expr),
1207                EnvironmentRef::dummy(),
1208                crate::execution::kcl_value::KclFunctionSourceParams {
1209                    std_props: None,
1210                    experimental: false,
1211                    include_in_feature_tree: false,
1212                },
1213            );
1214            let labeled = args
1215                .iter()
1216                .map(|(name, value)| {
1217                    let arg = Arg::new(value.clone(), SourceRange::default());
1218                    ((*name).to_owned(), arg)
1219                })
1220                .collect::<IndexMap<_, _>>();
1221            let exec_ctxt = ExecutorContext {
1222                engine: Arc::new(Box::new(crate::engine::conn_mock::EngineConnection::new().unwrap())),
1223                engine_batch: crate::engine::EngineBatchContext::default(),
1224                fs: Arc::new(crate::fs::FileManager::new()),
1225                settings: Default::default(),
1226                context_type: ContextType::Mock,
1227            };
1228            let mut exec_state = ExecState::new(&exec_ctxt);
1229            exec_state.mod_local.stack = Stack::new_for_tests();
1230
1231            let args = Args {
1232                fn_name: Some("test".to_owned()),
1233                labeled,
1234                unlabeled: Vec::new(),
1235                source_range: SourceRange::default(),
1236                node_path: None,
1237                ctx: exec_ctxt,
1238                pipe_value: None,
1239                _status: std::marker::PhantomData,
1240            };
1241
1242            let actual = assign_args_to_params_kw(&func_src, args, &mut exec_state).map(|_| exec_state.mod_local.stack);
1243            assert_eq!(
1244                actual, expected,
1245                "failed test '{test_name}':\ngot {actual:?}\nbut expected\n{expected:?}"
1246            );
1247        }
1248    }
1249
1250    #[tokio::test(flavor = "multi_thread")]
1251    async fn type_check_user_args() {
1252        let program = r#"fn makeMessage(prefix: string, suffix: string) {
1253  return prefix + suffix
1254}
1255
1256msg1 = makeMessage(prefix = "world", suffix = " hello")
1257msg2 = makeMessage(prefix = 1, suffix = 3)"#;
1258        let err = parse_execute(program).await.unwrap_err();
1259        assert_eq!(
1260            err.message(),
1261            "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`."
1262        )
1263    }
1264
1265    #[tokio::test(flavor = "multi_thread")]
1266    async fn map_closure_error_mentions_fn_name() {
1267        let program = r#"
1268arr = ["hello"]
1269map(array = arr, f = fn(@item: number) { return item })
1270"#;
1271        let err = parse_execute(program).await.unwrap_err();
1272        assert!(
1273            err.message().contains("map closure"),
1274            "expected map closure errors to include the closure name, got: {}",
1275            err.message()
1276        );
1277    }
1278
1279    #[tokio::test(flavor = "multi_thread")]
1280    async fn array_input_arg() {
1281        let ast = r#"fn f(@input: [mm]) { return 1 }
1282f([1, 2, 3])
1283f(1, 2, 3)
1284"#;
1285        parse_execute(ast).await.unwrap();
1286    }
1287}