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