Skip to main content

kcl_lib/execution/
fn_call.rs

1use async_recursion::async_recursion;
2use indexmap::IndexMap;
3use kcl_api::Group;
4use kcl_api::OpArg;
5
6use crate::CompilationIssue;
7use crate::NodePath;
8use crate::NodePathExt;
9use crate::SourceRange;
10use crate::errors::KclError;
11use crate::errors::KclErrorDetails;
12use crate::execution::BodyType;
13use crate::execution::ExecState;
14use crate::execution::ExecutorContext;
15use crate::execution::Geometry;
16use crate::execution::KclValue;
17use crate::execution::KclValueControlFlow;
18use crate::execution::Metadata;
19use crate::execution::Solid;
20use crate::execution::StatementKind;
21use crate::execution::TagEngineInfo;
22use crate::execution::TagIdentifier;
23use crate::execution::annotations;
24use crate::execution::cad_op::Operation;
25use crate::execution::cad_op::op_from_kcl_value;
26use crate::execution::control_continue;
27use crate::execution::kcl_value::FunctionBody;
28use crate::execution::kcl_value::FunctionSource;
29use crate::execution::kcl_value::NamedParam;
30use crate::execution::memory;
31use crate::execution::types::RuntimeType;
32use crate::parsing::ast::types::CallExpressionKw;
33use crate::parsing::ast::types::Node;
34use crate::parsing::ast::types::Type;
35use crate::std::ConsumedSolidArgCheck;
36use crate::std::solid_consumption::validate_value_not_consumed;
37use crate::std::solid_consumption::warn_if_value_consumed_for_deprecated_call;
38
39#[derive(Debug, Clone)]
40pub struct Args<Status: ArgsStatus = Desugared> {
41    /// Name of the function these args are being passed into.
42    pub fn_name: Option<String>,
43    /// Unlabeled keyword args. Currently only the first formal arg can be unlabeled.
44    /// If the argument was a local variable, then the first element of the tuple is its name
45    /// which may be used to treat this arg as a labelled arg.
46    pub unlabeled: Vec<(Option<String>, Arg)>,
47    /// Labeled args.
48    pub labeled: IndexMap<String, Arg>,
49    pub source_range: SourceRange,
50    pub node_path: Option<NodePath>,
51    pub ctx: ExecutorContext,
52    /// If this call happens inside a pipe (|>) expression, this holds the LHS of that |>.
53    /// Otherwise it's None.
54    pub pipe_value: Option<Arg>,
55    _status: std::marker::PhantomData<Status>,
56}
57
58pub trait ArgsStatus: std::fmt::Debug + Clone {}
59
60#[derive(Debug, Clone)]
61pub struct Sugary;
62impl ArgsStatus for Sugary {}
63
64// Invariants guaranteed by the `Desugared` status:
65// - There is either 0 or 1 unlabeled arguments
66// - Any lableled args are in the labeled map, and not the unlabeled Vec.
67// - The arguments match the type signature of the function exactly
68// - pipe_value.is_none()
69#[derive(Debug, Clone)]
70pub struct Desugared;
71impl ArgsStatus for Desugared {}
72
73impl Args<Sugary> {
74    /// Collect the given keyword arguments.
75    pub fn new(
76        labeled: IndexMap<String, Arg>,
77        unlabeled: Vec<(Option<String>, Arg)>,
78        source_range: SourceRange,
79        node_path: Option<NodePath>,
80        exec_state: &mut ExecState,
81        ctx: ExecutorContext,
82        fn_name: Option<String>,
83    ) -> Args<Sugary> {
84        Args {
85            fn_name,
86            labeled,
87            unlabeled,
88            source_range,
89            node_path,
90            ctx,
91            pipe_value: exec_state.pipe_value().map(|v| Arg::new(v.clone(), source_range)),
92            _status: std::marker::PhantomData,
93        }
94    }
95}
96
97impl<Status: ArgsStatus> Args<Status> {
98    /// How many arguments are there?
99    pub fn len(&self) -> usize {
100        self.labeled.len() + self.unlabeled.len()
101    }
102
103    /// Are there no arguments?
104    pub fn is_empty(&self) -> bool {
105        self.labeled.is_empty() && self.unlabeled.is_empty()
106    }
107}
108
109impl Args<Desugared> {
110    pub fn new_no_args(
111        source_range: SourceRange,
112        node_path: Option<NodePath>,
113        ctx: ExecutorContext,
114        fn_name: Option<String>,
115    ) -> Args {
116        Args {
117            fn_name,
118            unlabeled: Default::default(),
119            labeled: Default::default(),
120            source_range,
121            node_path,
122            ctx,
123            pipe_value: None,
124            _status: std::marker::PhantomData,
125        }
126    }
127
128    /// Get the unlabeled keyword argument. If not set, returns None.
129    pub(crate) fn unlabeled_kw_arg_unconverted(&self) -> Option<&Arg> {
130        self.unlabeled.first().map(|(_, a)| a)
131    }
132}
133
134#[derive(Debug, Clone)]
135pub struct Arg {
136    /// The evaluated argument.
137    pub value: KclValue,
138    /// The source range of the unevaluated argument.
139    pub source_range: SourceRange,
140}
141
142impl Arg {
143    pub fn new(value: KclValue, source_range: SourceRange) -> Self {
144        Self { value, source_range }
145    }
146
147    pub fn synthetic(value: KclValue) -> Self {
148        Self {
149            value,
150            source_range: SourceRange::synthetic(),
151        }
152    }
153
154    pub fn source_ranges(&self) -> Vec<SourceRange> {
155        vec![self.source_range]
156    }
157}
158
159impl Node<CallExpressionKw> {
160    #[async_recursion]
161    pub(super) async fn execute(
162        &self,
163        exec_state: &mut ExecState,
164        ctx: &ExecutorContext,
165    ) -> Result<KclValueControlFlow, KclError> {
166        let fn_name = &self.callee;
167        let callsite: SourceRange = self.into();
168
169        // Resolve the function before evaluating arguments so calls can mutate
170        // exec_state without holding a memory borrow.
171        let func: KclValue = fn_name.get_result(exec_state, ctx).await?;
172
173        let Some(fn_src) = func.as_function() else {
174            return Err(KclError::new_semantic(KclErrorDetails::new(
175                "cannot call this because it isn't a function".to_string(),
176                vec![callsite],
177            )));
178        };
179
180        // Build a hashmap from argument labels to the final evaluated values.
181        let mut fn_args = IndexMap::with_capacity(self.arguments.len());
182        let mut unlabeled = Vec::new();
183
184        // Evaluate the unlabeled first param, if any exists.
185        if let Some(ref arg_expr) = self.unlabeled {
186            let source_range = SourceRange::from(arg_expr.clone());
187            let metadata = Metadata { source_range };
188            let value_cf = ctx
189                .execute_expr(arg_expr, exec_state, &metadata, &[], StatementKind::Expression)
190                .await?;
191            let value = control_continue!(value_cf);
192
193            let label = arg_expr.ident_name().map(str::to_owned);
194
195            unlabeled.push((label, Arg::new(value, source_range)))
196        }
197
198        for arg_expr in &self.arguments {
199            let source_range = SourceRange::from(arg_expr.arg.clone());
200            let metadata = Metadata { source_range };
201            let value_cf = ctx
202                .execute_expr(&arg_expr.arg, exec_state, &metadata, &[], StatementKind::Expression)
203                .await?;
204            let value = control_continue!(value_cf);
205            let arg = Arg::new(value, source_range);
206            match &arg_expr.label {
207                Some(l) => {
208                    fn_args.insert(l.name.clone(), arg);
209                }
210                None => {
211                    unlabeled.push((arg_expr.arg.ident_name().map(str::to_owned), arg));
212                }
213            }
214        }
215
216        let args = Args::new(
217            fn_args,
218            unlabeled,
219            callsite,
220            self.node_path.clone(),
221            exec_state,
222            ctx.clone(),
223            Some(fn_name.name.name.clone()),
224        );
225
226        let return_value = fn_src
227            .call_kw(Some(fn_name.to_string()), exec_state, ctx, args, callsite)
228            .await
229            .map_err(|e| {
230                // Add the call expression to the source ranges.
231                //
232                // TODO: Use the name that the function was defined
233                // with, not the identifier it was used with.
234                e.add_unwind_location(Some(fn_name.name.name.clone()), callsite)
235            })?;
236
237        let result = return_value.ok_or_else(move || {
238            let mut source_ranges: Vec<SourceRange> = vec![callsite];
239            // We want to send the source range of the original function.
240            if let KclValue::Function { meta, .. } = func {
241                source_ranges = meta.iter().map(|m| m.source_range).collect();
242            };
243            KclError::new_undefined_value(
244                KclErrorDetails::new(
245                    format!("Result of user-defined function {fn_name} is undefined"),
246                    source_ranges,
247                ),
248                None,
249            )
250        })?;
251
252        Ok(result)
253    }
254}
255
256impl FunctionSource {
257    pub(crate) async fn call_kw(
258        &self,
259        fn_name: Option<String>,
260        exec_state: &mut ExecState,
261        ctx: &ExecutorContext,
262        args: Args<Sugary>,
263        callsite: SourceRange,
264    ) -> Result<Option<KclValueControlFlow>, KclError> {
265        exec_state.inc_call_stack_size(callsite)?;
266
267        let result = self.inner_call_kw(fn_name, exec_state, ctx, args, callsite).await;
268
269        exec_state.dec_call_stack_size(callsite)?;
270        result
271    }
272
273    async fn inner_call_kw(
274        &self,
275        fn_name: Option<String>,
276        exec_state: &mut ExecState,
277        ctx: &ExecutorContext,
278        args: Args<Sugary>,
279        callsite: SourceRange,
280    ) -> Result<Option<KclValueControlFlow>, KclError> {
281        // The KCL stdlib is allowed to use deprecated sketch1 functions inside.
282        let warn_on_deprecated_usage = !exec_state.mod_local.inside_stdlib;
283        if warn_on_deprecated_usage && self.deprecated {
284            exec_state.warn(
285                CompilationIssue::err(
286                    callsite,
287                    format!(
288                        "{} is deprecated, see the docs for a recommended replacement",
289                        match &fn_name {
290                            Some(n) => format!("`{n}`"),
291                            None => "This function".to_owned(),
292                        }
293                    ),
294                ),
295                annotations::WARN_DEPRECATED,
296            );
297        } else if warn_on_deprecated_usage
298            && let Some(since) = &self.deprecated_since
299            && annotations::version_ge(&exec_state.mod_local.settings.kcl_version, since)
300        {
301            exec_state.warn(
302                CompilationIssue::err(
303                    callsite,
304                    format!(
305                        "{} is deprecated as of KCL {since}. See the docs for a recommended replacement.",
306                        match &fn_name {
307                            Some(n) => format!("`{n}`"),
308                            None => "This function".to_owned(),
309                        }
310                    ),
311                ),
312                annotations::WARN_DEPRECATED,
313            );
314        }
315        if self.experimental {
316            exec_state.warn_experimental(
317                &match &fn_name {
318                    Some(n) => format!("`{n}`"),
319                    None => "This function".to_owned(),
320                },
321                callsite,
322            );
323        }
324
325        let args = type_check_params_kw(fn_name.as_deref(), self, args, exec_state)?;
326        let face_tag_names = face_tag_names_for_call(self, &args);
327
328        // Warn if experimental or deprecated arguments are used after desugaring.
329        for (label, arg) in &args.labeled {
330            let Some(param) = self.named_args.get(label.as_str()) else {
331                continue;
332            };
333            if param.experimental {
334                exec_state.warn_experimental(
335                    &match &fn_name {
336                        Some(f) => format!("`{f}({label})`"),
337                        None => label.to_owned(),
338                    },
339                    arg.source_range,
340                );
341            }
342            // `deprecated` deprecates the parameter for all versions, whereas
343            // `deprecated_since` only deprecates it at or after a given version.
344            let deprecation_suffix = if !warn_on_deprecated_usage {
345                None
346            } else if param.deprecated {
347                Some("is deprecated, see the docs for a recommended replacement".to_owned())
348            } else if let Some(since) = &param.deprecated_since
349                && annotations::version_ge(&exec_state.mod_local.settings.kcl_version, since)
350            {
351                Some(format!(
352                    "is deprecated as of KCL {since}. See the docs for a recommended replacement."
353                ))
354            } else {
355                None
356            };
357            if let Some(suffix) = deprecation_suffix {
358                let qualified = match &fn_name {
359                    Some(f) => format!("`{f}({label})`"),
360                    None => format!("`{label}`"),
361                };
362                exec_state.warn(
363                    CompilationIssue::err(arg.source_range, format!("{qualified} {suffix}")),
364                    annotations::WARN_DEPRECATED,
365                );
366            }
367        }
368
369        // Don't early return until the stack frame is popped!
370        self.body.prep_mem(exec_state)?;
371
372        // Some function calls might get added to the feature tree.
373        // We do this by adding an "operation".
374
375        // Don't add operations if the KCL code being executed is
376        // just the KCL stdlib calling other KCL stdlib,
377        // because the stdlib internals aren't relevant to users,
378        // that would just be pointless noise.
379        //
380        // Do add operations if the KCL being executed is
381        // user-defined, or the calling code is user-defined,
382        // because that's relevant to the user.
383        let would_trace_stdlib_internals = exec_state.mod_local.inside_stdlib && self.is_std();
384        // self.include_in_feature_tree is set by the KCL annotation `@(feature_tree = true)`.
385        let should_track_operation = !would_trace_stdlib_internals && self.include_in_feature_tree;
386        let op = if should_track_operation {
387            let op_labeled_args = args
388                .labeled
389                .iter()
390                .map(|(k, arg)| (k.clone(), OpArg::new(op_from_kcl_value(&arg.value), arg.source_range)))
391                .collect();
392
393            // If you're calling a stdlib function, track that call as an operation.
394            if self.is_std() {
395                Some(Operation::StdLibCall {
396                    name: fn_name.clone().unwrap_or_else(|| "unknown function".to_owned()),
397                    unlabeled_arg: args
398                        .unlabeled_kw_arg_unconverted()
399                        .map(|arg| OpArg::new(op_from_kcl_value(&arg.value), arg.source_range)),
400                    labeled_args: op_labeled_args,
401                    node_path: NodePath::placeholder(),
402                    source_range: callsite,
403                    stdlib_entry_source_range: exec_state.mod_local.stdlib_entry_source_range,
404                    is_error: false,
405                })
406            } else {
407                // Otherwise, you're calling a user-defined function, track that call as an operation.
408                exec_state.push_op(Operation::GroupBegin {
409                    group: Group::FunctionCall {
410                        name: fn_name.clone(),
411                        function_source_range: self.ast.as_source_range(),
412                        unlabeled_arg: args
413                            .unlabeled_kw_arg_unconverted()
414                            .map(|arg| OpArg::new(op_from_kcl_value(&arg.value), arg.source_range)),
415                        labeled_args: op_labeled_args,
416                    },
417                    node_path: NodePath::placeholder(),
418                    source_range: callsite,
419                });
420
421                None
422            }
423        } else {
424            None
425        };
426
427        let is_calling_into_stdlib = match &self.body {
428            FunctionBody::Rust(_) => true,
429            FunctionBody::Kcl(_) => self.is_std(),
430        };
431        let is_crossing_into_stdlib = is_calling_into_stdlib && !exec_state.mod_local.inside_stdlib;
432        let is_crossing_out_of_stdlib = !is_calling_into_stdlib && exec_state.mod_local.inside_stdlib;
433        let stdlib_entry_source_range = if is_crossing_into_stdlib {
434            // When we're calling into the stdlib, for example calling hole(),
435            // track the location so that any further stdlib calls like
436            // subtract() can point to the hole() call. The frontend needs this.
437            Some(callsite)
438        } else if is_crossing_out_of_stdlib {
439            // When map() calls a user-defined function, and it calls extrude()
440            // for example, we want it to point the the extrude() call, not
441            // the map() call.
442            None
443        } else {
444            // When we're not crossing the stdlib boundary, keep the previous
445            // value.
446            exec_state.mod_local.stdlib_entry_source_range
447        };
448
449        let prev_inside_stdlib = std::mem::replace(&mut exec_state.mod_local.inside_stdlib, is_calling_into_stdlib);
450        let prev_stdlib_entry_source_range = std::mem::replace(
451            &mut exec_state.mod_local.stdlib_entry_source_range,
452            stdlib_entry_source_range,
453        );
454        // Do not early return via ? or something until we've
455        // - put this `prev_inside_stdlib` value back.
456        // - called the pop_env.
457        let result = match &self.body {
458            FunctionBody::Rust(f) => f(exec_state, args).await.map(Some),
459            FunctionBody::Kcl(_) => {
460                if let Err(e) = assign_args_to_params_kw(self, args, exec_state) {
461                    exec_state.mod_local.inside_stdlib = prev_inside_stdlib;
462                    exec_state.mut_stack().pop_env()?;
463                    return Err(e);
464                }
465
466                ctx.exec_block(&self.ast.body, exec_state, BodyType::Block)
467                    .await
468                    .map(|cf| {
469                        if let Some(cf) = cf
470                            && cf.is_some_return()
471                        {
472                            return Some(cf);
473                        }
474                        // Ignore the block's value and extract the return value
475                        // from memory.
476                        exec_state
477                            .stack()
478                            .get(memory::RETURN_NAME, self.ast.as_source_range())
479                            .ok()
480                            .map(KclValue::continue_)
481                    })
482            }
483        };
484        exec_state.mod_local.inside_stdlib = prev_inside_stdlib;
485        exec_state.mod_local.stdlib_entry_source_range = prev_stdlib_entry_source_range;
486        exec_state.mut_stack().pop_env()?;
487
488        if should_track_operation {
489            if let Some(mut op) = op {
490                op.set_std_lib_call_is_error(result.is_err());
491                // Track call operation.  We do this after the call
492                // since things like patternTransform may call user code
493                // before running, and we will likely want to use the
494                // return value. The call takes ownership of the args,
495                // so we need to build the op before the call.
496                exec_state.push_op(op);
497            } else if !is_calling_into_stdlib {
498                exec_state.push_op(Operation::GroupEnd);
499            }
500        }
501
502        let mut result = match result {
503            Ok(Some(value)) => {
504                if value.is_some_return() {
505                    // `Exit` terminates the whole evaluation rather than completing this
506                    // function normally, so it bypasses return-type validation, including
507                    // the `never` contract.
508                    return Ok(Some(value));
509                } else {
510                    Ok(Some(value.into_value()))
511                }
512            }
513            Ok(None) => Ok(None),
514            Err(e) => Err(e),
515        };
516
517        if self.is_std()
518            && let Ok(Some(result)) = &mut result
519        {
520            update_memory_for_tags_of_geometry(result, exec_state)?;
521            if !face_tag_names.is_empty() {
522                attach_face_tags_to_geometry(result, exec_state, &face_tag_names);
523            }
524        }
525
526        coerce_result_type(result, self, exec_state).map(|r| r.map(KclValue::continue_))
527    }
528}
529
530impl FunctionBody {
531    fn prep_mem(&self, exec_state: &mut ExecState) -> Result<(), KclError> {
532        match self {
533            FunctionBody::Rust(_) => exec_state.mut_stack().push_new_root_env(true),
534            FunctionBody::Kcl(memory) => exec_state.mut_stack().push_new_env_for_call(*memory),
535        }
536    }
537}
538
539fn originates_from_sketch_block(value: &KclValue) -> bool {
540    match value {
541        KclValue::Uuid { .. } => false,
542        KclValue::Bool { .. } => false,
543        KclValue::Number { .. } => false,
544        KclValue::String { .. } => false,
545        KclValue::SketchVar { .. } => true,
546        KclValue::SketchConstraint { .. } => true,
547        KclValue::Tuple { value, .. } => value.iter().all(originates_from_sketch_block),
548        KclValue::HomArray { value, .. } => value.iter().all(originates_from_sketch_block),
549        // TODO: sketch block result should return true.
550        KclValue::Object { value, .. } => value.values().all(originates_from_sketch_block),
551        KclValue::TagIdentifier(_) => false,
552        KclValue::TagDeclarator(_) => false,
553        KclValue::GdtAnnotation { .. } => false,
554        KclValue::Plane { .. } => false,
555        KclValue::Face { .. } => false,
556        KclValue::BoundedEdge { .. } => false,
557        KclValue::Segment { .. } => true,
558        KclValue::Sketch { value: sketch } => sketch.origin_sketch_id.is_some(),
559        KclValue::Solid { value: solid } => solid
560            .sketch()
561            .map(|sketch| sketch.origin_sketch_id.is_some())
562            .unwrap_or(false),
563        KclValue::Helix { .. } => false,
564        KclValue::ImportedGeometry(_) => false,
565        KclValue::Function { .. } => false,
566        KclValue::Module { .. } => false,
567        KclValue::Type { .. } => false,
568        KclValue::KclNone { .. } => false,
569    }
570}
571
572fn face_tag_names_for_call(fn_def: &FunctionSource, args: &Args<Desugared>) -> Vec<String> {
573    let Some(std_props) = &fn_def.std_props else {
574        return Vec::new();
575    };
576
577    if !std_function_allows_face_tags(&std_props.name) {
578        return Vec::new();
579    }
580
581    args.labeled
582        .iter()
583        .filter(|(label, _)| matches!(label.as_str(), "tag" | "tagStart" | "tagEnd"))
584        .filter_map(|(_, arg)| match &arg.value {
585            KclValue::TagDeclarator(tag) => Some(tag.name.clone()),
586            _ => None,
587        })
588        .collect()
589}
590
591fn std_function_allows_face_tags(std_fn_name: &str) -> bool {
592    matches!(
593        std_fn_name,
594        "std::sketch::extrude"
595            | "std::solid::chamfer"
596            | "std::solid::fillet"
597            | "std::sketch::sweep"
598            | "std::sketch::loft"
599            | "std::sketch::revolve"
600    )
601}
602
603fn attach_face_tags_to_geometry(result: &mut KclValue, exec_state: &ExecState, tag_names: &[String]) {
604    match result {
605        KclValue::Solid { value } => attach_face_tags_to_solid(value, exec_state, tag_names),
606        KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
607            for v in value {
608                attach_face_tags_to_geometry(v, exec_state, tag_names);
609            }
610        }
611        _ => {}
612    }
613}
614
615fn attach_face_tags_to_solid(solid: &mut Solid, exec_state: &ExecState, tag_names: &[String]) {
616    let surfaces = solid.value.clone();
617    for surface in surfaces {
618        let Some(tag) = surface.get_tag() else {
619            continue;
620        };
621        if !tag_names.iter().any(|tag_name| tag_name == &tag.name) {
622            continue;
623        }
624
625        let tag_id = solid
626            .sketch()
627            .and_then(|sketch| sketch.tags.get(&tag.name))
628            .cloned()
629            .unwrap_or_else(|| {
630                let mut solid_copy = solid.clone();
631                clear_tags_from_solid_copy(&mut solid_copy);
632                TagIdentifier {
633                    value: tag.name.clone(),
634                    info: vec![(
635                        exec_state.stack().current_epoch(),
636                        TagEngineInfo {
637                            id: surface.get_id(),
638                            surface: Some(surface.clone()),
639                            path: None,
640                            geometry: Geometry::Solid(solid_copy),
641                        },
642                    )],
643                    meta: vec![Metadata {
644                        source_range: tag.clone().into(),
645                    }],
646                }
647            });
648
649        match solid.faces.get_mut(&tag.name) {
650            Some(existing_tag) => existing_tag.merge_info(&tag_id),
651            None => {
652                solid.faces.insert(tag.name.clone(), tag_id);
653            }
654        }
655    }
656}
657
658fn clear_tags_from_solid_copy(solid: &mut Solid) {
659    if let Some(sketch) = solid.sketch_mut() {
660        sketch.tags.clear(); // Avoid recursive tags.
661    }
662    solid.faces.clear();
663}
664
665fn update_memory_for_tags_of_geometry(result: &mut KclValue, exec_state: &mut ExecState) -> Result<(), KclError> {
666    let is_sketch_block = originates_from_sketch_block(&*result);
667    // If the return result is a sketch or solid, we want to update the
668    // memory for the tags of the group.
669    // TODO: This could probably be done in a better way, but as of now this was my only idea
670    // and it works.
671    match result {
672        KclValue::Sketch { value } if !is_sketch_block => {
673            for (name, tag) in value.tags.iter() {
674                if exec_state.stack().cur_frame_contains(name)? {
675                    exec_state.mut_stack().update(name, |v, _| {
676                        if let Some(existing_tag) = v.as_mut_tag() {
677                            existing_tag.merge_info(tag);
678                        }
679                    })?;
680                } else {
681                    exec_state.mut_stack().add(
682                        name.to_owned(),
683                        KclValue::TagIdentifier(Box::new(tag.clone())),
684                        SourceRange::default(),
685                    )?;
686                }
687            }
688        }
689        KclValue::Solid { value } => {
690            let surfaces = value.value.clone();
691            if value.sketch_mut().is_none() {
692                // If the solid isn't based on a sketch, then it doesn't have a tag container,
693                // so there's nothing to do here.
694                return Ok(());
695            };
696            // Now that we know there's work to do (because there's a tag container),
697            // run some clones.
698            let solid_copies: Vec<Box<Solid>> = surfaces.iter().map(|_| value.clone()).collect();
699            // Get the tag container. We expect it to always succeed because we already checked
700            // for a tag container above.
701            let Some(sketch) = value.sketch_mut() else {
702                return Ok(());
703            };
704            for (v, mut solid_copy) in surfaces.iter().zip(solid_copies) {
705                clear_tags_from_solid_copy(&mut solid_copy);
706                if let Some(tag) = v.get_tag() {
707                    // Get the past tag and update it.
708                    let mut is_part_of_sketch = false;
709                    let tag_id = if let Some(t) = sketch.tags.get(&tag.name) {
710                        is_part_of_sketch = true;
711                        let mut t = t.clone();
712                        let Some(info) = t.get_cur_info() else {
713                            return Err(KclError::new_internal(KclErrorDetails::new(
714                                format!("Tag {} does not have path info", tag.name),
715                                vec![tag.into()],
716                            )));
717                        };
718
719                        let mut info = info.clone();
720                        info.id = v.get_id();
721                        info.surface = Some(v.clone());
722                        info.geometry = Geometry::Solid(*solid_copy);
723                        t.info.push((exec_state.stack().current_epoch(), info));
724                        t
725                    } else {
726                        // It's probably a fillet or a chamfer.
727                        // Initialize it.
728                        TagIdentifier {
729                            value: tag.name.clone(),
730                            info: vec![(
731                                exec_state.stack().current_epoch(),
732                                TagEngineInfo {
733                                    id: v.get_id(),
734                                    surface: Some(v.clone()),
735                                    path: None,
736                                    geometry: Geometry::Solid(*solid_copy),
737                                },
738                            )],
739                            meta: vec![Metadata {
740                                source_range: tag.clone().into(),
741                            }],
742                        }
743                    };
744
745                    // update the sketch tags.
746                    sketch.merge_tags(Some(&tag_id).into_iter());
747
748                    if exec_state.stack().cur_frame_contains(&tag.name)? {
749                        exec_state.mut_stack().update(&tag.name, |v, _| {
750                            if let Some(existing_tag) = v.as_mut_tag() {
751                                existing_tag.merge_info(&tag_id);
752                            }
753                        })?;
754                    } else if !is_sketch_block || !is_part_of_sketch {
755                        // The above condition is saying that we add a tag to
756                        // the stack in either of these cases:
757                        //
758                        // 1. It originates from a legacy sketch v1.
759                        //
760                        // 2. It originates from a sketch block and it's not
761                        // part of the sketch. Instead, it's part of the solid,
762                        // as in tagging a cap face `extrude(tagEnd, tagStart)`
763                        // or chamfer face `chamfer(tag)`.
764                        exec_state.mut_stack().add(
765                            tag.name.clone(),
766                            KclValue::TagIdentifier(Box::new(tag_id)),
767                            SourceRange::default(),
768                        )?;
769                    }
770                }
771            }
772
773            // Find the stale sketch in memory and update it.
774            if let Some(sketch) = value.sketch() {
775                if sketch.tags.is_empty() {
776                    return Ok(());
777                }
778                let sketch_tags: Vec<_> = sketch.tags.values().cloned().collect();
779                let sketches_to_update: Vec<_> = exec_state.stack().find_keys_in_current_env(|v| match v {
780                    KclValue::Sketch { value: sk } => sk.original_id == sketch.original_id,
781                    _ => false,
782                })?;
783
784                for k in sketches_to_update {
785                    exec_state.mut_stack().update(&k, |v, _| {
786                        if let Some(sketch) = v.as_mut_sketch() {
787                            sketch.merge_tags(sketch_tags.iter());
788                        }
789                    })?;
790                }
791            }
792        }
793        KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
794            for v in value {
795                update_memory_for_tags_of_geometry(v, exec_state)?;
796            }
797        }
798        _ => {}
799    }
800    Ok(())
801}
802
803fn type_err_str(expected: &Type, found: &KclValue, source_range: &SourceRange, exec_state: &mut ExecState) -> String {
804    fn strip_backticks(s: &str) -> &str {
805        let mut result = s;
806        if s.starts_with('`') {
807            result = &result[1..]
808        }
809        if s.ends_with('`') {
810            result = &result[..result.len() - 1]
811        }
812        result
813    }
814
815    let expected_human = expected.human_friendly_type();
816    let expected_ty = expected.to_string();
817    let expected_str =
818        if expected_human == expected_ty || expected_human == format!("a value with type `{expected_ty}`") {
819            format!("a value with type `{expected_ty}`")
820        } else {
821            format!("{expected_human} (`{expected_ty}`)")
822        };
823    let found_human = found.human_friendly_type();
824    let found_ty = found.principal_type_string();
825    let found_str = if found_human == found_ty || found_human == format!("a {}", strip_backticks(&found_ty)) {
826        format!("a value with type {found_ty}")
827    } else {
828        format!("{found_human} (with type {found_ty})")
829    };
830
831    let mut result = format!("{expected_str}, but found {found_str}.");
832
833    if found.is_unknown_number() {
834        exec_state.clear_units_warnings(source_range);
835        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`.");
836    }
837
838    result
839}
840
841/// Build the error message for a labeled argument whose label doesn't match any
842/// parameter of the callee. Shared between keyword function calls and sketch
843/// blocks so the wording stays consistent.
844pub(crate) fn unexpected_kw_arg_message(label: &str, callee_name: Option<&str>) -> String {
845    format!(
846        "`{label}` is not an argument of {}",
847        callee_name
848            .map(|n| format!("`{n}`"))
849            .unwrap_or_else(|| "this function".to_owned()),
850    )
851}
852
853fn type_check_params_kw(
854    fn_name: Option<&str>,
855    fn_def: &FunctionSource,
856    mut args: Args<Sugary>,
857    exec_state: &mut ExecState,
858) -> Result<Args<Desugared>, KclError> {
859    let fn_name = fn_name.or(args.fn_name.as_deref());
860    let mut result = Args::new_no_args(
861        args.source_range,
862        args.node_path.clone(),
863        args.ctx,
864        fn_name.map(|f| f.to_string()).or_else(|| args.fn_name.clone()),
865    );
866
867    // If it's possible the input arg was meant to be labelled and we probably don't want to use
868    // it as the input arg, then treat it as labelled.
869    if let Some((Some(label), _)) = args.unlabeled.first()
870        && args.unlabeled.len() == 1
871        && (fn_def.input_arg.is_none() || args.pipe_value.is_some())
872        && fn_def.named_args.iter().any(|p| p.0 == label)
873        && !args.labeled.contains_key(label)
874    {
875        let Some((label, arg)) = args.unlabeled.pop() else {
876            let message = "Expected unlabeled arg to be present".to_owned();
877            debug_assert!(false, "{}", &message);
878            return Err(KclError::new_internal(KclErrorDetails::new(
879                message,
880                vec![args.source_range],
881            )));
882        };
883        args.labeled.insert(label.unwrap(), arg);
884    }
885
886    // Apply the `a == a: a` shorthand by desugaring unlabeled args into labeled ones.
887    let (labeled_unlabeled, unlabeled_unlabeled) = args.unlabeled.into_iter().partition(|(l, _)| {
888        if let Some(l) = l
889            && fn_def.named_args.contains_key(l)
890            && !args.labeled.contains_key(l)
891        {
892            true
893        } else {
894            false
895        }
896    });
897    args.unlabeled = unlabeled_unlabeled;
898    for (l, arg) in labeled_unlabeled {
899        let previous = args.labeled.insert(l.unwrap(), arg);
900        debug_assert!(previous.is_none());
901    }
902
903    if let Some((name, ty)) = &fn_def.input_arg {
904        // Expecting an input arg
905
906        if args.unlabeled.is_empty() {
907            // No args provided
908
909            if let Some(pipe) = args.pipe_value {
910                // But there is a pipeline
911                result.unlabeled = vec![(None, pipe)];
912            } else if let Some(arg) = args.labeled.swap_remove(name) {
913                // Mistakenly labelled
914                exec_state.err(CompilationIssue::err(
915                    arg.source_range,
916                    format!(
917                        "{} expects an unlabeled first argument (`@{name}`), but it is labelled in the call. You might try removing the `{name} = `",
918                        fn_name
919                            .map(|n| format!("The function `{n}`"))
920                            .unwrap_or_else(|| "This function".to_owned()),
921                    ),
922                ));
923                result.unlabeled = vec![(Some(name.clone()), arg)];
924            } else {
925                // Just missing
926                return Err(KclError::new_argument(KclErrorDetails::new(
927                    "This function expects an unlabeled first parameter, but you haven't passed it one.".to_owned(),
928                    fn_def.ast.as_source_ranges(),
929                )));
930            }
931        } else if args.unlabeled.len() == 1
932            && let Some(unlabeled_arg) = args.unlabeled.pop()
933        {
934            let mut arg = unlabeled_arg.1;
935            if let Some(ty) = ty {
936                // Suppress warnings about types because they should only be
937                // warned about once for the function definition.
938                let rty = RuntimeType::from_parsed(ty.clone(), exec_state, arg.source_range, false, true)
939                    .map_err(|e| KclError::new_semantic(e.into()))?;
940                arg.value = arg.value.coerce(&rty, true, exec_state).map_err(|_| {
941                    KclError::new_argument(KclErrorDetails::new(
942                        format!(
943                            "The input argument of {} requires {}",
944                            fn_name
945                                .map(|n| format!("`{n}`"))
946                                .unwrap_or_else(|| "this function".to_owned()),
947                            type_err_str(ty, &arg.value, &arg.source_range, exec_state),
948                        ),
949                        vec![arg.source_range],
950                    ))
951                })?;
952            }
953            result.unlabeled = vec![(None, arg)]
954        } else {
955            // Multiple unlabelled args
956
957            // Try to un-spread args into an array
958            if let Some(Type::Array { len, .. }) = ty {
959                if len.satisfied(args.unlabeled.len(), false).is_none() {
960                    exec_state.err(CompilationIssue::err(
961                        args.source_range,
962                        format!(
963                            "{} expects an array input argument with {} elements",
964                            fn_name
965                                .map(|n| format!("The function `{n}`"))
966                                .unwrap_or_else(|| "This function".to_owned()),
967                            len.human_friendly_type(),
968                        ),
969                    ));
970                }
971
972                let source_range = SourceRange::merge(args.unlabeled.iter().map(|(_, a)| a.source_range));
973                exec_state.warn_experimental("array input arguments", source_range);
974                result.unlabeled = vec![(
975                    None,
976                    Arg {
977                        source_range,
978                        value: KclValue::HomArray {
979                            value: args.unlabeled.drain(..).map(|(_, a)| a.value).collect(),
980                            ty: RuntimeType::any(),
981                        },
982                    },
983                )]
984            }
985        }
986    }
987
988    // Either we didn't move the arg above, or we're not expecting one.
989    if !args.unlabeled.is_empty() {
990        // Not expecting an input arg, but found one or more
991        let actuals = args.labeled.keys();
992        let formals: Vec<_> = fn_def
993            .named_args
994            .keys()
995            .filter_map(|name| {
996                if actuals.clone().any(|a| a == name) {
997                    return None;
998                }
999
1000                Some(format!("`{name}`"))
1001            })
1002            .collect();
1003
1004        let suggestion = if formals.is_empty() {
1005            String::new()
1006        } else {
1007            format!("; suggested labels: {}", formals.join(", "))
1008        };
1009
1010        let mut errors = args.unlabeled.iter().map(|(_, arg)| {
1011            CompilationIssue::err(
1012                arg.source_range,
1013                format!("This argument needs a label, but it doesn't have one{suggestion}"),
1014            )
1015        });
1016
1017        let first = errors.next().unwrap();
1018        errors.for_each(|e| exec_state.err(e));
1019
1020        return Err(KclError::new_argument(first.into()));
1021    }
1022
1023    for (label, mut arg) in args.labeled {
1024        match fn_def.named_args.get(&label) {
1025            Some(NamedParam {
1026                experimental: _,
1027                deprecated: _,
1028                deprecated_since: _,
1029                default_value: def,
1030                ty,
1031            }) => {
1032                // For optional args, passing None should be the same as not passing an arg.
1033                if !(def.is_some() && matches!(arg.value, KclValue::KclNone { .. })) {
1034                    if let Some(ty) = ty {
1035                        // Suppress warnings about types because they should
1036                        // only be warned about once for the function
1037                        // definition.
1038                        let rty = RuntimeType::from_parsed(ty.clone(), exec_state, arg.source_range, false, true)
1039                            .map_err(|e| KclError::new_semantic(e.into()))?;
1040                        arg.value = arg
1041                                .value
1042                                .coerce(
1043                                    &rty,
1044                                    true,
1045                                    exec_state,
1046                                )
1047                                .map_err(|e| {
1048                                    let mut message = format!(
1049                                        "{label} requires {}",
1050                                        type_err_str(ty, &arg.value, &arg.source_range, exec_state),
1051                                    );
1052                                    if let Some(ty) = e.explicit_coercion {
1053                                        // TODO if we have access to the AST for the argument we could choose which example to suggest.
1054                                        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}`");
1055                                    }
1056                                    KclError::new_argument(KclErrorDetails::new(
1057                                        message,
1058                                        vec![arg.source_range],
1059                                    ))
1060                                })?;
1061                    }
1062                    result.labeled.insert(label, arg);
1063                }
1064            }
1065            None => {
1066                exec_state.err(CompilationIssue::err(
1067                    arg.source_range,
1068                    unexpected_kw_arg_message(&label, fn_name),
1069                ));
1070            }
1071        }
1072    }
1073
1074    let consumed_solid_arg_check = fn_def
1075        .std_props
1076        .as_ref()
1077        .map_or(ConsumedSolidArgCheck::Error, |props| props.consumed_solid_arg_check);
1078    match consumed_solid_arg_check {
1079        ConsumedSolidArgCheck::Error => {
1080            result
1081                .unlabeled
1082                .iter()
1083                .map(|(_, arg)| arg)
1084                .chain(result.labeled.values())
1085                .try_for_each(|arg| validate_value_not_consumed(&arg.value, exec_state, arg.source_range))?;
1086        }
1087        ConsumedSolidArgCheck::WarnDeprecated => {
1088            let std_fn_name = fn_def
1089                .std_props
1090                .as_ref()
1091                .map(|props| props.name.as_str())
1092                .unwrap_or("function");
1093            for arg in result
1094                .unlabeled
1095                .iter()
1096                .map(|(_, arg)| arg)
1097                .chain(result.labeled.values())
1098            {
1099                warn_if_value_consumed_for_deprecated_call(&arg.value, exec_state, arg.source_range, std_fn_name)?;
1100            }
1101        }
1102    }
1103
1104    Ok(result)
1105}
1106
1107fn assign_args_to_params_kw(
1108    fn_def: &FunctionSource,
1109    args: Args<Desugared>,
1110    exec_state: &mut ExecState,
1111) -> Result<(), KclError> {
1112    // Add the arguments to the memory.  A new call frame should have already
1113    // been created.
1114    let source_ranges = fn_def.ast.as_source_ranges();
1115
1116    for (name, param) in fn_def.named_args.iter() {
1117        let arg = args.labeled.get(name);
1118        match arg {
1119            Some(arg) => {
1120                exec_state.mut_stack().add(
1121                    name.clone(),
1122                    arg.value.clone(),
1123                    arg.source_ranges().pop().unwrap_or(SourceRange::synthetic()),
1124                )?;
1125            }
1126            None => match &param.default_value {
1127                Some(default_val) => {
1128                    let value = KclValue::from_default_param(default_val.clone(), exec_state);
1129                    exec_state
1130                        .mut_stack()
1131                        .add(name.clone(), value, default_val.source_range())?;
1132                }
1133                None => {
1134                    return Err(KclError::new_argument(KclErrorDetails::new(
1135                        format!("This function requires a parameter {name}, but you haven't passed it one."),
1136                        source_ranges,
1137                    )));
1138                }
1139            },
1140        }
1141    }
1142
1143    if let Some((param_name, _)) = &fn_def.input_arg {
1144        let Some(unlabeled) = args.unlabeled_kw_arg_unconverted() else {
1145            debug_assert!(false, "Bad args");
1146            return Err(KclError::new_internal(KclErrorDetails::new(
1147                "Desugared arguments are inconsistent".to_owned(),
1148                source_ranges,
1149            )));
1150        };
1151        exec_state.mut_stack().add(
1152            param_name.clone(),
1153            unlabeled.value.clone(),
1154            unlabeled.source_ranges().pop().unwrap_or(SourceRange::synthetic()),
1155        )?;
1156    }
1157
1158    Ok(())
1159}
1160
1161fn coerce_result_type(
1162    result: Result<Option<KclValue>, KclError>,
1163    fn_def: &FunctionSource,
1164    exec_state: &mut ExecState,
1165) -> Result<Option<KclValue>, KclError> {
1166    let result = result?;
1167
1168    let Some(ret_ty) = &fn_def.return_type else {
1169        return Ok(result);
1170    };
1171
1172    // Suppress warnings about types because they should only be warned
1173    // about once for the function definition.
1174    let ty = RuntimeType::from_parsed(ret_ty.inner.clone(), exec_state, ret_ty.as_source_range(), false, true)
1175        .map_err(|e| KclError::new_semantic(e.into()))?;
1176
1177    // `never` describes the absence of normal completion, so either successful
1178    // result shape violates the function's declared contract.
1179    if ty.subtype(&RuntimeType::never()) {
1180        let message = if result.is_some() {
1181            "This function returned a value, but its return type is `never`. A function with return type `never` must stop evaluation abnormally. You may want to use `fail(...)` to stop evaluation and provide a message."
1182        } else {
1183            "This function completed without returning a value, but its return type is `never`. A function with return type `never` must stop evaluation abnormally. You may want to use `fail(...)` to stop evaluation and provide a message."
1184        };
1185        return Err(KclError::new_type(KclErrorDetails::new(
1186            message.to_owned(),
1187            ret_ty.as_source_ranges(),
1188        )));
1189    }
1190
1191    let Some(val) = result else {
1192        return Ok(None);
1193    };
1194
1195    let val = val.coerce(&ty, true, exec_state).map_err(|_| {
1196        KclError::new_type(KclErrorDetails::new(
1197            format!(
1198                "This function requires its result to be {}",
1199                type_err_str(ret_ty, &val, &(&val).into(), exec_state)
1200            ),
1201            ret_ty.as_source_ranges(),
1202        ))
1203    })?;
1204    Ok(Some(val))
1205}
1206
1207#[cfg(test)]
1208mod test {
1209    use std::sync::Arc;
1210
1211    use super::*;
1212    use crate::engine::engine_manager::EngineManager;
1213    use crate::errors::Severity;
1214    use crate::execution::ContextType;
1215    use crate::execution::EnvironmentRef;
1216    use crate::execution::ExecTestResults;
1217    use crate::execution::memory::Stack;
1218    use crate::execution::parse_execute;
1219    use crate::execution::types::NumericType;
1220    use crate::execution::types::NumericTypeExt;
1221    use crate::parsing::ast::types::DefaultParamVal;
1222    use crate::parsing::ast::types::FunctionExpression;
1223    use crate::parsing::ast::types::Identifier;
1224    use crate::parsing::ast::types::Parameter;
1225    use crate::parsing::ast::types::Program;
1226
1227    fn source_texts<'a>(program: &'a str, error: &KclError) -> Vec<&'a str> {
1228        error
1229            .source_ranges()
1230            .into_iter()
1231            .map(|range| &program[range.start()..range.end()])
1232            .collect()
1233    }
1234
1235    fn get_var(result: &ExecTestResults, name: &str) -> KclValue {
1236        result
1237            .exec_state
1238            .stack()
1239            .memory
1240            .get_from_owned(name, result.mem_env, SourceRange::default(), 0)
1241            .unwrap_or_else(|err| panic!("expected variable `{name}` to exist: {err:?}"))
1242    }
1243
1244    fn var_exists(result: &ExecTestResults, name: &str) -> bool {
1245        result
1246            .exec_state
1247            .stack()
1248            .memory
1249            .get_from_owned(name, result.mem_env, SourceRange::default(), 0)
1250            .is_ok()
1251    }
1252
1253    fn assert_vars_are_tags(result: &ExecTestResults, names: &[&str]) {
1254        for name in names {
1255            assert!(
1256                matches!(get_var(result, name), KclValue::TagIdentifier(_)),
1257                "expected variable `{name}` to be a tag identifier"
1258            );
1259        }
1260    }
1261
1262    fn assert_vars_are_missing(result: &ExecTestResults, names: &[&str]) {
1263        for name in names {
1264            assert!(!var_exists(result, name), "expected variable `{name}` to be absent");
1265        }
1266    }
1267
1268    fn assert_body_face_tags(result: &ExecTestResults, expected: &[&str], unexpected: &[&str]) {
1269        let body = get_var(result, "body");
1270        let KclValue::Solid { value: body } = body else {
1271            panic!("expected `body` to be a solid");
1272        };
1273
1274        for tag in expected {
1275            assert!(body.faces.contains_key(*tag), "expected body.faces to contain `{tag}`");
1276        }
1277
1278        for tag in unexpected {
1279            assert!(
1280                !body.faces.contains_key(*tag),
1281                "expected body.faces not to contain sketch tag `{tag}`"
1282            );
1283        }
1284    }
1285
1286    fn deprecated_solid_tag_access_warnings(result: &ExecTestResults) -> Vec<&CompilationIssue> {
1287        result
1288            .exec_state
1289            .issues()
1290            .iter()
1291            .filter(|issue| issue.message.contains("Accessing solid-created face"))
1292            .collect()
1293    }
1294
1295    #[tokio::test(flavor = "multi_thread")]
1296    async fn test_assign_args_to_params() {
1297        // Set up a little framework for this test.
1298        fn mem(number: usize) -> KclValue {
1299            KclValue::Number {
1300                value: number as f64,
1301                ty: NumericType::count(),
1302                meta: Default::default(),
1303            }
1304        }
1305        fn ident(s: &'static str) -> Node<Identifier> {
1306            Node::no_src(Identifier {
1307                name: s.to_owned(),
1308                digest: None,
1309            })
1310        }
1311        fn opt_param(s: &'static str) -> Parameter {
1312            Parameter {
1313                experimental: false,
1314                deprecated: false,
1315                deprecated_since: None,
1316                identifier: ident(s),
1317                param_type: None,
1318                default_value: Some(DefaultParamVal::none()),
1319                labeled: true,
1320                digest: None,
1321            }
1322        }
1323        fn req_param(s: &'static str) -> Parameter {
1324            Parameter {
1325                experimental: false,
1326                deprecated: false,
1327                deprecated_since: None,
1328                identifier: ident(s),
1329                param_type: None,
1330                default_value: None,
1331                labeled: true,
1332                digest: None,
1333            }
1334        }
1335        fn additional_program_memory(items: &[(String, KclValue)]) -> Stack {
1336            let mut program_memory = Stack::new_for_tests();
1337            for (name, item) in items {
1338                program_memory
1339                    .add(name.clone(), item.clone(), SourceRange::default())
1340                    .unwrap();
1341            }
1342            program_memory
1343        }
1344        // Declare the test cases.
1345        for (test_name, params, args, expected) in [
1346            ("empty", Vec::new(), Vec::new(), Ok(additional_program_memory(&[]))),
1347            (
1348                "all params required, and all given, should be OK",
1349                vec![req_param("x")],
1350                vec![("x", mem(1))],
1351                Ok(additional_program_memory(&[("x".to_owned(), mem(1))])),
1352            ),
1353            (
1354                "all params required, none given, should error",
1355                vec![req_param("x")],
1356                vec![],
1357                Err(KclError::new_argument(KclErrorDetails::new(
1358                    "This function requires a parameter x, but you haven't passed it one.".to_owned(),
1359                    vec![SourceRange::default()],
1360                ))),
1361            ),
1362            (
1363                "all params optional, none given, should be OK",
1364                vec![opt_param("x")],
1365                vec![],
1366                Ok(additional_program_memory(&[("x".to_owned(), KclValue::none())])),
1367            ),
1368            (
1369                "mixed params, too few given",
1370                vec![req_param("x"), opt_param("y")],
1371                vec![],
1372                Err(KclError::new_argument(KclErrorDetails::new(
1373                    "This function requires a parameter x, but you haven't passed it one.".to_owned(),
1374                    vec![SourceRange::default()],
1375                ))),
1376            ),
1377            (
1378                "mixed params, minimum given, should be OK",
1379                vec![req_param("x"), opt_param("y")],
1380                vec![("x", mem(1))],
1381                Ok(additional_program_memory(&[
1382                    ("x".to_owned(), mem(1)),
1383                    ("y".to_owned(), KclValue::none()),
1384                ])),
1385            ),
1386            (
1387                "mixed params, maximum given, should be OK",
1388                vec![req_param("x"), opt_param("y")],
1389                vec![("x", mem(1)), ("y", mem(2))],
1390                Ok(additional_program_memory(&[
1391                    ("x".to_owned(), mem(1)),
1392                    ("y".to_owned(), mem(2)),
1393                ])),
1394            ),
1395        ] {
1396            // Run each test.
1397            let func_expr = Node::no_src(FunctionExpression {
1398                name: None,
1399                params,
1400                body: Program::empty(),
1401                return_type: None,
1402                digest: None,
1403            });
1404            let func_src = FunctionSource::kcl(
1405                Box::new(func_expr),
1406                EnvironmentRef::dummy(),
1407                crate::execution::kcl_value::KclFunctionSourceParams {
1408                    std_props: None,
1409                    experimental: false,
1410                    include_in_feature_tree: false,
1411                },
1412            );
1413            let labeled = args
1414                .iter()
1415                .map(|(name, value)| {
1416                    let arg = Arg::new(value.clone(), SourceRange::default());
1417                    ((*name).to_owned(), arg)
1418                })
1419                .collect::<IndexMap<_, _>>();
1420            let exec_ctxt = ExecutorContext {
1421                engine: Arc::new(EngineManager::new_mock()),
1422                engine_batch: crate::engine::EngineBatchContext::default(),
1423                fs: crate::fs::new_file_system_handle(crate::fs::FileManager::new()),
1424                settings: Default::default(),
1425                context_type: ContextType::Mock,
1426                execution_callbacks: Default::default(),
1427            };
1428            let mut exec_state = ExecState::new(&exec_ctxt);
1429            exec_state.mod_local.stack = Stack::new_for_tests();
1430
1431            let args = Args {
1432                fn_name: Some("test".to_owned()),
1433                labeled,
1434                unlabeled: Vec::new(),
1435                source_range: SourceRange::default(),
1436                node_path: None,
1437                ctx: exec_ctxt,
1438                pipe_value: None,
1439                _status: std::marker::PhantomData,
1440            };
1441
1442            let actual = assign_args_to_params_kw(&func_src, args, &mut exec_state).map(|_| exec_state.mod_local.stack);
1443            assert_eq!(
1444                actual, expected,
1445                "failed test '{test_name}':\ngot {actual:?}\nbut expected\n{expected:?}"
1446            );
1447        }
1448    }
1449
1450    #[tokio::test(flavor = "multi_thread")]
1451    async fn type_check_user_args() {
1452        let program = r#"fn makeMessage(prefix: string, suffix: string) {
1453  return prefix + suffix
1454}
1455
1456msg1 = makeMessage(prefix = "world", suffix = " hello")
1457msg2 = makeMessage(prefix = 1, suffix = 3)"#;
1458        let err = parse_execute(program).await.unwrap_err();
1459        assert_eq!(
1460            err.message(),
1461            "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`."
1462        )
1463    }
1464
1465    #[tokio::test(flavor = "multi_thread")]
1466    async fn never_function_cannot_return_a_value() {
1467        let program = r#"@settings(experimentalFeatures = allow)
1468fn bad(): never {
1469  return 42
1470}
1471
1472bad()
1473"#;
1474        let err = parse_execute(program).await.unwrap_err();
1475
1476        assert!(matches!(&err, KclError::Type { .. }));
1477        assert_eq!(
1478            err.message(),
1479            "This function returned a value, but its return type is `never`. A function with return type `never` must stop evaluation abnormally. You may want to use `fail(...)` to stop evaluation and provide a message."
1480        );
1481    }
1482
1483    #[tokio::test(flavor = "multi_thread")]
1484    async fn never_function_cannot_fall_through() {
1485        let program = r#"@settings(experimentalFeatures = allow)
1486fn alsoBad(): never {
1487  x = 42
1488}
1489
1490alsoBad()
1491"#;
1492        let err = parse_execute(program).await.unwrap_err();
1493
1494        assert!(matches!(&err, KclError::Type { .. }));
1495        assert_eq!(
1496            err.message(),
1497            "This function completed without returning a value, but its return type is `never`. A function with return type `never` must stop evaluation abnormally. You may want to use `fail(...)` to stop evaluation and provide a message."
1498        );
1499    }
1500
1501    #[tokio::test(flavor = "multi_thread")]
1502    async fn never_union_function_cannot_return_a_value() {
1503        let program = r#"@settings(experimentalFeatures = allow)
1504fn bad(): never | never {
1505  return 42
1506}
1507
1508bad()
1509"#;
1510        let err = parse_execute(program).await.unwrap_err();
1511
1512        assert!(matches!(&err, KclError::Type { .. }));
1513        assert_eq!(
1514            err.message(),
1515            "This function returned a value, but its return type is `never`. A function with return type `never` must stop evaluation abnormally. You may want to use `fail(...)` to stop evaluation and provide a message."
1516        );
1517    }
1518
1519    #[tokio::test(flavor = "multi_thread")]
1520    async fn never_union_function_cannot_fall_through() {
1521        let program = r#"@settings(experimentalFeatures = allow)
1522fn alsoBad(): never | never {
1523  x = 42
1524}
1525
1526alsoBad()
1527"#;
1528        let err = parse_execute(program).await.unwrap_err();
1529
1530        assert!(matches!(&err, KclError::Type { .. }));
1531        assert_eq!(
1532            err.message(),
1533            "This function completed without returning a value, but its return type is `never`. A function with return type `never` must stop evaluation abnormally. You may want to use `fail(...)` to stop evaluation and provide a message."
1534        );
1535    }
1536
1537    #[tokio::test(flavor = "multi_thread")]
1538    async fn never_function_contract_is_path_dependent() {
1539        let function = r#"@settings(experimentalFeatures = allow)
1540fn failOrReturn(@shouldFail: bool): never {
1541  return if shouldFail {
1542    fail("requested failure")
1543  } else {
1544    42
1545  }
1546}
1547"#;
1548
1549        let err = parse_execute(&format!("{function}\nfailOrReturn(true)\n"))
1550            .await
1551            .unwrap_err();
1552        assert!(matches!(&err, KclError::UserDefined { .. }));
1553        assert_eq!(err.message(), "requested failure");
1554
1555        let err = parse_execute(&format!("{function}\nfailOrReturn(false)\n"))
1556            .await
1557            .unwrap_err();
1558        assert!(matches!(&err, KclError::Type { .. }));
1559        assert_eq!(
1560            err.message(),
1561            "This function returned a value, but its return type is `never`. A function with return type `never` must stop evaluation abnormally. You may want to use `fail(...)` to stop evaluation and provide a message."
1562        );
1563    }
1564
1565    #[tokio::test(flavor = "multi_thread")]
1566    async fn never_type_alias_contract_is_path_dependent() {
1567        let function = r#"@settings(experimentalFeatures = allow)
1568type impossible = never
1569fn failOrReturn(@shouldFail: bool): impossible {
1570  return if shouldFail {
1571    fail("requested failure")
1572  } else {
1573    42
1574  }
1575}
1576"#;
1577
1578        let err = parse_execute(&format!("{function}\nfailOrReturn(true)\n"))
1579            .await
1580            .unwrap_err();
1581        assert!(matches!(&err, KclError::UserDefined { .. }));
1582        assert_eq!(err.message(), "requested failure");
1583
1584        let err = parse_execute(&format!("{function}\nfailOrReturn(false)\n"))
1585            .await
1586            .unwrap_err();
1587        assert!(matches!(&err, KclError::Type { .. }));
1588        assert_eq!(
1589            err.message(),
1590            "This function returned a value, but its return type is `never`. A function with return type `never` must stop evaluation abnormally. You may want to use `fail(...)` to stop evaluation and provide a message."
1591        );
1592    }
1593
1594    #[tokio::test(flavor = "multi_thread")]
1595    async fn union_with_never_can_return_a_value_or_fail() {
1596        let function = r#"@settings(experimentalFeatures = allow)
1597fn stringOrFail(@shouldFail: bool): string | never {
1598  return if shouldFail {
1599    fail("requested failure")
1600  } else {
1601    "ok"
1602  }
1603}
1604"#;
1605
1606        let result = parse_execute(&format!("{function}\nresult = stringOrFail(false)\n"))
1607            .await
1608            .unwrap();
1609        let KclValue::String { value, .. } = get_var(&result, "result") else {
1610            panic!("expected `result` to be a string")
1611        };
1612        assert_eq!(value, "ok");
1613
1614        let err = parse_execute(&format!("{function}\nstringOrFail(true)\n"))
1615            .await
1616            .unwrap_err();
1617        assert!(matches!(&err, KclError::UserDefined { .. }));
1618        assert_eq!(err.message(), "requested failure");
1619    }
1620
1621    #[tokio::test(flavor = "multi_thread")]
1622    async fn fail_reports_user_defined_message_and_callsite_once() {
1623        let program = r#"@settings(experimentalFeatures = allow)
1624fail("custom failure")
1625"#;
1626
1627        let err = parse_execute(program).await.unwrap_err();
1628
1629        assert!(matches!(&err, KclError::UserDefined { .. }));
1630        assert_eq!(err.message(), "custom failure");
1631        assert_eq!(err.get_message(), "user-defined: custom failure");
1632        assert_eq!(serde_json::to_value(&err).unwrap()["kind"], "user_defined");
1633        assert_eq!(source_texts(program, &err), [r#"fail("custom failure")"#]);
1634        assert_eq!(err.backtrace().len(), 1);
1635    }
1636
1637    #[tokio::test(flavor = "multi_thread")]
1638    async fn fail_unwinds_through_nested_never_functions_once() {
1639        let program = r#"@settings(experimentalFeatures = allow)
1640fn inner(): never {
1641  fail("nested failure")
1642}
1643
1644fn outer(): never {
1645  inner()
1646}
1647
1648outer()
1649"#;
1650
1651        let err = parse_execute(program).await.unwrap_err();
1652
1653        assert!(matches!(&err, KclError::UserDefined { .. }));
1654        assert_eq!(err.message(), "nested failure");
1655        assert_eq!(
1656            source_texts(program, &err),
1657            [r#"fail("nested failure")"#, "inner()", "outer()"]
1658        );
1659        assert_eq!(
1660            err.backtrace()
1661                .iter()
1662                .map(|item| item.fn_name.as_deref())
1663                .collect::<Vec<_>>(),
1664            [Some("inner"), Some("outer"), None]
1665        );
1666    }
1667
1668    #[tokio::test(flavor = "multi_thread")]
1669    async fn fail_is_valid_in_a_function_with_a_value_return_type() {
1670        let function = r#"@settings(experimentalFeatures = allow)
1671fn valueOrFail(@shouldFail: bool): number {
1672  return if shouldFail {
1673    fail("no value")
1674  } else {
1675    42
1676  }
1677}
1678"#;
1679
1680        parse_execute(&format!("{function}\nresult = valueOrFail(false)\n"))
1681            .await
1682            .unwrap();
1683
1684        let err = parse_execute(&format!("{function}\nvalueOrFail(true)\n"))
1685            .await
1686            .unwrap_err();
1687        assert!(matches!(&err, KclError::UserDefined { .. }));
1688        assert_eq!(err.message(), "no value");
1689    }
1690
1691    #[tokio::test(flavor = "multi_thread")]
1692    async fn never_function_with_fail_or_fallthrough_is_path_dependent() {
1693        let function = r#"@settings(experimentalFeatures = allow)
1694fn failOrFallThrough(@shouldFail: bool): never {
1695  result = if shouldFail {
1696    fail("requested failure")
1697  } else {
1698    42
1699  }
1700}
1701"#;
1702
1703        let err = parse_execute(&format!("{function}\nfailOrFallThrough(true)\n"))
1704            .await
1705            .unwrap_err();
1706        assert!(matches!(&err, KclError::UserDefined { .. }));
1707        assert_eq!(err.message(), "requested failure");
1708
1709        let err = parse_execute(&format!("{function}\nfailOrFallThrough(false)\n"))
1710            .await
1711            .unwrap_err();
1712        assert!(matches!(&err, KclError::Type { .. }));
1713        assert_eq!(
1714            err.message(),
1715            "This function completed without returning a value, but its return type is `never`. A function with return type `never` must stop evaluation abnormally. You may want to use `fail(...)` to stop evaluation and provide a message."
1716        );
1717    }
1718
1719    #[tokio::test(flavor = "multi_thread")]
1720    async fn fail_argument_evaluation_errors_take_precedence() {
1721        let program = r#"@settings(experimentalFeatures = allow)
1722fn stop(): never {
1723  fail(missingMessage)
1724}
1725
1726stop()
1727"#;
1728
1729        let err = parse_execute(program).await.unwrap_err();
1730
1731        assert!(matches!(&err, KclError::UndefinedValue { .. }));
1732        assert_eq!(err.message(), "`missingMessage` is not defined");
1733        assert_eq!(source_texts(program, &err), ["missingMessage", "stop()"]);
1734    }
1735
1736    #[tokio::test(flavor = "multi_thread")]
1737    async fn fail_rejects_invalid_message_arguments_before_invocation() {
1738        for program in [
1739            "@settings(experimentalFeatures = allow)\nfail()\n",
1740            "@settings(experimentalFeatures = allow)\nfail(42)\n",
1741        ] {
1742            let err = parse_execute(program).await.unwrap_err();
1743            assert!(matches!(&err, KclError::Argument { .. }), "{err:?}");
1744        }
1745    }
1746
1747    #[tokio::test(flavor = "multi_thread")]
1748    async fn map_closure_error_mentions_fn_name() {
1749        let program = r#"
1750arr = ["hello"]
1751map(array = arr, f = fn(@item: number) { return item })
1752"#;
1753        let err = parse_execute(program).await.unwrap_err();
1754        assert!(
1755            err.message().contains("map closure"),
1756            "expected map closure errors to include the closure name, got: {}",
1757            err.message()
1758        );
1759    }
1760
1761    #[tokio::test(flavor = "multi_thread")]
1762    async fn array_input_arg() {
1763        let ast = r#"fn f(@input: [mm]) { return 1 }
1764f([1, 2, 3])
1765f(1, 2, 3)
1766"#;
1767        parse_execute(ast).await.unwrap();
1768    }
1769
1770    #[tokio::test(flavor = "multi_thread")]
1771    async fn extrude_tagged_body_gets_face_tags_and_keeps_legacy_bindings() {
1772        let program = r#"@settings(kclVersion = 2.0)
1773profile = sketch(on = XY) {
1774  line1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
1775  line2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
1776  line3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
1777  line4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
1778  coincident([line1.end, line2.start])
1779  coincident([line2.end, line3.start])
1780  coincident([line3.end, line4.start])
1781  coincident([line4.end, line1.start])
1782}
1783region1 = region(point = [5mm, 5mm], sketch = profile)
1784
1785body = extrude(region1, length = 5mm, tagStart = $bottom, tagEnd = $top)
1786bottomFromBody = body.faces.bottom
1787topFromBody = body.faces.top
1788lineFromSketch = region1.tags.line1
1789legacyBottom = bottom
1790legacyTop = top
1791"#;
1792
1793        let result = parse_execute(program).await.unwrap();
1794        assert_body_face_tags(&result, &["bottom", "top"], &["line1"]);
1795        assert_vars_are_tags(
1796            &result,
1797            &[
1798                "bottom",
1799                "top",
1800                "bottomFromBody",
1801                "topFromBody",
1802                "lineFromSketch",
1803                "legacyBottom",
1804                "legacyTop",
1805            ],
1806        );
1807        assert_vars_are_missing(&result, &["line1"]);
1808    }
1809
1810    #[tokio::test(flavor = "multi_thread")]
1811    async fn extrude_without_tag_arguments_does_not_get_face_tags() {
1812        let program = r#"@settings(kclVersion = 2.0)
1813profile = sketch(on = XY) {
1814  line1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
1815  line2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
1816  line3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
1817  line4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
1818  coincident([line1.end, line2.start])
1819  coincident([line2.end, line3.start])
1820  coincident([line3.end, line4.start])
1821  coincident([line4.end, line1.start])
1822}
1823region1 = region(point = [5mm, 5mm], sketch = profile)
1824
1825body = extrude(region1, length = 5mm)
1826"#;
1827
1828        let result = parse_execute(program).await.unwrap();
1829        let body = get_var(&result, "body");
1830        let KclValue::Solid { value: body } = body else {
1831            panic!("expected `body` to be a solid");
1832        };
1833
1834        assert!(
1835            body.faces.is_empty(),
1836            "body faces should only be populated for tagged calls"
1837        );
1838    }
1839
1840    #[tokio::test(flavor = "multi_thread")]
1841    async fn revolve_tagged_body_gets_face_tags() {
1842        let program = r#"@settings(kclVersion = 2.0)
1843profile = sketch(on = XY) {
1844  side = line(start = [var 5mm, var 0mm], end = [var 5mm, var 10mm])
1845  line2 = line(start = [var 5mm, var 10mm], end = [var 6mm, var 10mm])
1846  line3 = line(start = [var 6mm, var 10mm], end = [var 6mm, var 0mm])
1847  line4 = line(start = [var 6mm, var 0mm], end = [var 5mm, var 0mm])
1848  coincident([side.end, line2.start])
1849  coincident([line2.end, line3.start])
1850  coincident([line3.end, line4.start])
1851  coincident([line4.end, side.start])
1852}
1853region1 = region(point = [5.5mm, 5mm], sketch = profile)
1854
1855body = revolve(region1, axis = Y, angle = 90deg, tagStart = $startCap, tagEnd = $endCap)
1856startFromBody = body.faces.startCap
1857endFromBody = body.faces.endCap
1858sideFromSketch = region1.tags.side
1859legacyStart = startCap
1860legacyEnd = endCap
1861"#;
1862
1863        let result = parse_execute(program).await.unwrap();
1864        assert_body_face_tags(&result, &["startCap", "endCap"], &["side"]);
1865        assert_vars_are_tags(
1866            &result,
1867            &[
1868                "startCap",
1869                "endCap",
1870                "startFromBody",
1871                "endFromBody",
1872                "sideFromSketch",
1873                "legacyStart",
1874                "legacyEnd",
1875            ],
1876        );
1877        assert_vars_are_missing(&result, &["side"]);
1878    }
1879
1880    #[tokio::test(flavor = "multi_thread")]
1881    async fn sweep_tagged_body_gets_face_tags() {
1882        let program = r#"@settings(kclVersion = 2.0)
1883profile = sketch(on = XZ) {
1884  edge1 = line(start = [var 0mm, var 0mm], end = [var 2mm, var 0mm])
1885  edge2 = line(start = [var 2mm, var 0mm], end = [var 2mm, var 2mm])
1886  edge3 = line(start = [var 2mm, var 2mm], end = [var 0mm, var 2mm])
1887  edge4 = line(start = [var 0mm, var 2mm], end = [var 0mm, var 0mm])
1888  coincident([edge1.end, edge2.start])
1889  coincident([edge2.end, edge3.start])
1890  coincident([edge3.end, edge4.start])
1891  coincident([edge4.end, edge1.start])
1892}
1893profileRegion = region(point = [1mm, 1mm], sketch = profile)
1894
1895pathSketch = sketch(on = offsetPlane(YZ, offset = -2mm)) {
1896  pathLine = line(start = [var 0mm, var 0mm], end = [var 0mm, var 5mm])
1897}
1898
1899body = sweep(profileRegion, path = pathSketch.pathLine, tagStart = $startCap, tagEnd = $endCap)
1900startFromBody = body.faces.startCap
1901endFromBody = body.faces.endCap
1902edgeFromSketch = profileRegion.tags.edge1
1903pathFromSketch = pathSketch.pathLine
1904legacyStart = startCap
1905legacyEnd = endCap
1906"#;
1907
1908        let result = parse_execute(program).await.unwrap();
1909        assert_body_face_tags(&result, &["startCap", "endCap"], &["edge1", "pathLine"]);
1910        assert_vars_are_tags(
1911            &result,
1912            &[
1913                "startCap",
1914                "endCap",
1915                "startFromBody",
1916                "endFromBody",
1917                "edgeFromSketch",
1918                "legacyStart",
1919                "legacyEnd",
1920            ],
1921        );
1922        assert_vars_are_missing(&result, &["edge1", "pathLine"]);
1923    }
1924
1925    #[tokio::test(flavor = "multi_thread")]
1926    async fn loft_tagged_body_gets_face_tags() {
1927        let program = r#"@settings(kclVersion = 2.0)
1928lowerProfile = sketch(on = XY) {
1929  edge1 = line(start = [var 0mm, var 0mm], end = [var 6mm, var 0mm])
1930  edge2 = line(start = [var 6mm, var 0mm], end = [var 6mm, var 4mm])
1931  edge3 = line(start = [var 6mm, var 4mm], end = [var 0mm, var 4mm])
1932  edge4 = line(start = [var 0mm, var 4mm], end = [var 0mm, var 0mm])
1933  coincident([edge1.end, edge2.start])
1934  coincident([edge2.end, edge3.start])
1935  coincident([edge3.end, edge4.start])
1936  coincident([edge4.end, edge1.start])
1937}
1938lowerRegion = region(point = [3mm, 2mm], sketch = lowerProfile)
1939
1940upperProfile = sketch(on = offsetPlane(XY, offset = 8mm)) {
1941  edge5 = line(start = [var 1mm, var 1mm], end = [var 5mm, var 1mm])
1942  edge6 = line(start = [var 5mm, var 1mm], end = [var 4mm, var 3mm])
1943  edge7 = line(start = [var 4mm, var 3mm], end = [var 2mm, var 3mm])
1944  edge8 = line(start = [var 2mm, var 3mm], end = [var 1mm, var 1mm])
1945  coincident([edge5.end, edge6.start])
1946  coincident([edge6.end, edge7.start])
1947  coincident([edge7.end, edge8.start])
1948  coincident([edge8.end, edge5.start])
1949}
1950upperRegion = region(point = [3mm, 2mm], sketch = upperProfile)
1951
1952body = loft([lowerRegion, upperRegion], tagStart = $startCap, tagEnd = $endCap)
1953startFromBody = body.faces.startCap
1954endFromBody = body.faces.endCap
1955edgeFromSketch = lowerRegion.tags.edge1
1956legacyStart = startCap
1957legacyEnd = endCap
1958"#;
1959
1960        let result = parse_execute(program).await.unwrap();
1961        assert_body_face_tags(&result, &["startCap", "endCap"], &["edge1"]);
1962        assert_vars_are_tags(
1963            &result,
1964            &[
1965                "startCap",
1966                "endCap",
1967                "startFromBody",
1968                "endFromBody",
1969                "edgeFromSketch",
1970                "legacyStart",
1971                "legacyEnd",
1972            ],
1973        );
1974        assert_vars_are_missing(&result, &["edge1"]);
1975    }
1976
1977    #[tokio::test(flavor = "multi_thread")]
1978    async fn chamfer_tagged_body_gets_face_tags() {
1979        let program = r#"@settings(kclVersion = 2.0)
1980profile = sketch(on = XY) {
1981  edge1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
1982  edge2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
1983  edge3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
1984  edge4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
1985  coincident([edge1.end, edge2.start])
1986  coincident([edge2.end, edge3.start])
1987  coincident([edge3.end, edge4.start])
1988  coincident([edge4.end, edge1.start])
1989}
1990profileRegion = region(point = [5mm, 5mm], sketch = profile)
1991
1992base = extrude(profileRegion, length = 5mm, tagEnd = $top)
1993body = chamfer(base, tags = getCommonEdge(faces = [profileRegion.tags.edge1, top]), length = 1mm, tag = $chamferFace)
1994chamferFromBody = body.faces.chamferFace
1995topFromBody = body.faces.top
1996edgeFromSketch = profileRegion.tags.edge1
1997legacyChamfer = chamferFace
1998legacyTop = top
1999"#;
2000
2001        let result = parse_execute(program).await.unwrap();
2002        assert_body_face_tags(&result, &["top", "chamferFace"], &["edge1"]);
2003        assert_vars_are_tags(
2004            &result,
2005            &[
2006                "top",
2007                "chamferFace",
2008                "chamferFromBody",
2009                "topFromBody",
2010                "edgeFromSketch",
2011                "legacyChamfer",
2012                "legacyTop",
2013            ],
2014        );
2015        assert_vars_are_missing(&result, &["edge1"]);
2016    }
2017
2018    #[tokio::test(flavor = "multi_thread")]
2019    async fn fillet_tagged_body_gets_face_tags() {
2020        let program = r#"@settings(kclVersion = 2.0)
2021profile = sketch(on = XY) {
2022  edge1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
2023  edge2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
2024  edge3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
2025  edge4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
2026  coincident([edge1.end, edge2.start])
2027  coincident([edge2.end, edge3.start])
2028  coincident([edge3.end, edge4.start])
2029  coincident([edge4.end, edge1.start])
2030}
2031profileRegion = region(point = [5mm, 5mm], sketch = profile)
2032
2033base = extrude(profileRegion, length = 5mm, tagEnd = $top)
2034body = fillet(base, tags = getCommonEdge(faces = [profileRegion.tags.edge1, top]), radius = 1mm, tag = $filletFace)
2035filletFromBody = body.faces.filletFace
2036topFromBody = body.faces.top
2037edgeFromSketch = profileRegion.tags.edge1
2038legacyFillet = filletFace
2039legacyTop = top
2040"#;
2041
2042        let result = parse_execute(program).await.unwrap();
2043        assert_body_face_tags(&result, &["top", "filletFace"], &["edge1"]);
2044        assert_vars_are_tags(
2045            &result,
2046            &[
2047                "top",
2048                "filletFace",
2049                "filletFromBody",
2050                "topFromBody",
2051                "edgeFromSketch",
2052                "legacyFillet",
2053                "legacyTop",
2054            ],
2055        );
2056        assert_vars_are_missing(&result, &["edge1"]);
2057    }
2058
2059    #[tokio::test(flavor = "multi_thread")]
2060    async fn accessing_body_tag_through_body_sketch_tags_warns() {
2061        let program = r#"@settings(kclVersion = 2.0)
2062profile = startSketchOn(XY)
2063  |> startProfile(at = [0, 0])
2064  |> line(end = [10, 0], tag = $line1)
2065  |> line(end = [0, 10])
2066  |> line(end = [-10, 0])
2067  |> close()
2068
2069body = extrude(profile, length = 5, tagEnd = $top)
2070topFromSketch = body.sketch.tags.top
2071topFromBody = body.faces.top
2072"#;
2073
2074        let result = parse_execute(program).await.unwrap();
2075        assert!(matches!(get_var(&result, "topFromSketch"), KclValue::TagIdentifier(_)));
2076        assert!(matches!(get_var(&result, "topFromBody"), KclValue::TagIdentifier(_)));
2077
2078        let warnings = deprecated_solid_tag_access_warnings(&result);
2079        assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
2080        assert_eq!(warnings[0].severity, Severity::Warning);
2081        assert!(warnings[0].message.contains("`top`"), "found {}", warnings[0].message);
2082        assert!(
2083            warnings[0].message.contains("Accessing solid-created face `top` through sketch tags is deprecated. Use the body's faces instead, e.g. `body.faces.top`."),
2084            "found {}",
2085            warnings[0].message
2086        );
2087    }
2088
2089    #[tokio::test(flavor = "multi_thread")]
2090    async fn accessing_sketch_path_tag_through_body_sketch_tags_does_not_warn() {
2091        let program = r#"@settings(kclVersion = 2.0)
2092profile = startSketchOn(XY)
2093  |> startProfile(at = [0, 0])
2094  |> line(end = [10, 0], tag = $line1)
2095  |> line(end = [0, 10])
2096  |> line(end = [-10, 0])
2097  |> close()
2098
2099body = extrude(profile, length = 5, tagEnd = $top)
2100lineFromSketch = body.sketch.tags.line1
2101"#;
2102
2103        let result = parse_execute(program).await.unwrap();
2104        assert!(matches!(get_var(&result, "lineFromSketch"), KclValue::TagIdentifier(_)));
2105        let warnings = deprecated_solid_tag_access_warnings(&result);
2106        assert!(
2107            warnings.is_empty(),
2108            "sketch path tags should not get body-tag deprecation warnings: {warnings:#?}"
2109        );
2110    }
2111
2112    #[tokio::test(flavor = "multi_thread")]
2113    async fn accessing_body_tag_through_sketch_block_region_tags_warns() {
2114        let program = r#"@settings(kclVersion = 2.0)
2115profile = sketch(on = XY) {
2116  line1 = line(start = [0, 0], end = [10, 0])
2117  line2 = line(start = [10, 0], end = [10, 10])
2118  line3 = line(start = [10, 10], end = [0, 10])
2119  line4 = line(start = [0, 10], end = [0, 0])
2120}
2121
2122profileRegion = region(point = [1, 1], sketch = profile)
2123body = extrude(profileRegion, length = 5, tagEnd = $top)
2124topFromRegion = profileRegion.tags.top
2125"#;
2126
2127        let result = parse_execute(program).await.unwrap();
2128        assert!(matches!(get_var(&result, "topFromRegion"), KclValue::TagIdentifier(_)));
2129
2130        let warnings = deprecated_solid_tag_access_warnings(&result);
2131        assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
2132        assert_eq!(warnings[0].severity, Severity::Warning);
2133        assert!(warnings[0].message.contains("`top`"), "found {}", warnings[0].message);
2134    }
2135
2136    fn deprecation_warnings(result: &ExecTestResults) -> Vec<&CompilationIssue> {
2137        result
2138            .exec_state
2139            .issues()
2140            .iter()
2141            .filter(|issue| issue.message.contains("is deprecated"))
2142            .collect()
2143    }
2144
2145    #[tokio::test(flavor = "multi_thread")]
2146    async fn passing_param_deprecated_for_all_versions_warns() {
2147        // `@(deprecated = true)` deprecates the parameter regardless of the KCL
2148        // version, so even on the latest version the call should warn.
2149        let program = r#"@settings(kclVersion = 2.0)
2150fn f(
2151  @a: number,
2152  @(deprecated = true)
2153  oldArg?: number,
2154) {
2155  return a
2156}
2157x = f(1, oldArg = 2)
2158"#;
2159
2160        let result = parse_execute(program).await.unwrap();
2161        let warnings = deprecation_warnings(&result);
2162        assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
2163        assert_eq!(warnings[0].severity, Severity::Warning);
2164        assert!(
2165            warnings[0].message.contains("`f(oldArg)` is deprecated"),
2166            "found {}",
2167            warnings[0].message
2168        );
2169    }
2170
2171    #[tokio::test(flavor = "multi_thread")]
2172    async fn not_passing_deprecated_param_does_not_warn() {
2173        let program = r#"fn f(
2174  @a: number,
2175  @(deprecated = true)
2176  oldArg?: number,
2177) {
2178  return a
2179}
2180x = f(1)
2181"#;
2182
2183        let result = parse_execute(program).await.unwrap();
2184        let warnings = deprecation_warnings(&result);
2185        assert!(
2186            warnings.is_empty(),
2187            "unused deprecated parameter should not warn: {warnings:#?}"
2188        );
2189    }
2190
2191    #[tokio::test(flavor = "multi_thread")]
2192    async fn deprecated_calls_inside_kcl_stdlib_do_not_warn() {
2193        let program = include_str!("../../tests/cube_with_hole/input.kcl");
2194
2195        let result = parse_execute(program).await.unwrap();
2196        let warnings = deprecation_warnings(&result);
2197        assert!(
2198            warnings.is_empty(),
2199            "KCL stdlib internals should not emit deprecation warnings: {warnings:#?}"
2200        );
2201    }
2202
2203    #[tokio::test(flavor = "multi_thread")]
2204    async fn deprecated_stdlib_call_from_user_code_still_warns() {
2205        let program = r#"@settings(kclVersion = 2.0)
2206plane = startSketchOn(XY)
2207"#;
2208
2209        let result = parse_execute(program).await.unwrap();
2210        let warnings = deprecation_warnings(&result);
2211        assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
2212        assert!(
2213            warnings[0].message.contains("`startSketchOn` is deprecated"),
2214            "found {}",
2215            warnings[0].message
2216        );
2217    }
2218}