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 pub fn_name: Option<String>,
43 pub unlabeled: Vec<(Option<String>, Arg)>,
47 pub labeled: IndexMap<String, Arg>,
49 pub source_range: SourceRange,
50 pub node_path: Option<NodePath>,
51 pub ctx: ExecutorContext,
52 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#[derive(Debug, Clone)]
70pub struct Desugared;
71impl ArgsStatus for Desugared {}
72
73impl Args<Sugary> {
74 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 pub fn len(&self) -> usize {
100 self.labeled.len() + self.unlabeled.len()
101 }
102
103 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 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 pub value: KclValue,
138 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 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 let mut fn_args = IndexMap::with_capacity(self.arguments.len());
182 let mut unlabeled = Vec::new();
183
184 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 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 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 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 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 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) = ¶m.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 self.body.prep_mem(exec_state)?;
371
372 let would_trace_stdlib_internals = exec_state.mod_local.inside_stdlib && self.is_std();
384 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 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 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 Some(callsite)
438 } else if is_crossing_out_of_stdlib {
439 None
443 } else {
444 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 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 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 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 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 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(); }
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 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 return Ok(());
695 };
696 let solid_copies: Vec<Box<Solid>> = surfaces.iter().map(|_| value.clone()).collect();
699 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 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 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 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 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 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
841pub(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 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 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 if args.unlabeled.is_empty() {
907 if let Some(pipe) = args.pipe_value {
910 result.unlabeled = vec![(None, pipe)];
912 } else if let Some(arg) = args.labeled.swap_remove(name) {
913 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 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 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 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 if !args.unlabeled.is_empty() {
990 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 if !(def.is_some() && matches!(arg.value, KclValue::KclNone { .. })) {
1034 if let Some(ty) = ty {
1035 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 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 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 ¶m.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 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 if ty.subtype(&RuntimeType::never()) {
1180 let message = if result.is_some() {
1181 "This function is declared to return `never`, but it returned a value."
1182 } else {
1183 "This function is declared to return `never`, but it completed without returning a value."
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 get_var(result: &ExecTestResults, name: &str) -> KclValue {
1228 result
1229 .exec_state
1230 .stack()
1231 .memory
1232 .get_from_owned(name, result.mem_env, SourceRange::default(), 0)
1233 .unwrap_or_else(|err| panic!("expected variable `{name}` to exist: {err:?}"))
1234 }
1235
1236 fn var_exists(result: &ExecTestResults, name: &str) -> bool {
1237 result
1238 .exec_state
1239 .stack()
1240 .memory
1241 .get_from_owned(name, result.mem_env, SourceRange::default(), 0)
1242 .is_ok()
1243 }
1244
1245 fn assert_vars_are_tags(result: &ExecTestResults, names: &[&str]) {
1246 for name in names {
1247 assert!(
1248 matches!(get_var(result, name), KclValue::TagIdentifier(_)),
1249 "expected variable `{name}` to be a tag identifier"
1250 );
1251 }
1252 }
1253
1254 fn assert_vars_are_missing(result: &ExecTestResults, names: &[&str]) {
1255 for name in names {
1256 assert!(!var_exists(result, name), "expected variable `{name}` to be absent");
1257 }
1258 }
1259
1260 fn assert_body_face_tags(result: &ExecTestResults, expected: &[&str], unexpected: &[&str]) {
1261 let body = get_var(result, "body");
1262 let KclValue::Solid { value: body } = body else {
1263 panic!("expected `body` to be a solid");
1264 };
1265
1266 for tag in expected {
1267 assert!(body.faces.contains_key(*tag), "expected body.faces to contain `{tag}`");
1268 }
1269
1270 for tag in unexpected {
1271 assert!(
1272 !body.faces.contains_key(*tag),
1273 "expected body.faces not to contain sketch tag `{tag}`"
1274 );
1275 }
1276 }
1277
1278 fn deprecated_solid_tag_access_warnings(result: &ExecTestResults) -> Vec<&CompilationIssue> {
1279 result
1280 .exec_state
1281 .issues()
1282 .iter()
1283 .filter(|issue| issue.message.contains("Accessing solid-created face"))
1284 .collect()
1285 }
1286
1287 #[tokio::test(flavor = "multi_thread")]
1288 async fn test_assign_args_to_params() {
1289 fn mem(number: usize) -> KclValue {
1291 KclValue::Number {
1292 value: number as f64,
1293 ty: NumericType::count(),
1294 meta: Default::default(),
1295 }
1296 }
1297 fn ident(s: &'static str) -> Node<Identifier> {
1298 Node::no_src(Identifier {
1299 name: s.to_owned(),
1300 digest: None,
1301 })
1302 }
1303 fn opt_param(s: &'static str) -> Parameter {
1304 Parameter {
1305 experimental: false,
1306 deprecated: false,
1307 deprecated_since: None,
1308 identifier: ident(s),
1309 param_type: None,
1310 default_value: Some(DefaultParamVal::none()),
1311 labeled: true,
1312 digest: None,
1313 }
1314 }
1315 fn req_param(s: &'static str) -> Parameter {
1316 Parameter {
1317 experimental: false,
1318 deprecated: false,
1319 deprecated_since: None,
1320 identifier: ident(s),
1321 param_type: None,
1322 default_value: None,
1323 labeled: true,
1324 digest: None,
1325 }
1326 }
1327 fn additional_program_memory(items: &[(String, KclValue)]) -> Stack {
1328 let mut program_memory = Stack::new_for_tests();
1329 for (name, item) in items {
1330 program_memory
1331 .add(name.clone(), item.clone(), SourceRange::default())
1332 .unwrap();
1333 }
1334 program_memory
1335 }
1336 for (test_name, params, args, expected) in [
1338 ("empty", Vec::new(), Vec::new(), Ok(additional_program_memory(&[]))),
1339 (
1340 "all params required, and all given, should be OK",
1341 vec![req_param("x")],
1342 vec![("x", mem(1))],
1343 Ok(additional_program_memory(&[("x".to_owned(), mem(1))])),
1344 ),
1345 (
1346 "all params required, none given, should error",
1347 vec![req_param("x")],
1348 vec![],
1349 Err(KclError::new_argument(KclErrorDetails::new(
1350 "This function requires a parameter x, but you haven't passed it one.".to_owned(),
1351 vec![SourceRange::default()],
1352 ))),
1353 ),
1354 (
1355 "all params optional, none given, should be OK",
1356 vec![opt_param("x")],
1357 vec![],
1358 Ok(additional_program_memory(&[("x".to_owned(), KclValue::none())])),
1359 ),
1360 (
1361 "mixed params, too few given",
1362 vec![req_param("x"), opt_param("y")],
1363 vec![],
1364 Err(KclError::new_argument(KclErrorDetails::new(
1365 "This function requires a parameter x, but you haven't passed it one.".to_owned(),
1366 vec![SourceRange::default()],
1367 ))),
1368 ),
1369 (
1370 "mixed params, minimum given, should be OK",
1371 vec![req_param("x"), opt_param("y")],
1372 vec![("x", mem(1))],
1373 Ok(additional_program_memory(&[
1374 ("x".to_owned(), mem(1)),
1375 ("y".to_owned(), KclValue::none()),
1376 ])),
1377 ),
1378 (
1379 "mixed params, maximum given, should be OK",
1380 vec![req_param("x"), opt_param("y")],
1381 vec![("x", mem(1)), ("y", mem(2))],
1382 Ok(additional_program_memory(&[
1383 ("x".to_owned(), mem(1)),
1384 ("y".to_owned(), mem(2)),
1385 ])),
1386 ),
1387 ] {
1388 let func_expr = Node::no_src(FunctionExpression {
1390 name: None,
1391 params,
1392 body: Program::empty(),
1393 return_type: None,
1394 digest: None,
1395 });
1396 let func_src = FunctionSource::kcl(
1397 Box::new(func_expr),
1398 EnvironmentRef::dummy(),
1399 crate::execution::kcl_value::KclFunctionSourceParams {
1400 std_props: None,
1401 experimental: false,
1402 include_in_feature_tree: false,
1403 },
1404 );
1405 let labeled = args
1406 .iter()
1407 .map(|(name, value)| {
1408 let arg = Arg::new(value.clone(), SourceRange::default());
1409 ((*name).to_owned(), arg)
1410 })
1411 .collect::<IndexMap<_, _>>();
1412 let exec_ctxt = ExecutorContext {
1413 engine: Arc::new(EngineManager::new_mock()),
1414 engine_batch: crate::engine::EngineBatchContext::default(),
1415 fs: crate::fs::new_file_system_handle(crate::fs::FileManager::new()),
1416 settings: Default::default(),
1417 context_type: ContextType::Mock,
1418 execution_callbacks: Default::default(),
1419 };
1420 let mut exec_state = ExecState::new(&exec_ctxt);
1421 exec_state.mod_local.stack = Stack::new_for_tests();
1422
1423 let args = Args {
1424 fn_name: Some("test".to_owned()),
1425 labeled,
1426 unlabeled: Vec::new(),
1427 source_range: SourceRange::default(),
1428 node_path: None,
1429 ctx: exec_ctxt,
1430 pipe_value: None,
1431 _status: std::marker::PhantomData,
1432 };
1433
1434 let actual = assign_args_to_params_kw(&func_src, args, &mut exec_state).map(|_| exec_state.mod_local.stack);
1435 assert_eq!(
1436 actual, expected,
1437 "failed test '{test_name}':\ngot {actual:?}\nbut expected\n{expected:?}"
1438 );
1439 }
1440 }
1441
1442 #[tokio::test(flavor = "multi_thread")]
1443 async fn type_check_user_args() {
1444 let program = r#"fn makeMessage(prefix: string, suffix: string) {
1445 return prefix + suffix
1446}
1447
1448msg1 = makeMessage(prefix = "world", suffix = " hello")
1449msg2 = makeMessage(prefix = 1, suffix = 3)"#;
1450 let err = parse_execute(program).await.unwrap_err();
1451 assert_eq!(
1452 err.message(),
1453 "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`."
1454 )
1455 }
1456
1457 #[tokio::test(flavor = "multi_thread")]
1458 async fn never_function_cannot_return_a_value() {
1459 let program = r#"@settings(experimentalFeatures = allow)
1460fn bad(): never {
1461 return 42
1462}
1463
1464bad()
1465"#;
1466 let err = parse_execute(program).await.unwrap_err();
1467
1468 assert!(matches!(&err, KclError::Type { .. }));
1469 assert_eq!(
1470 err.message(),
1471 "This function is declared to return `never`, but it returned a value."
1472 );
1473 }
1474
1475 #[tokio::test(flavor = "multi_thread")]
1476 async fn never_function_cannot_fall_through() {
1477 let program = r#"@settings(experimentalFeatures = allow)
1478fn alsoBad(): never {
1479 x = 42
1480}
1481
1482alsoBad()
1483"#;
1484 let err = parse_execute(program).await.unwrap_err();
1485
1486 assert!(matches!(&err, KclError::Type { .. }));
1487 assert_eq!(
1488 err.message(),
1489 "This function is declared to return `never`, but it completed without returning a value."
1490 );
1491 }
1492
1493 #[tokio::test(flavor = "multi_thread")]
1494 async fn never_union_function_cannot_return_a_value() {
1495 let program = r#"@settings(experimentalFeatures = allow)
1496fn bad(): never | never {
1497 return 42
1498}
1499
1500bad()
1501"#;
1502 let err = parse_execute(program).await.unwrap_err();
1503
1504 assert!(matches!(&err, KclError::Type { .. }));
1505 assert_eq!(
1506 err.message(),
1507 "This function is declared to return `never`, but it returned a value."
1508 );
1509 }
1510
1511 #[tokio::test(flavor = "multi_thread")]
1512 async fn never_union_function_cannot_fall_through() {
1513 let program = r#"@settings(experimentalFeatures = allow)
1514fn alsoBad(): never | never {
1515 x = 42
1516}
1517
1518alsoBad()
1519"#;
1520 let err = parse_execute(program).await.unwrap_err();
1521
1522 assert!(matches!(&err, KclError::Type { .. }));
1523 assert_eq!(
1524 err.message(),
1525 "This function is declared to return `never`, but it completed without returning a value."
1526 );
1527 }
1528
1529 #[tokio::test(flavor = "multi_thread")]
1530 async fn never_function_contract_is_path_dependent() {
1531 let function = r#"@settings(experimentalFeatures = allow)
1532fn pathDependent(@propagateError: bool): never {
1533 return if propagateError {
1534 missingValue
1535 } else {
1536 42
1537 }
1538}
1539"#;
1540
1541 let err = parse_execute(&format!("{function}\npathDependent(true)\n"))
1542 .await
1543 .unwrap_err();
1544 assert!(matches!(&err, KclError::UndefinedValue { .. }));
1545 assert_eq!(err.message(), "`missingValue` is not defined");
1546
1547 let err = parse_execute(&format!("{function}\npathDependent(false)\n"))
1548 .await
1549 .unwrap_err();
1550 assert!(matches!(&err, KclError::Type { .. }));
1551 assert_eq!(
1552 err.message(),
1553 "This function is declared to return `never`, but it returned a value."
1554 );
1555 }
1556
1557 #[tokio::test(flavor = "multi_thread")]
1558 async fn map_closure_error_mentions_fn_name() {
1559 let program = r#"
1560arr = ["hello"]
1561map(array = arr, f = fn(@item: number) { return item })
1562"#;
1563 let err = parse_execute(program).await.unwrap_err();
1564 assert!(
1565 err.message().contains("map closure"),
1566 "expected map closure errors to include the closure name, got: {}",
1567 err.message()
1568 );
1569 }
1570
1571 #[tokio::test(flavor = "multi_thread")]
1572 async fn array_input_arg() {
1573 let ast = r#"fn f(@input: [mm]) { return 1 }
1574f([1, 2, 3])
1575f(1, 2, 3)
1576"#;
1577 parse_execute(ast).await.unwrap();
1578 }
1579
1580 #[tokio::test(flavor = "multi_thread")]
1581 async fn extrude_tagged_body_gets_face_tags_and_keeps_legacy_bindings() {
1582 let program = r#"@settings(kclVersion = 2.0)
1583profile = sketch(on = XY) {
1584 line1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
1585 line2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
1586 line3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
1587 line4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
1588 coincident([line1.end, line2.start])
1589 coincident([line2.end, line3.start])
1590 coincident([line3.end, line4.start])
1591 coincident([line4.end, line1.start])
1592}
1593region1 = region(point = [5mm, 5mm], sketch = profile)
1594
1595body = extrude(region1, length = 5mm, tagStart = $bottom, tagEnd = $top)
1596bottomFromBody = body.faces.bottom
1597topFromBody = body.faces.top
1598lineFromSketch = region1.tags.line1
1599legacyBottom = bottom
1600legacyTop = top
1601"#;
1602
1603 let result = parse_execute(program).await.unwrap();
1604 assert_body_face_tags(&result, &["bottom", "top"], &["line1"]);
1605 assert_vars_are_tags(
1606 &result,
1607 &[
1608 "bottom",
1609 "top",
1610 "bottomFromBody",
1611 "topFromBody",
1612 "lineFromSketch",
1613 "legacyBottom",
1614 "legacyTop",
1615 ],
1616 );
1617 assert_vars_are_missing(&result, &["line1"]);
1618 }
1619
1620 #[tokio::test(flavor = "multi_thread")]
1621 async fn extrude_without_tag_arguments_does_not_get_face_tags() {
1622 let program = r#"@settings(kclVersion = 2.0)
1623profile = sketch(on = XY) {
1624 line1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
1625 line2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
1626 line3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
1627 line4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
1628 coincident([line1.end, line2.start])
1629 coincident([line2.end, line3.start])
1630 coincident([line3.end, line4.start])
1631 coincident([line4.end, line1.start])
1632}
1633region1 = region(point = [5mm, 5mm], sketch = profile)
1634
1635body = extrude(region1, length = 5mm)
1636"#;
1637
1638 let result = parse_execute(program).await.unwrap();
1639 let body = get_var(&result, "body");
1640 let KclValue::Solid { value: body } = body else {
1641 panic!("expected `body` to be a solid");
1642 };
1643
1644 assert!(
1645 body.faces.is_empty(),
1646 "body faces should only be populated for tagged calls"
1647 );
1648 }
1649
1650 #[tokio::test(flavor = "multi_thread")]
1651 async fn revolve_tagged_body_gets_face_tags() {
1652 let program = r#"@settings(kclVersion = 2.0)
1653profile = sketch(on = XY) {
1654 side = line(start = [var 5mm, var 0mm], end = [var 5mm, var 10mm])
1655 line2 = line(start = [var 5mm, var 10mm], end = [var 6mm, var 10mm])
1656 line3 = line(start = [var 6mm, var 10mm], end = [var 6mm, var 0mm])
1657 line4 = line(start = [var 6mm, var 0mm], end = [var 5mm, var 0mm])
1658 coincident([side.end, line2.start])
1659 coincident([line2.end, line3.start])
1660 coincident([line3.end, line4.start])
1661 coincident([line4.end, side.start])
1662}
1663region1 = region(point = [5.5mm, 5mm], sketch = profile)
1664
1665body = revolve(region1, axis = Y, angle = 90deg, tagStart = $startCap, tagEnd = $endCap)
1666startFromBody = body.faces.startCap
1667endFromBody = body.faces.endCap
1668sideFromSketch = region1.tags.side
1669legacyStart = startCap
1670legacyEnd = endCap
1671"#;
1672
1673 let result = parse_execute(program).await.unwrap();
1674 assert_body_face_tags(&result, &["startCap", "endCap"], &["side"]);
1675 assert_vars_are_tags(
1676 &result,
1677 &[
1678 "startCap",
1679 "endCap",
1680 "startFromBody",
1681 "endFromBody",
1682 "sideFromSketch",
1683 "legacyStart",
1684 "legacyEnd",
1685 ],
1686 );
1687 assert_vars_are_missing(&result, &["side"]);
1688 }
1689
1690 #[tokio::test(flavor = "multi_thread")]
1691 async fn sweep_tagged_body_gets_face_tags() {
1692 let program = r#"@settings(kclVersion = 2.0)
1693profile = sketch(on = XZ) {
1694 edge1 = line(start = [var 0mm, var 0mm], end = [var 2mm, var 0mm])
1695 edge2 = line(start = [var 2mm, var 0mm], end = [var 2mm, var 2mm])
1696 edge3 = line(start = [var 2mm, var 2mm], end = [var 0mm, var 2mm])
1697 edge4 = line(start = [var 0mm, var 2mm], end = [var 0mm, var 0mm])
1698 coincident([edge1.end, edge2.start])
1699 coincident([edge2.end, edge3.start])
1700 coincident([edge3.end, edge4.start])
1701 coincident([edge4.end, edge1.start])
1702}
1703profileRegion = region(point = [1mm, 1mm], sketch = profile)
1704
1705pathSketch = sketch(on = offsetPlane(YZ, offset = -2mm)) {
1706 pathLine = line(start = [var 0mm, var 0mm], end = [var 0mm, var 5mm])
1707}
1708
1709body = sweep(profileRegion, path = pathSketch.pathLine, tagStart = $startCap, tagEnd = $endCap)
1710startFromBody = body.faces.startCap
1711endFromBody = body.faces.endCap
1712edgeFromSketch = profileRegion.tags.edge1
1713pathFromSketch = pathSketch.pathLine
1714legacyStart = startCap
1715legacyEnd = endCap
1716"#;
1717
1718 let result = parse_execute(program).await.unwrap();
1719 assert_body_face_tags(&result, &["startCap", "endCap"], &["edge1", "pathLine"]);
1720 assert_vars_are_tags(
1721 &result,
1722 &[
1723 "startCap",
1724 "endCap",
1725 "startFromBody",
1726 "endFromBody",
1727 "edgeFromSketch",
1728 "legacyStart",
1729 "legacyEnd",
1730 ],
1731 );
1732 assert_vars_are_missing(&result, &["edge1", "pathLine"]);
1733 }
1734
1735 #[tokio::test(flavor = "multi_thread")]
1736 async fn loft_tagged_body_gets_face_tags() {
1737 let program = r#"@settings(kclVersion = 2.0)
1738lowerProfile = sketch(on = XY) {
1739 edge1 = line(start = [var 0mm, var 0mm], end = [var 6mm, var 0mm])
1740 edge2 = line(start = [var 6mm, var 0mm], end = [var 6mm, var 4mm])
1741 edge3 = line(start = [var 6mm, var 4mm], end = [var 0mm, var 4mm])
1742 edge4 = line(start = [var 0mm, var 4mm], end = [var 0mm, var 0mm])
1743 coincident([edge1.end, edge2.start])
1744 coincident([edge2.end, edge3.start])
1745 coincident([edge3.end, edge4.start])
1746 coincident([edge4.end, edge1.start])
1747}
1748lowerRegion = region(point = [3mm, 2mm], sketch = lowerProfile)
1749
1750upperProfile = sketch(on = offsetPlane(XY, offset = 8mm)) {
1751 edge5 = line(start = [var 1mm, var 1mm], end = [var 5mm, var 1mm])
1752 edge6 = line(start = [var 5mm, var 1mm], end = [var 4mm, var 3mm])
1753 edge7 = line(start = [var 4mm, var 3mm], end = [var 2mm, var 3mm])
1754 edge8 = line(start = [var 2mm, var 3mm], end = [var 1mm, var 1mm])
1755 coincident([edge5.end, edge6.start])
1756 coincident([edge6.end, edge7.start])
1757 coincident([edge7.end, edge8.start])
1758 coincident([edge8.end, edge5.start])
1759}
1760upperRegion = region(point = [3mm, 2mm], sketch = upperProfile)
1761
1762body = loft([lowerRegion, upperRegion], tagStart = $startCap, tagEnd = $endCap)
1763startFromBody = body.faces.startCap
1764endFromBody = body.faces.endCap
1765edgeFromSketch = lowerRegion.tags.edge1
1766legacyStart = startCap
1767legacyEnd = endCap
1768"#;
1769
1770 let result = parse_execute(program).await.unwrap();
1771 assert_body_face_tags(&result, &["startCap", "endCap"], &["edge1"]);
1772 assert_vars_are_tags(
1773 &result,
1774 &[
1775 "startCap",
1776 "endCap",
1777 "startFromBody",
1778 "endFromBody",
1779 "edgeFromSketch",
1780 "legacyStart",
1781 "legacyEnd",
1782 ],
1783 );
1784 assert_vars_are_missing(&result, &["edge1"]);
1785 }
1786
1787 #[tokio::test(flavor = "multi_thread")]
1788 async fn chamfer_tagged_body_gets_face_tags() {
1789 let program = r#"@settings(kclVersion = 2.0)
1790profile = sketch(on = XY) {
1791 edge1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
1792 edge2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
1793 edge3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
1794 edge4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
1795 coincident([edge1.end, edge2.start])
1796 coincident([edge2.end, edge3.start])
1797 coincident([edge3.end, edge4.start])
1798 coincident([edge4.end, edge1.start])
1799}
1800profileRegion = region(point = [5mm, 5mm], sketch = profile)
1801
1802base = extrude(profileRegion, length = 5mm, tagEnd = $top)
1803body = chamfer(base, tags = getCommonEdge(faces = [profileRegion.tags.edge1, top]), length = 1mm, tag = $chamferFace)
1804chamferFromBody = body.faces.chamferFace
1805topFromBody = body.faces.top
1806edgeFromSketch = profileRegion.tags.edge1
1807legacyChamfer = chamferFace
1808legacyTop = top
1809"#;
1810
1811 let result = parse_execute(program).await.unwrap();
1812 assert_body_face_tags(&result, &["top", "chamferFace"], &["edge1"]);
1813 assert_vars_are_tags(
1814 &result,
1815 &[
1816 "top",
1817 "chamferFace",
1818 "chamferFromBody",
1819 "topFromBody",
1820 "edgeFromSketch",
1821 "legacyChamfer",
1822 "legacyTop",
1823 ],
1824 );
1825 assert_vars_are_missing(&result, &["edge1"]);
1826 }
1827
1828 #[tokio::test(flavor = "multi_thread")]
1829 async fn fillet_tagged_body_gets_face_tags() {
1830 let program = r#"@settings(kclVersion = 2.0)
1831profile = sketch(on = XY) {
1832 edge1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
1833 edge2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
1834 edge3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
1835 edge4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
1836 coincident([edge1.end, edge2.start])
1837 coincident([edge2.end, edge3.start])
1838 coincident([edge3.end, edge4.start])
1839 coincident([edge4.end, edge1.start])
1840}
1841profileRegion = region(point = [5mm, 5mm], sketch = profile)
1842
1843base = extrude(profileRegion, length = 5mm, tagEnd = $top)
1844body = fillet(base, tags = getCommonEdge(faces = [profileRegion.tags.edge1, top]), radius = 1mm, tag = $filletFace)
1845filletFromBody = body.faces.filletFace
1846topFromBody = body.faces.top
1847edgeFromSketch = profileRegion.tags.edge1
1848legacyFillet = filletFace
1849legacyTop = top
1850"#;
1851
1852 let result = parse_execute(program).await.unwrap();
1853 assert_body_face_tags(&result, &["top", "filletFace"], &["edge1"]);
1854 assert_vars_are_tags(
1855 &result,
1856 &[
1857 "top",
1858 "filletFace",
1859 "filletFromBody",
1860 "topFromBody",
1861 "edgeFromSketch",
1862 "legacyFillet",
1863 "legacyTop",
1864 ],
1865 );
1866 assert_vars_are_missing(&result, &["edge1"]);
1867 }
1868
1869 #[tokio::test(flavor = "multi_thread")]
1870 async fn accessing_body_tag_through_body_sketch_tags_warns() {
1871 let program = r#"@settings(kclVersion = 2.0)
1872profile = startSketchOn(XY)
1873 |> startProfile(at = [0, 0])
1874 |> line(end = [10, 0], tag = $line1)
1875 |> line(end = [0, 10])
1876 |> line(end = [-10, 0])
1877 |> close()
1878
1879body = extrude(profile, length = 5, tagEnd = $top)
1880topFromSketch = body.sketch.tags.top
1881topFromBody = body.faces.top
1882"#;
1883
1884 let result = parse_execute(program).await.unwrap();
1885 assert!(matches!(get_var(&result, "topFromSketch"), KclValue::TagIdentifier(_)));
1886 assert!(matches!(get_var(&result, "topFromBody"), KclValue::TagIdentifier(_)));
1887
1888 let warnings = deprecated_solid_tag_access_warnings(&result);
1889 assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
1890 assert_eq!(warnings[0].severity, Severity::Warning);
1891 assert!(warnings[0].message.contains("`top`"), "found {}", warnings[0].message);
1892 assert!(
1893 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`."),
1894 "found {}",
1895 warnings[0].message
1896 );
1897 }
1898
1899 #[tokio::test(flavor = "multi_thread")]
1900 async fn accessing_sketch_path_tag_through_body_sketch_tags_does_not_warn() {
1901 let program = r#"@settings(kclVersion = 2.0)
1902profile = startSketchOn(XY)
1903 |> startProfile(at = [0, 0])
1904 |> line(end = [10, 0], tag = $line1)
1905 |> line(end = [0, 10])
1906 |> line(end = [-10, 0])
1907 |> close()
1908
1909body = extrude(profile, length = 5, tagEnd = $top)
1910lineFromSketch = body.sketch.tags.line1
1911"#;
1912
1913 let result = parse_execute(program).await.unwrap();
1914 assert!(matches!(get_var(&result, "lineFromSketch"), KclValue::TagIdentifier(_)));
1915 let warnings = deprecated_solid_tag_access_warnings(&result);
1916 assert!(
1917 warnings.is_empty(),
1918 "sketch path tags should not get body-tag deprecation warnings: {warnings:#?}"
1919 );
1920 }
1921
1922 #[tokio::test(flavor = "multi_thread")]
1923 async fn accessing_body_tag_through_sketch_block_region_tags_warns() {
1924 let program = r#"@settings(kclVersion = 2.0)
1925profile = sketch(on = XY) {
1926 line1 = line(start = [0, 0], end = [10, 0])
1927 line2 = line(start = [10, 0], end = [10, 10])
1928 line3 = line(start = [10, 10], end = [0, 10])
1929 line4 = line(start = [0, 10], end = [0, 0])
1930}
1931
1932profileRegion = region(point = [1, 1], sketch = profile)
1933body = extrude(profileRegion, length = 5, tagEnd = $top)
1934topFromRegion = profileRegion.tags.top
1935"#;
1936
1937 let result = parse_execute(program).await.unwrap();
1938 assert!(matches!(get_var(&result, "topFromRegion"), KclValue::TagIdentifier(_)));
1939
1940 let warnings = deprecated_solid_tag_access_warnings(&result);
1941 assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
1942 assert_eq!(warnings[0].severity, Severity::Warning);
1943 assert!(warnings[0].message.contains("`top`"), "found {}", warnings[0].message);
1944 }
1945
1946 fn deprecation_warnings(result: &ExecTestResults) -> Vec<&CompilationIssue> {
1947 result
1948 .exec_state
1949 .issues()
1950 .iter()
1951 .filter(|issue| issue.message.contains("is deprecated"))
1952 .collect()
1953 }
1954
1955 #[tokio::test(flavor = "multi_thread")]
1956 async fn passing_param_deprecated_for_all_versions_warns() {
1957 let program = r#"@settings(kclVersion = 2.0)
1960fn f(
1961 @a: number,
1962 @(deprecated = true)
1963 oldArg?: number,
1964) {
1965 return a
1966}
1967x = f(1, oldArg = 2)
1968"#;
1969
1970 let result = parse_execute(program).await.unwrap();
1971 let warnings = deprecation_warnings(&result);
1972 assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
1973 assert_eq!(warnings[0].severity, Severity::Warning);
1974 assert!(
1975 warnings[0].message.contains("`f(oldArg)` is deprecated"),
1976 "found {}",
1977 warnings[0].message
1978 );
1979 }
1980
1981 #[tokio::test(flavor = "multi_thread")]
1982 async fn not_passing_deprecated_param_does_not_warn() {
1983 let program = r#"fn f(
1984 @a: number,
1985 @(deprecated = true)
1986 oldArg?: number,
1987) {
1988 return a
1989}
1990x = f(1)
1991"#;
1992
1993 let result = parse_execute(program).await.unwrap();
1994 let warnings = deprecation_warnings(&result);
1995 assert!(
1996 warnings.is_empty(),
1997 "unused deprecated parameter should not warn: {warnings:#?}"
1998 );
1999 }
2000
2001 #[tokio::test(flavor = "multi_thread")]
2002 async fn deprecated_calls_inside_kcl_stdlib_do_not_warn() {
2003 let program = include_str!("../../tests/cube_with_hole/input.kcl");
2004
2005 let result = parse_execute(program).await.unwrap();
2006 let warnings = deprecation_warnings(&result);
2007 assert!(
2008 warnings.is_empty(),
2009 "KCL stdlib internals should not emit deprecation warnings: {warnings:#?}"
2010 );
2011 }
2012
2013 #[tokio::test(flavor = "multi_thread")]
2014 async fn deprecated_stdlib_call_from_user_code_still_warns() {
2015 let program = r#"@settings(kclVersion = 2.0)
2016plane = startSketchOn(XY)
2017"#;
2018
2019 let result = parse_execute(program).await.unwrap();
2020 let warnings = deprecation_warnings(&result);
2021 assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
2022 assert!(
2023 warnings[0].message.contains("`startSketchOn` is deprecated"),
2024 "found {}",
2025 warnings[0].message
2026 );
2027 }
2028}