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