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::kcl_value::ParamUnavailable;
31use crate::execution::memory;
32use crate::execution::types::CoercionMode;
33use crate::execution::types::RuntimeType;
34use crate::parsing::ast::types::CallExpressionKw;
35use crate::parsing::ast::types::Node;
36use crate::parsing::ast::types::Type;
37use crate::std::ConsumedSolidArgCheck;
38use crate::std::RegionBehavior;
39use crate::std::StaleRegionPolicy;
40use crate::std::region_consumption::PendingRegionConsumption;
41use crate::std::region_consumption::prepare_region_consumption;
42use crate::std::region_consumption::record_consumed_regions;
43use crate::std::region_consumption::validate_region_args_not_consumed;
44use crate::std::region_consumption::warn_if_region_args_consumed;
45use crate::std::solid_consumption::validate_value_not_consumed;
46use crate::std::solid_consumption::warn_if_value_consumed_for_deprecated_call;
47
48#[derive(Debug, Clone)]
49pub struct Args<Status: ArgsStatus = Desugared> {
50 pub fn_name: Option<String>,
52 pub unlabeled: Vec<(Option<String>, Arg)>,
56 pub labeled: IndexMap<String, Arg>,
58 pub source_range: SourceRange,
59 pub node_path: Option<NodePath>,
60 pub ctx: ExecutorContext,
61 pub pipe_value: Option<Arg>,
64 _status: std::marker::PhantomData<Status>,
65}
66
67pub trait ArgsStatus: std::fmt::Debug + Clone {}
68
69#[derive(Debug, Clone)]
70pub struct Sugary;
71impl ArgsStatus for Sugary {}
72
73#[derive(Debug, Clone)]
79pub struct Desugared;
80impl ArgsStatus for Desugared {}
81
82impl Args<Sugary> {
83 pub fn new(
85 labeled: IndexMap<String, Arg>,
86 unlabeled: Vec<(Option<String>, Arg)>,
87 source_range: SourceRange,
88 node_path: Option<NodePath>,
89 exec_state: &mut ExecState,
90 ctx: ExecutorContext,
91 fn_name: Option<String>,
92 ) -> Args<Sugary> {
93 Args {
94 fn_name,
95 labeled,
96 unlabeled,
97 source_range,
98 node_path,
99 ctx,
100 pipe_value: exec_state.pipe_value().map(|v| Arg::new(v.clone(), source_range)),
101 _status: std::marker::PhantomData,
102 }
103 }
104}
105
106impl<Status: ArgsStatus> Args<Status> {
107 pub fn len(&self) -> usize {
109 self.labeled.len() + self.unlabeled.len()
110 }
111
112 pub fn is_empty(&self) -> bool {
114 self.labeled.is_empty() && self.unlabeled.is_empty()
115 }
116}
117
118impl Args<Desugared> {
119 pub fn new_no_args(
120 source_range: SourceRange,
121 node_path: Option<NodePath>,
122 ctx: ExecutorContext,
123 fn_name: Option<String>,
124 ) -> Args {
125 Args {
126 fn_name,
127 unlabeled: Default::default(),
128 labeled: Default::default(),
129 source_range,
130 node_path,
131 ctx,
132 pipe_value: None,
133 _status: std::marker::PhantomData,
134 }
135 }
136
137 pub(crate) fn unlabeled_kw_arg_unconverted(&self) -> Option<&Arg> {
139 self.unlabeled.first().map(|(_, a)| a)
140 }
141}
142
143#[derive(Debug, Clone)]
144pub struct Arg {
145 pub value: KclValue,
147 pub source_range: SourceRange,
149}
150
151impl Arg {
152 pub fn new(value: KclValue, source_range: SourceRange) -> Self {
153 Self { value, source_range }
154 }
155
156 pub fn synthetic(value: KclValue) -> Self {
157 Self {
158 value,
159 source_range: SourceRange::synthetic(),
160 }
161 }
162
163 pub fn source_ranges(&self) -> Vec<SourceRange> {
164 vec![self.source_range]
165 }
166}
167
168impl Node<CallExpressionKw> {
169 #[async_recursion]
170 pub(super) async fn execute(
171 &self,
172 exec_state: &mut ExecState,
173 ctx: &ExecutorContext,
174 ) -> Result<KclValueControlFlow, KclError> {
175 let fn_name = &self.callee;
176 let callsite: SourceRange = self.into();
177
178 let func: KclValue = fn_name.get_result(exec_state, ctx).await?;
181
182 let Some(fn_src) = func.as_function() else {
183 return Err(KclError::new_semantic(KclErrorDetails::new(
184 "cannot call this because it isn't a function".to_string(),
185 vec![callsite],
186 )));
187 };
188
189 let mut fn_args = IndexMap::with_capacity(self.arguments.len());
191 let mut unlabeled = Vec::new();
192
193 if let Some(ref arg_expr) = self.unlabeled {
195 let source_range = SourceRange::from(arg_expr.clone());
196 let metadata = Metadata { source_range };
197 let value_cf = ctx
198 .execute_expr(arg_expr, exec_state, &metadata, &[], StatementKind::Expression)
199 .await?;
200 let value = control_continue!(value_cf);
201
202 let label = arg_expr.ident_name().map(str::to_owned);
203
204 unlabeled.push((label, Arg::new(value, source_range)))
205 }
206
207 for arg_expr in &self.arguments {
208 let source_range = SourceRange::from(arg_expr.arg.clone());
209 let metadata = Metadata { source_range };
210 let value_cf = ctx
211 .execute_expr(&arg_expr.arg, exec_state, &metadata, &[], StatementKind::Expression)
212 .await?;
213 let value = control_continue!(value_cf);
214 let arg = Arg::new(value, source_range);
215 match &arg_expr.label {
216 Some(l) => {
217 fn_args.insert(l.name.clone(), arg);
218 }
219 None => {
220 unlabeled.push((arg_expr.arg.ident_name().map(str::to_owned), arg));
221 }
222 }
223 }
224
225 let args = Args::new(
226 fn_args,
227 unlabeled,
228 callsite,
229 self.node_path.clone(),
230 exec_state,
231 ctx.clone(),
232 Some(fn_name.name.name.clone()),
233 );
234
235 let return_value = fn_src
236 .call_kw(Some(fn_name.to_string()), exec_state, ctx, args, callsite)
237 .await
238 .map_err(|e| {
239 e.add_unwind_location(Some(fn_name.to_string()), callsite)
244 })?;
245
246 let result = return_value.ok_or_else(move || {
247 let mut source_ranges: Vec<SourceRange> = vec![callsite];
248 if let KclValue::Function { meta, .. } = func {
250 source_ranges = meta.iter().map(|m| m.source_range).collect();
251 };
252 KclError::new_undefined_value(
253 KclErrorDetails::new(
254 format!("Result of user-defined function {fn_name} is undefined"),
255 source_ranges,
256 ),
257 None,
258 )
259 })?;
260
261 Ok(result)
262 }
263}
264
265const SKETCH_V1_MIGRATION_HELP: &str = "It is part of the legacy sketch API (sketch v1), which is replaced by the sketch-solve API.
270
271See https://zoo.dev/docs/kcl-book/sketch2d_constraints.html for an introduction to sketch-solve with examples.
272
273Draw 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()`. ";
274
275fn migration_help(fn_src: &FunctionSource) -> Option<&'static str> {
278 let name = &fn_src.std_props.as_ref()?.name;
279 name.starts_with("std::sketch::").then_some(SKETCH_V1_MIGRATION_HELP)
282}
283
284impl FunctionSource {
285 pub(crate) async fn call_kw(
286 &self,
287 fn_name: Option<String>,
288 exec_state: &mut ExecState,
289 ctx: &ExecutorContext,
290 args: Args<Sugary>,
291 callsite: SourceRange,
292 ) -> Result<Option<KclValueControlFlow>, KclError> {
293 exec_state.inc_call_stack_size(callsite)?;
294
295 let result = self.inner_call_kw(fn_name, exec_state, ctx, args, callsite).await;
296
297 exec_state.dec_call_stack_size(callsite)?;
298 result
299 }
300
301 async fn inner_call_kw(
302 &self,
303 fn_name: Option<String>,
304 exec_state: &mut ExecState,
305 ctx: &ExecutorContext,
306 args: Args<Sugary>,
307 callsite: SourceRange,
308 ) -> Result<Option<KclValueControlFlow>, KclError> {
309 let (state, args) = self.call_setup(&fn_name, exec_state, args, callsite)?;
310 let result = match &self.body {
314 FunctionBody::Rust(f) => f(exec_state, args).await.map(Some),
315 FunctionBody::Kcl(_) => {
316 if let Err(e) = assign_args_to_params_kw(self, args, exec_state) {
317 return Err(Self::call_abort_on_arg_binding_failure(state, e, exec_state));
318 }
319
320 let block_result = ctx.exec_block(&self.ast.body, exec_state, BodyType::Block).await;
321 self.kcl_body_result(block_result, exec_state)
322 }
323 };
324 self.call_finish(state, result, exec_state)
325 }
326
327 pub(super) fn call_setup(
336 &self,
337 fn_name: &Option<String>,
338 exec_state: &mut ExecState,
339 args: Args<Sugary>,
340 callsite: SourceRange,
341 ) -> Result<(CallState, Args), KclError> {
342 let warn_on_deprecated_usage = !exec_state.mod_local.inside_stdlib;
344 if warn_on_deprecated_usage {
345 let subject = match &fn_name {
346 Some(n) => format!("`{n}`"),
347 None => "This function".to_owned(),
348 };
349 let message = if self.deprecated {
350 Some(match migration_help(self) {
351 Some(help) => format!("{subject} is deprecated. {help}"),
352 None => format!("{subject} is deprecated, see the docs for a recommended replacement"),
353 })
354 } else if let Some(since) = &self.deprecated_since
355 && annotations::version_ge(exec_state.deprecation_version(), since)
356 {
357 Some(match migration_help(self) {
358 Some(help) => format!("{subject} is deprecated as of KCL {since}. {help}"),
359 None => {
360 format!(
361 "{subject} is deprecated as of KCL {since}. See the docs for a recommended replacement."
362 )
363 }
364 })
365 } else {
366 None
367 };
368 if let Some(message) = message {
369 let mut issue = CompilationIssue::err(callsite, message);
370 issue.tag = crate::errors::Tag::Deprecated;
371 exec_state.warn(issue, annotations::WARN_DEPRECATED);
372 }
373 }
374 if self.experimental {
375 exec_state.warn_experimental(
376 &match &fn_name {
377 Some(n) => format!("`{n}`"),
378 None => "This function".to_owned(),
379 },
380 callsite,
381 );
382 }
383
384 let args = type_check_params_kw(fn_name.as_deref(), self, args, exec_state)?;
385 let face_tag_names = face_tag_names_for_call(self, &args);
386 let pending_region_consumption = prepare_region_consumption(
387 self.std_props
388 .as_ref()
389 .map_or(RegionBehavior::WarnOnConsumed, |props| props.region_behavior),
390 &args,
391 exec_state,
392 )?;
393
394 for (label, arg) in &args.labeled {
396 let Some(param) = self.named_args.get(label.as_str()) else {
397 continue;
398 };
399 if param.experimental {
400 exec_state.warn_experimental(
401 &match &fn_name {
402 Some(f) => format!("`{f}({label})`"),
403 None => label.to_owned(),
404 },
405 arg.source_range,
406 );
407 }
408 let deprecation_suffix = if !warn_on_deprecated_usage {
411 None
412 } else if param.deprecated {
413 Some("is deprecated, see the docs for a recommended replacement".to_owned())
414 } else if let Some(since) = ¶m.deprecated_since
415 && annotations::version_ge(exec_state.deprecation_version(), since)
416 {
417 Some(format!(
418 "is deprecated as of KCL {since}. See the docs for a recommended replacement."
419 ))
420 } else {
421 None
422 };
423 if let Some(suffix) = deprecation_suffix {
424 let qualified = match &fn_name {
425 Some(f) => format!("`{f}({label})`"),
426 None => format!("`{label}`"),
427 };
428 let mut issue = CompilationIssue::err(arg.source_range, format!("{qualified} {suffix}"));
429 issue.tag = crate::errors::Tag::Deprecated;
430 exec_state.warn(issue, annotations::WARN_DEPRECATED);
431 }
432 }
433
434 self.body.prep_mem(exec_state)?;
436
437 let would_trace_stdlib_internals = exec_state.mod_local.inside_stdlib && self.is_std();
449 let should_track_operation = !would_trace_stdlib_internals && self.include_in_feature_tree;
451 let op = if should_track_operation {
452 let op_labeled_args = args
453 .labeled
454 .iter()
455 .map(|(k, arg)| (k.clone(), OpArg::new(op_from_kcl_value(&arg.value), arg.source_range)))
456 .collect();
457
458 if self.is_std() {
460 Some(Operation::StdLibCall {
461 name: fn_name.clone().unwrap_or_else(|| "unknown function".to_owned()),
462 unlabeled_arg: args
463 .unlabeled_kw_arg_unconverted()
464 .map(|arg| OpArg::new(op_from_kcl_value(&arg.value), arg.source_range)),
465 labeled_args: op_labeled_args,
466 node_path: NodePath::placeholder(),
467 source_range: callsite,
468 stdlib_entry_source_range: exec_state.mod_local.stdlib_entry_source_range,
469 is_error: false,
470 })
471 } else {
472 exec_state.push_op(Operation::GroupBegin {
474 group: Group::FunctionCall {
475 name: fn_name.clone(),
476 function_source_range: self.ast.as_source_range(),
477 unlabeled_arg: args
478 .unlabeled_kw_arg_unconverted()
479 .map(|arg| OpArg::new(op_from_kcl_value(&arg.value), arg.source_range)),
480 labeled_args: op_labeled_args,
481 },
482 node_path: NodePath::placeholder(),
483 source_range: callsite,
484 });
485
486 None
487 }
488 } else {
489 None
490 };
491
492 let is_calling_into_stdlib = match &self.body {
493 FunctionBody::Rust(_) => true,
494 FunctionBody::Kcl(_) => self.is_std(),
495 };
496 let is_crossing_into_stdlib = is_calling_into_stdlib && !exec_state.mod_local.inside_stdlib;
497 let is_crossing_out_of_stdlib = !is_calling_into_stdlib && exec_state.mod_local.inside_stdlib;
498 let stdlib_entry_source_range = if is_crossing_into_stdlib {
499 Some(callsite)
503 } else if is_crossing_out_of_stdlib {
504 None
508 } else {
509 exec_state.mod_local.stdlib_entry_source_range
512 };
513
514 let prev_inside_stdlib = std::mem::replace(&mut exec_state.mod_local.inside_stdlib, is_calling_into_stdlib);
515 let prev_stdlib_entry_source_range = std::mem::replace(
516 &mut exec_state.mod_local.stdlib_entry_source_range,
517 stdlib_entry_source_range,
518 );
519
520 Ok((
521 CallState {
522 prev_inside_stdlib,
523 prev_stdlib_entry_source_range,
524 op,
525 should_track_operation,
526 is_calling_into_stdlib,
527 face_tag_names,
528 pending_region_consumption,
529 },
530 args,
531 ))
532 }
533
534 pub(super) fn kcl_body_result(
546 &self,
547 block_result: Result<Option<KclValueControlFlow>, KclError>,
548 exec_state: &mut ExecState,
549 ) -> Result<Option<KclValueControlFlow>, KclError> {
550 block_result.map(|cf| {
551 if let Some(cf) = cf
552 && cf.is_some_return()
553 {
554 return Some(cf);
555 }
556 exec_state
559 .stack()
560 .get(memory::RETURN_NAME, self.ast.as_source_range())
561 .ok()
562 .map(KclValue::continue_)
563 })
564 }
565
566 pub(super) fn call_abort_on_arg_binding_failure(
573 state: CallState,
574 e: KclError,
575 exec_state: &mut ExecState,
576 ) -> KclError {
577 exec_state.mod_local.inside_stdlib = state.prev_inside_stdlib;
578 match exec_state.mut_stack().pop_env() {
579 Ok(_) => e,
580 Err(pop_err) => pop_err,
581 }
582 }
583
584 pub(super) fn call_finish(
594 &self,
595 state: CallState,
596 result: Result<Option<KclValueControlFlow>, KclError>,
597 exec_state: &mut ExecState,
598 ) -> Result<Option<KclValueControlFlow>, KclError> {
599 let CallState {
600 prev_inside_stdlib,
601 prev_stdlib_entry_source_range,
602 op,
603 should_track_operation,
604 is_calling_into_stdlib,
605 face_tag_names,
606 pending_region_consumption,
607 } = state;
608 exec_state.mod_local.inside_stdlib = prev_inside_stdlib;
609 exec_state.mod_local.stdlib_entry_source_range = prev_stdlib_entry_source_range;
610 exec_state.mut_stack().pop_env()?;
611
612 if result.is_ok()
613 && let Some(pending_region_consumption) = pending_region_consumption
614 {
615 record_consumed_regions(exec_state, pending_region_consumption);
616 }
617
618 if should_track_operation {
619 if let Some(mut op) = op {
620 op.set_std_lib_call_is_error(result.is_err());
621 exec_state.push_op(op);
627 } else if !is_calling_into_stdlib {
628 exec_state.push_op(Operation::GroupEnd);
629 }
630 }
631
632 let mut result = match result {
633 Ok(Some(value)) => {
634 if value.is_exit() {
635 return Ok(Some(value));
639 } else {
640 Ok(Some(value.into_value()))
643 }
644 }
645 Ok(None) => Ok(None),
646 Err(e) => Err(e),
647 };
648
649 if self.is_std()
650 && let Ok(Some(result)) = &mut result
651 {
652 update_memory_for_tags_of_geometry(result, exec_state)?;
653 if !face_tag_names.is_empty() {
654 attach_face_tags_to_geometry(result, exec_state, &face_tag_names);
655 }
656 }
657
658 coerce_result_type(result, self, exec_state).map(|r| r.map(KclValue::continue_))
659 }
660}
661
662#[derive(Debug)]
666pub(super) struct CallState {
667 prev_inside_stdlib: bool,
668 prev_stdlib_entry_source_range: Option<SourceRange>,
669 op: Option<Operation>,
671 should_track_operation: bool,
672 is_calling_into_stdlib: bool,
673 face_tag_names: Vec<String>,
674 pending_region_consumption: Option<PendingRegionConsumption>,
675}
676
677impl FunctionBody {
678 fn prep_mem(&self, exec_state: &mut ExecState) -> Result<(), KclError> {
679 match self {
680 FunctionBody::Rust(_) => exec_state.mut_stack().push_new_root_env(true),
681 FunctionBody::Kcl(memory) => exec_state.mut_stack().push_new_env_for_call(*memory),
682 }
683 }
684}
685
686fn might_be_legacy_sketch(value: &KclValue) -> bool {
695 match value {
696 KclValue::Uuid { .. } => false,
697 KclValue::Bool { .. } => false,
698 KclValue::Number { .. } => false,
699 KclValue::String { .. } => false,
700 KclValue::Enum { .. } => false,
701 KclValue::SketchVar { .. } => false,
702 KclValue::SketchConstraint { .. } => false,
703 KclValue::Tuple { value, .. } => value.iter().any(might_be_legacy_sketch),
704 KclValue::HomArray { value, .. } => value.iter().any(might_be_legacy_sketch),
705 KclValue::Object { value, .. } => value.values().any(might_be_legacy_sketch),
707 KclValue::TagIdentifier(_) => false,
708 KclValue::TagDeclarator(_) => false,
709 KclValue::GdtAnnotation { .. } => false,
710 KclValue::CameraView { .. } => false,
711 KclValue::NamedView { .. } => false,
712 KclValue::Plane { .. } => false,
713 KclValue::Face { .. } => false,
714 KclValue::BoundedEdge { .. } => false,
715 KclValue::Segment { .. } => false,
716 KclValue::Sketch { value: sketch } => sketch.origin_sketch_id.is_none(),
717 KclValue::Solid { value: solid } => solid
721 .sketch()
722 .map(|sketch| sketch.origin_sketch_id.is_none())
723 .unwrap_or(true),
724 KclValue::Helix { .. } => false,
725 KclValue::ImportedGeometry(_) => false,
726 KclValue::Function { .. } => false,
727 KclValue::Module { .. } => false,
728 KclValue::Type { .. } => false,
729 KclValue::KclNone { .. } => false,
730 }
731}
732
733fn face_tag_names_for_call(fn_def: &FunctionSource, args: &Args<Desugared>) -> Vec<String> {
734 let Some(std_props) = &fn_def.std_props else {
735 return Vec::new();
736 };
737
738 if !std_function_allows_face_tags(&std_props.name) {
739 return Vec::new();
740 }
741
742 args.labeled
743 .iter()
744 .filter(|(label, _)| matches!(label.as_str(), "tag" | "tagStart" | "tagEnd"))
745 .filter_map(|(_, arg)| match &arg.value {
746 KclValue::TagDeclarator(tag) => Some(tag.name.clone()),
747 _ => None,
748 })
749 .collect()
750}
751
752fn std_function_allows_face_tags(std_fn_name: &str) -> bool {
753 matches!(
754 std_fn_name,
755 "std::sketch::extrude"
756 | "std::solid::chamfer"
757 | "std::solid::fillet"
758 | "std::sketch::sweep"
759 | "std::sketch::loft"
760 | "std::sketch::revolve"
761 )
762}
763
764fn attach_face_tags_to_geometry(result: &mut KclValue, exec_state: &ExecState, tag_names: &[String]) {
765 match result {
766 KclValue::Solid { value } => attach_face_tags_to_solid(value, exec_state, tag_names),
767 KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
768 for v in value {
769 attach_face_tags_to_geometry(v, exec_state, tag_names);
770 }
771 }
772 _ => {}
773 }
774}
775
776fn attach_face_tags_to_solid(solid: &mut Solid, exec_state: &ExecState, tag_names: &[String]) {
777 let surfaces = solid.value.clone();
778 for surface in surfaces {
779 let Some(tag) = surface.get_tag() else {
780 continue;
781 };
782 if !tag_names.iter().any(|tag_name| tag_name == &tag.name) {
783 continue;
784 }
785
786 let tag_id = solid
787 .sketch()
788 .and_then(|sketch| sketch.tags.get(&tag.name))
789 .cloned()
790 .unwrap_or_else(|| {
791 let mut solid_copy = solid.clone();
792 clear_tags_from_solid_copy(&mut solid_copy);
793 TagIdentifier {
794 value: tag.name.clone(),
795 info: vec![(
796 exec_state.stack().current_epoch(),
797 TagEngineInfo {
798 id: surface.get_id(),
799 surface: Some(surface.clone()),
800 path: None,
801 geometry: Geometry::Solid(solid_copy),
802 },
803 )],
804 meta: vec![Metadata {
805 source_range: tag.clone().into(),
806 }],
807 }
808 });
809
810 match solid.faces.get_mut(&tag.name) {
811 Some(existing_tag) => existing_tag.merge_info(&tag_id),
812 None => {
813 solid.faces.insert(tag.name.clone(), tag_id);
814 }
815 }
816 }
817}
818
819fn clear_tags_from_solid_copy(solid: &mut Solid) {
820 if let Some(sketch) = solid.sketch_mut() {
821 sketch.tags.clear(); }
823 solid.faces.clear();
824}
825
826fn update_memory_for_tags_of_geometry(result: &mut KclValue, exec_state: &mut ExecState) -> Result<(), KclError> {
827 let might_be_legacy = might_be_legacy_sketch(&*result);
828 match result {
833 KclValue::Sketch { value } if might_be_legacy => {
834 for (name, tag) in value.tags.iter() {
835 if exec_state.stack().cur_frame_contains(name)? {
836 exec_state.mut_stack().update(name, |v, _| {
837 if let Some(existing_tag) = v.as_mut_tag() {
838 existing_tag.merge_info(tag);
839 }
840 })?;
841 } else {
842 exec_state.mut_stack().add(
843 name.to_owned(),
844 KclValue::TagIdentifier(Box::new(tag.clone())),
845 SourceRange::default(),
846 )?;
847 }
848 }
849 }
850 KclValue::Solid { value } => {
851 if value.sketch().is_none() {
852 return Ok(());
855 };
856 let surfaces: Vec<_> = value
859 .value
860 .iter()
861 .filter(|surface| surface.get_tag().is_some())
862 .cloned()
863 .collect();
864 let solid_copies: Vec<Box<Solid>> = surfaces.iter().map(|_| value.clone()).collect();
866 let Some(sketch) = value.sketch_mut() else {
869 return Ok(());
870 };
871 for (v, mut solid_copy) in surfaces.iter().zip(solid_copies) {
872 clear_tags_from_solid_copy(&mut solid_copy);
873 if let Some(tag) = v.get_tag() {
874 let mut is_part_of_sketch = false;
876 let tag_id = if let Some(t) = sketch.tags.get(&tag.name) {
877 is_part_of_sketch = true;
878 let mut t = t.clone();
879 let Some(info) = t.get_cur_info() else {
880 return Err(KclError::new_internal(KclErrorDetails::new(
881 format!("Tag {} does not have path info", tag.name),
882 vec![tag.into()],
883 )));
884 };
885
886 let mut info = info.clone();
887 info.id = v.get_id();
888 info.surface = Some(v.clone());
889 info.geometry = Geometry::Solid(*solid_copy);
890 t.info.push((exec_state.stack().current_epoch(), info));
891 t
892 } else {
893 TagIdentifier {
896 value: tag.name.clone(),
897 info: vec![(
898 exec_state.stack().current_epoch(),
899 TagEngineInfo {
900 id: v.get_id(),
901 surface: Some(v.clone()),
902 path: None,
903 geometry: Geometry::Solid(*solid_copy),
904 },
905 )],
906 meta: vec![Metadata {
907 source_range: tag.clone().into(),
908 }],
909 }
910 };
911
912 sketch.merge_tags(Some(&tag_id).into_iter());
914
915 if exec_state.stack().cur_frame_contains(&tag.name)? {
916 exec_state.mut_stack().update(&tag.name, |v, _| {
917 if let Some(existing_tag) = v.as_mut_tag() {
918 existing_tag.merge_info(&tag_id);
919 }
920 })?;
921 } else if might_be_legacy || !is_part_of_sketch {
922 exec_state.mut_stack().add(
932 tag.name.clone(),
933 KclValue::TagIdentifier(Box::new(tag_id)),
934 SourceRange::default(),
935 )?;
936 }
937 }
938 }
939
940 if let Some(sketch) = value.sketch() {
942 if sketch.tags.is_empty() {
943 return Ok(());
944 }
945 let sketch_tags: Vec<_> = sketch.tags.values().cloned().collect();
946 let sketches_to_update: Vec<_> = exec_state.stack().find_keys_in_current_env(|v| match v {
947 KclValue::Sketch { value: sk } => sk.original_id == sketch.original_id,
948 _ => false,
949 })?;
950
951 for k in sketches_to_update {
952 exec_state.mut_stack().update(&k, |v, _| {
953 if let Some(sketch) = v.as_mut_sketch() {
954 sketch.merge_tags(sketch_tags.iter());
955 }
956 })?;
957 }
958 }
959 }
960 KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
961 for v in value {
962 update_memory_for_tags_of_geometry(v, exec_state)?;
963 }
964 }
965 _ => {}
966 }
967 Ok(())
968}
969
970fn type_err_str(expected: &Type, found: &KclValue, source_range: &SourceRange, exec_state: &mut ExecState) -> String {
971 fn strip_backticks(s: &str) -> &str {
972 let mut result = s;
973 if s.starts_with('`') {
974 result = &result[1..]
975 }
976 if s.ends_with('`') {
977 result = &result[..result.len() - 1]
978 }
979 result
980 }
981
982 let expected_human = expected.human_friendly_type();
983 let expected_ty = expected.to_string();
984 let expected_str =
985 if expected_human == expected_ty || expected_human == format!("a value with type `{expected_ty}`") {
986 format!("a value with type `{expected_ty}`")
987 } else {
988 format!("{expected_human} (`{expected_ty}`)")
989 };
990 let found_human = found.human_friendly_type();
991 let found_ty = found.principal_type_string();
992 let found_str = if found_human == found_ty || found_human == format!("a {}", strip_backticks(&found_ty)) {
993 format!("a value with type {found_ty}")
994 } else {
995 format!("{found_human} (with type {found_ty})")
996 };
997
998 let mut result = format!("{expected_str}, but found {found_str}.");
999
1000 if found.is_unknown_number() {
1001 exec_state.clear_units_warnings(source_range);
1002 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`.");
1003 }
1004
1005 result
1006}
1007
1008pub(crate) fn unexpected_kw_arg_message(label: &str, callee_name: Option<&str>) -> String {
1012 format!(
1013 "`{label}` is not an argument of {}",
1014 callee_name
1015 .map(|n| format!("`{n}`"))
1016 .unwrap_or_else(|| "this function".to_owned()),
1017 )
1018}
1019
1020fn unavailable_kw_arg_message(
1026 label: &str,
1027 callee_name: Option<&str>,
1028 reason: ParamUnavailable<'_>,
1029 program_version: &str,
1030) -> String {
1031 let base = unexpected_kw_arg_message(label, callee_name);
1032 match reason {
1033 ParamUnavailable::NotYetAdded(added) => {
1034 format!("{base}; it was added in KCL {added}, but this program uses KCL {program_version}")
1035 }
1036 ParamUnavailable::Removed(removed) => {
1037 format!("{base}; it was removed in KCL {removed}, but this program uses KCL {program_version}")
1038 }
1039 }
1040}
1041
1042fn resolved_signature_type<'a>(
1049 resolved: Option<&'a RuntimeType>,
1050 written: &Type,
1051 source_range: SourceRange,
1052) -> Result<&'a RuntimeType, KclError> {
1053 resolved.ok_or_else(|| {
1054 KclError::new_internal(KclErrorDetails::new(
1055 format!(
1056 "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."
1057 ),
1058 vec![source_range],
1059 ))
1060 })
1061}
1062
1063fn type_check_params_kw(
1064 fn_name: Option<&str>,
1065 fn_def: &FunctionSource,
1066 mut args: Args<Sugary>,
1067 exec_state: &mut ExecState,
1068) -> Result<Args<Desugared>, KclError> {
1069 let fn_name = fn_name.or(args.fn_name.as_deref());
1070 let mut result = Args::new_no_args(
1071 args.source_range,
1072 args.node_path.clone(),
1073 args.ctx,
1074 fn_name.map(|f| f.to_string()).or_else(|| args.fn_name.clone()),
1075 );
1076
1077 if let Some((Some(label), _)) = args.unlabeled.first()
1080 && args.unlabeled.len() == 1
1081 && (fn_def.input_arg.is_none() || args.pipe_value.is_some())
1082 && fn_def.active_named_arg(label, exec_state).is_some()
1083 && !args.labeled.contains_key(label)
1084 {
1085 let Some((label, arg)) = args.unlabeled.pop() else {
1086 let message = "Expected unlabeled arg to be present".to_owned();
1087 debug_assert!(false, "{}", &message);
1088 return Err(KclError::new_internal(KclErrorDetails::new(
1089 message,
1090 vec![args.source_range],
1091 )));
1092 };
1093 args.labeled.insert(label.unwrap(), arg);
1094 }
1095
1096 let (labeled_unlabeled, unlabeled_unlabeled) = args.unlabeled.into_iter().partition(|(l, _)| {
1098 if let Some(l) = l
1099 && fn_def.active_named_arg(l, exec_state).is_some()
1100 && !args.labeled.contains_key(l)
1101 {
1102 true
1103 } else {
1104 false
1105 }
1106 });
1107 args.unlabeled = unlabeled_unlabeled;
1108 for (l, arg) in labeled_unlabeled {
1109 let previous = args.labeled.insert(l.unwrap(), arg);
1110 debug_assert!(previous.is_none());
1111 }
1112
1113 if let Some((name, ty)) = &fn_def.input_arg {
1114 if args.unlabeled.is_empty() {
1117 if let Some(pipe) = args.pipe_value {
1120 result.unlabeled = vec![(None, pipe)];
1122 } else if let Some(arg) = args.labeled.swap_remove(name) {
1123 exec_state.err(CompilationIssue::err(
1125 arg.source_range,
1126 format!(
1127 "{} expects an unlabeled first argument (`@{name}`), but it is labelled in the call. You might try removing the `{name} = `",
1128 fn_name
1129 .map(|n| format!("The function `{n}`"))
1130 .unwrap_or_else(|| "This function".to_owned()),
1131 ),
1132 ));
1133 result.unlabeled = vec![(Some(name.clone()), arg)];
1134 } else {
1135 return Err(KclError::new_argument(KclErrorDetails::new(
1137 "This function expects an unlabeled first parameter, but you haven't passed it one.".to_owned(),
1138 fn_def.ast.as_source_ranges(),
1139 )));
1140 }
1141 } else if args.unlabeled.len() == 1
1142 && let Some(unlabeled_arg) = args.unlabeled.pop()
1143 {
1144 let mut arg = unlabeled_arg.1;
1145 if let Some(ty) = ty {
1146 let rty = resolved_signature_type(fn_def.resolved_input_ty.as_ref(), ty, arg.source_range)?;
1147 arg.value = arg
1148 .value
1149 .coerce(rty, CoercionMode::implicit(), exec_state)
1150 .map_err(|_| {
1151 KclError::new_argument(KclErrorDetails::new(
1152 format!(
1153 "The input argument of {} requires {}",
1154 fn_name
1155 .map(|n| format!("`{n}`"))
1156 .unwrap_or_else(|| "this function".to_owned()),
1157 type_err_str(ty, &arg.value, &arg.source_range, exec_state),
1158 ),
1159 vec![arg.source_range],
1160 ))
1161 })?;
1162 }
1163 result.unlabeled = vec![(None, arg)]
1164 } else {
1165 if let Some(Type::Array { len, .. }) = ty {
1169 if len.satisfied(args.unlabeled.len(), false).is_none() {
1170 exec_state.err(CompilationIssue::err(
1171 args.source_range,
1172 format!(
1173 "{} expects an array input argument with {} elements",
1174 fn_name
1175 .map(|n| format!("The function `{n}`"))
1176 .unwrap_or_else(|| "This function".to_owned()),
1177 len.human_friendly_type(),
1178 ),
1179 ));
1180 }
1181
1182 let source_range = SourceRange::merge(args.unlabeled.iter().map(|(_, a)| a.source_range));
1183 exec_state.warn_experimental("array input arguments", source_range);
1184 result.unlabeled = vec![(
1185 None,
1186 Arg {
1187 source_range,
1188 value: KclValue::HomArray {
1189 value: args.unlabeled.drain(..).map(|(_, a)| a.value).collect(),
1190 ty: RuntimeType::any(),
1191 },
1192 },
1193 )]
1194 }
1195 }
1196 }
1197
1198 if !args.unlabeled.is_empty() {
1200 let actuals = args.labeled.keys();
1202 let formals: Vec<_> = fn_def
1203 .active_named_args(exec_state)
1204 .filter_map(|(name, _)| {
1205 if actuals.clone().any(|a| a == name) {
1206 return None;
1207 }
1208
1209 Some(format!("`{name}`"))
1210 })
1211 .collect();
1212
1213 let suggestion = if formals.is_empty() {
1214 String::new()
1215 } else {
1216 format!("; suggested labels: {}", formals.join(", "))
1217 };
1218
1219 let mut errors = args.unlabeled.iter().map(|(_, arg)| {
1220 CompilationIssue::err(
1221 arg.source_range,
1222 format!("This argument needs a label, but it doesn't have one{suggestion}"),
1223 )
1224 });
1225
1226 let first = errors.next().unwrap();
1227 errors.for_each(|e| exec_state.err(e));
1228
1229 return Err(KclError::new_argument(first.into()));
1230 }
1231
1232 for (label, mut arg) in args.labeled {
1233 let param = fn_def.named_args.get(&label);
1234 match param.map(|param| (param, param.unavailable_reason(exec_state))) {
1235 Some((
1236 NamedParam {
1237 experimental: _,
1238 added_in: _,
1239 deprecated: _,
1240 deprecated_since: _,
1241 removed_in: _,
1242 default_value: def,
1243 ty,
1244 resolved_ty,
1245 },
1246 None,
1247 )) => {
1248 if !(def.is_some() && matches!(arg.value, KclValue::KclNone { .. })) {
1250 if let Some(ty) = ty {
1251 let rty = resolved_signature_type(resolved_ty.as_ref(), ty, arg.source_range)?;
1252 arg.value = arg
1253 .value
1254 .coerce(
1255 rty,
1256 CoercionMode::implicit(),
1257 exec_state,
1258 )
1259 .map_err(|e| {
1260 let mut message = format!(
1261 "{label} requires {}",
1262 type_err_str(ty, &arg.value, &arg.source_range, exec_state),
1263 );
1264 if let Some(ty) = e.explicit_coercion {
1265 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}`");
1267 }
1268 KclError::new_argument(KclErrorDetails::new(
1269 message,
1270 vec![arg.source_range],
1271 ))
1272 })?;
1273 }
1274 result.labeled.insert(label, arg);
1275 }
1276 }
1277 Some((_, Some(reason))) => {
1278 let message = unavailable_kw_arg_message(&label, fn_name, reason, exec_state.kcl_version().as_str());
1279 exec_state.err(CompilationIssue::err(arg.source_range, message));
1280 }
1281 None => {
1282 exec_state.err(CompilationIssue::err(
1283 arg.source_range,
1284 unexpected_kw_arg_message(&label, fn_name),
1285 ));
1286 }
1287 }
1288 }
1289
1290 let consumed_solid_arg_check = fn_def
1291 .std_props
1292 .as_ref()
1293 .map_or(ConsumedSolidArgCheck::Error, |props| props.consumed_solid_arg_check);
1294 if matches!(fn_def.body, FunctionBody::Rust(_))
1295 && let Some(props) = fn_def.std_props.as_ref()
1296 {
1297 match props.region_behavior.stale_region_policy() {
1298 Some(StaleRegionPolicy::Error) => validate_region_args_not_consumed(&result, exec_state)?,
1299 Some(StaleRegionPolicy::Warning) => {
1300 warn_if_region_args_consumed(&result, exec_state, &props.name)?;
1301 }
1302 None => {}
1303 }
1304 }
1305 match consumed_solid_arg_check {
1306 ConsumedSolidArgCheck::Error => {
1307 result
1308 .unlabeled
1309 .iter()
1310 .map(|(_, arg)| arg)
1311 .chain(result.labeled.values())
1312 .try_for_each(|arg| validate_value_not_consumed(&arg.value, exec_state, arg.source_range))?;
1313 }
1314 ConsumedSolidArgCheck::WarnDeprecated => {
1315 let std_fn_name = fn_def
1316 .std_props
1317 .as_ref()
1318 .map(|props| props.name.as_str())
1319 .unwrap_or("function");
1320 for arg in result
1321 .unlabeled
1322 .iter()
1323 .map(|(_, arg)| arg)
1324 .chain(result.labeled.values())
1325 {
1326 warn_if_value_consumed_for_deprecated_call(&arg.value, exec_state, arg.source_range, std_fn_name)?;
1327 }
1328 }
1329 }
1330
1331 Ok(result)
1332}
1333
1334pub(super) fn assign_args_to_params_kw(
1335 fn_def: &FunctionSource,
1336 args: Args<Desugared>,
1337 exec_state: &mut ExecState,
1338) -> Result<(), KclError> {
1339 let source_ranges = fn_def.ast.as_source_ranges();
1342
1343 for (name, param) in fn_def.named_args.iter() {
1344 let arg = args.labeled.get(name);
1345 match arg {
1346 Some(arg) => {
1347 exec_state.mut_stack().add(
1348 name.clone(),
1349 arg.value.clone(),
1350 arg.source_ranges().pop().unwrap_or(SourceRange::synthetic()),
1351 )?;
1352 }
1353 None => match ¶m.default_value {
1354 Some(default_val) => {
1355 let value = KclValue::from_default_param(default_val.clone(), exec_state);
1356 exec_state
1357 .mut_stack()
1358 .add(name.clone(), value, default_val.source_range())?;
1359 }
1360 None => {
1361 return Err(KclError::new_argument(KclErrorDetails::new(
1362 format!("This function requires a parameter {name}, but you haven't passed it one."),
1363 source_ranges,
1364 )));
1365 }
1366 },
1367 }
1368 }
1369
1370 if let Some((param_name, _)) = &fn_def.input_arg {
1371 let Some(unlabeled) = args.unlabeled_kw_arg_unconverted() else {
1372 debug_assert!(false, "Bad args");
1373 return Err(KclError::new_internal(KclErrorDetails::new(
1374 "Desugared arguments are inconsistent".to_owned(),
1375 source_ranges,
1376 )));
1377 };
1378 exec_state.mut_stack().add(
1379 param_name.clone(),
1380 unlabeled.value.clone(),
1381 unlabeled.source_ranges().pop().unwrap_or(SourceRange::synthetic()),
1382 )?;
1383 }
1384
1385 Ok(())
1386}
1387
1388fn coerce_result_type(
1389 result: Result<Option<KclValue>, KclError>,
1390 fn_def: &FunctionSource,
1391 exec_state: &mut ExecState,
1392) -> Result<Option<KclValue>, KclError> {
1393 let result = result?;
1394
1395 let Some(ret_ty) = &fn_def.return_type else {
1396 return Ok(result);
1397 };
1398
1399 let ty = resolved_signature_type(
1400 fn_def.resolved_return_ty.as_ref(),
1401 &ret_ty.inner,
1402 ret_ty.as_source_range(),
1403 )?;
1404
1405 if ty.subtype(&RuntimeType::never()) {
1408 let message = if result.is_some() {
1409 "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."
1410 } else {
1411 "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."
1412 };
1413 return Err(KclError::new_type(KclErrorDetails::new(
1414 message.to_owned(),
1415 ret_ty.as_source_ranges(),
1416 )));
1417 }
1418
1419 let Some(val) = result else {
1420 return Ok(None);
1421 };
1422
1423 let val = val.coerce(ty, CoercionMode::implicit(), exec_state).map_err(|_| {
1424 KclError::new_type(KclErrorDetails::new(
1425 format!(
1426 "This function requires its result to be {}",
1427 type_err_str(ret_ty, &val, &(&val).into(), exec_state)
1428 ),
1429 ret_ty.as_source_ranges(),
1430 ))
1431 })?;
1432 Ok(Some(val))
1433}
1434
1435#[cfg(test)]
1436mod test {
1437 use std::sync::Arc;
1438
1439 use super::*;
1440 use crate::engine::engine_manager::EngineManager;
1441 use crate::errors::Severity;
1442 use crate::execution::ContextType;
1443 use crate::execution::EnvironmentRef;
1444 use crate::execution::ExecTestResults;
1445 use crate::execution::memory::Stack;
1446 use crate::execution::parse_execute;
1447 use crate::execution::types::NumericType;
1448 use crate::execution::types::NumericTypeExt;
1449 use crate::parsing::ast::types::DefaultParamVal;
1450 use crate::parsing::ast::types::FunctionExpression;
1451 use crate::parsing::ast::types::Identifier;
1452 use crate::parsing::ast::types::Parameter;
1453 use crate::parsing::ast::types::Program;
1454
1455 fn source_texts<'a>(program: &'a str, error: &KclError) -> Vec<&'a str> {
1456 error
1457 .source_ranges()
1458 .into_iter()
1459 .map(|range| &program[range.start()..range.end()])
1460 .collect()
1461 }
1462
1463 fn get_var(result: &ExecTestResults, name: &str) -> KclValue {
1464 result
1465 .exec_state
1466 .stack()
1467 .memory
1468 .get_from_owned(name, result.mem_env, SourceRange::default(), 0)
1469 .unwrap_or_else(|err| panic!("expected variable `{name}` to exist: {err:?}"))
1470 }
1471
1472 fn var_exists(result: &ExecTestResults, name: &str) -> bool {
1473 result
1474 .exec_state
1475 .stack()
1476 .memory
1477 .get_from_owned(name, result.mem_env, SourceRange::default(), 0)
1478 .is_ok()
1479 }
1480
1481 fn assert_vars_are_tags(result: &ExecTestResults, names: &[&str]) {
1482 for name in names {
1483 assert!(
1484 matches!(get_var(result, name), KclValue::TagIdentifier(_)),
1485 "expected variable `{name}` to be a tag identifier"
1486 );
1487 }
1488 }
1489
1490 fn assert_vars_are_missing(result: &ExecTestResults, names: &[&str]) {
1491 for name in names {
1492 assert!(!var_exists(result, name), "expected variable `{name}` to be absent");
1493 }
1494 }
1495
1496 fn assert_body_face_tags(result: &ExecTestResults, expected: &[&str], unexpected: &[&str]) {
1497 let body = get_var(result, "body");
1498 let KclValue::Solid { value: body } = body else {
1499 panic!("expected `body` to be a solid");
1500 };
1501
1502 for tag in expected {
1503 assert!(body.faces.contains_key(*tag), "expected body.faces to contain `{tag}`");
1504 }
1505
1506 for tag in unexpected {
1507 assert!(
1508 !body.faces.contains_key(*tag),
1509 "expected body.faces not to contain sketch tag `{tag}`"
1510 );
1511 }
1512 }
1513
1514 fn deprecated_solid_tag_access_warnings(result: &ExecTestResults) -> Vec<&CompilationIssue> {
1515 result
1516 .exec_state
1517 .issues()
1518 .iter()
1519 .filter(|issue| issue.message.contains("Accessing solid-created face"))
1520 .collect()
1521 }
1522
1523 #[tokio::test(flavor = "multi_thread")]
1524 async fn test_assign_args_to_params() {
1525 fn mem(number: usize) -> KclValue {
1527 KclValue::Number {
1528 value: number as f64,
1529 ty: NumericType::count(),
1530 meta: Default::default(),
1531 }
1532 }
1533 fn ident(s: &'static str) -> Node<Identifier> {
1534 Node::no_src(Identifier {
1535 name: s.to_owned(),
1536 digest: None,
1537 })
1538 }
1539 fn opt_param(s: &'static str) -> Parameter {
1540 Parameter {
1541 experimental: false,
1542 added_in: None,
1543 deprecated: false,
1544 deprecated_since: None,
1545 removed_in: None,
1546 identifier: ident(s),
1547 param_type: None,
1548 default_value: Some(DefaultParamVal::none()),
1549 labeled: true,
1550 digest: None,
1551 }
1552 }
1553 fn req_param(s: &'static str) -> Parameter {
1554 Parameter {
1555 experimental: false,
1556 added_in: None,
1557 deprecated: false,
1558 deprecated_since: None,
1559 removed_in: None,
1560 identifier: ident(s),
1561 param_type: None,
1562 default_value: None,
1563 labeled: true,
1564 digest: None,
1565 }
1566 }
1567 fn additional_program_memory(items: &[(String, KclValue)]) -> Stack {
1568 let mut program_memory = Stack::new_for_tests();
1569 for (name, item) in items {
1570 program_memory
1571 .add(name.clone(), item.clone(), SourceRange::default())
1572 .unwrap();
1573 }
1574 program_memory
1575 }
1576 for (test_name, params, args, expected) in [
1578 ("empty", Vec::new(), Vec::new(), Ok(additional_program_memory(&[]))),
1579 (
1580 "all params required, and all given, should be OK",
1581 vec![req_param("x")],
1582 vec![("x", mem(1))],
1583 Ok(additional_program_memory(&[("x".to_owned(), mem(1))])),
1584 ),
1585 (
1586 "all params required, none given, should error",
1587 vec![req_param("x")],
1588 vec![],
1589 Err(KclError::new_argument(KclErrorDetails::new(
1590 "This function requires a parameter x, but you haven't passed it one.".to_owned(),
1591 vec![SourceRange::default()],
1592 ))),
1593 ),
1594 (
1595 "all params optional, none given, should be OK",
1596 vec![opt_param("x")],
1597 vec![],
1598 Ok(additional_program_memory(&[("x".to_owned(), KclValue::none())])),
1599 ),
1600 (
1601 "mixed params, too few given",
1602 vec![req_param("x"), opt_param("y")],
1603 vec![],
1604 Err(KclError::new_argument(KclErrorDetails::new(
1605 "This function requires a parameter x, but you haven't passed it one.".to_owned(),
1606 vec![SourceRange::default()],
1607 ))),
1608 ),
1609 (
1610 "mixed params, minimum given, should be OK",
1611 vec![req_param("x"), opt_param("y")],
1612 vec![("x", mem(1))],
1613 Ok(additional_program_memory(&[
1614 ("x".to_owned(), mem(1)),
1615 ("y".to_owned(), KclValue::none()),
1616 ])),
1617 ),
1618 (
1619 "mixed params, maximum given, should be OK",
1620 vec![req_param("x"), opt_param("y")],
1621 vec![("x", mem(1)), ("y", mem(2))],
1622 Ok(additional_program_memory(&[
1623 ("x".to_owned(), mem(1)),
1624 ("y".to_owned(), mem(2)),
1625 ])),
1626 ),
1627 ] {
1628 let func_expr = Node::no_src(FunctionExpression {
1630 name: None,
1631 params,
1632 body: Program::empty(),
1633 return_type: None,
1634 digest: None,
1635 });
1636 let func_src = FunctionSource::kcl(
1637 crate::parsing::ast::types::BoxNode::new(func_expr),
1638 EnvironmentRef::dummy(),
1639 crate::execution::kcl_value::KclFunctionSourceParams {
1640 std_props: None,
1641 experimental: false,
1642 include_in_feature_tree: false,
1643 },
1644 );
1645 let labeled = args
1646 .iter()
1647 .map(|(name, value)| {
1648 let arg = Arg::new(value.clone(), SourceRange::default());
1649 ((*name).to_owned(), arg)
1650 })
1651 .collect::<IndexMap<_, _>>();
1652 let exec_ctxt = ExecutorContext {
1653 engine: Arc::new(EngineManager::new_mock()),
1654 engine_batch: crate::engine::EngineBatchContext::default(),
1655 fs: crate::fs::new_file_system_handle(crate::fs::FileManager::new()),
1656 settings: Default::default(),
1657 context_type: ContextType::Mock,
1658 execution_callbacks: Default::default(),
1659 executor_kind: crate::execution::machine::ExecutorKind::resolve(),
1660 machine_call_depth_limit: crate::execution::machine::DEFAULT_MACHINE_CALL_DEPTH_LIMIT,
1661 configure_engine_render: true,
1662 };
1663 let mut exec_state = ExecState::new(&exec_ctxt);
1664 exec_state.mod_local.stack = Stack::new_for_tests();
1665
1666 let args = Args {
1667 fn_name: Some("test".to_owned()),
1668 labeled,
1669 unlabeled: Vec::new(),
1670 source_range: SourceRange::default(),
1671 node_path: None,
1672 ctx: exec_ctxt,
1673 pipe_value: None,
1674 _status: std::marker::PhantomData,
1675 };
1676
1677 let actual = assign_args_to_params_kw(&func_src, args, &mut exec_state).map(|_| exec_state.mod_local.stack);
1678 assert_eq!(
1679 actual, expected,
1680 "failed test '{test_name}':\ngot {actual:?}\nbut expected\n{expected:?}"
1681 );
1682 }
1683 }
1684
1685 #[tokio::test(flavor = "multi_thread")]
1686 async fn type_check_user_args() {
1687 let program = r#"fn makeMessage(prefix: string, suffix: string) {
1688 return prefix + suffix
1689}
1690
1691msg1 = makeMessage(prefix = "world", suffix = " hello")
1692msg2 = makeMessage(prefix = 1, suffix = 3)"#;
1693 let err = parse_execute(program).await.unwrap_err();
1694 assert_eq!(
1695 err.message(),
1696 "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`."
1697 )
1698 }
1699
1700 #[tokio::test(flavor = "multi_thread")]
1701 async fn never_function_cannot_return_a_value() {
1702 let program = r#"@settings(kclVersion = "3.0-preview")
1703fn bad(): never {
1704 return 42
1705}
1706
1707bad()
1708"#;
1709 let err = parse_execute(program).await.unwrap_err();
1710
1711 assert!(matches!(&err, KclError::Type { .. }));
1712 assert_eq!(
1713 err.message(),
1714 "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."
1715 );
1716 }
1717
1718 #[tokio::test(flavor = "multi_thread")]
1719 async fn never_function_cannot_fall_through() {
1720 let program = r#"@settings(kclVersion = "3.0-preview")
1721fn alsoBad(): never {
1722 x = 42
1723}
1724
1725alsoBad()
1726"#;
1727 let err = parse_execute(program).await.unwrap_err();
1728
1729 assert!(matches!(&err, KclError::Type { .. }));
1730 assert_eq!(
1731 err.message(),
1732 "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."
1733 );
1734 }
1735
1736 #[tokio::test(flavor = "multi_thread")]
1737 async fn never_union_function_cannot_return_a_value() {
1738 let program = r#"@settings(kclVersion = "3.0-preview")
1739fn bad(): never | never {
1740 return 42
1741}
1742
1743bad()
1744"#;
1745 let err = parse_execute(program).await.unwrap_err();
1746
1747 assert!(matches!(&err, KclError::Type { .. }));
1748 assert_eq!(
1749 err.message(),
1750 "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."
1751 );
1752 }
1753
1754 #[tokio::test(flavor = "multi_thread")]
1755 async fn never_union_function_cannot_fall_through() {
1756 let program = r#"@settings(kclVersion = "3.0-preview")
1757fn alsoBad(): never | never {
1758 x = 42
1759}
1760
1761alsoBad()
1762"#;
1763 let err = parse_execute(program).await.unwrap_err();
1764
1765 assert!(matches!(&err, KclError::Type { .. }));
1766 assert_eq!(
1767 err.message(),
1768 "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."
1769 );
1770 }
1771
1772 #[tokio::test(flavor = "multi_thread")]
1773 async fn never_function_contract_is_path_dependent() {
1774 let function = r#"@settings(kclVersion = "3.0-preview")
1775fn failOrReturn(@shouldFail: bool): never {
1776 return if shouldFail {
1777 fail("requested failure")
1778 } else {
1779 42
1780 }
1781}
1782"#;
1783
1784 let err = parse_execute(&format!("{function}\nfailOrReturn(true)\n"))
1785 .await
1786 .unwrap_err();
1787 assert!(matches!(&err, KclError::UserDefined { .. }));
1788 assert_eq!(err.message(), "requested failure");
1789
1790 let err = parse_execute(&format!("{function}\nfailOrReturn(false)\n"))
1791 .await
1792 .unwrap_err();
1793 assert!(matches!(&err, KclError::Type { .. }));
1794 assert_eq!(
1795 err.message(),
1796 "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."
1797 );
1798 }
1799
1800 #[tokio::test(flavor = "multi_thread")]
1801 async fn never_type_alias_contract_is_path_dependent() {
1802 let function = r#"@settings(kclVersion = "3.0-preview")
1803type impossible = never
1804fn failOrReturn(@shouldFail: bool): impossible {
1805 return if shouldFail {
1806 fail("requested failure")
1807 } else {
1808 42
1809 }
1810}
1811"#;
1812
1813 let err = parse_execute(&format!("{function}\nfailOrReturn(true)\n"))
1814 .await
1815 .unwrap_err();
1816 assert!(matches!(&err, KclError::UserDefined { .. }));
1817 assert_eq!(err.message(), "requested failure");
1818
1819 let err = parse_execute(&format!("{function}\nfailOrReturn(false)\n"))
1820 .await
1821 .unwrap_err();
1822 assert!(matches!(&err, KclError::Type { .. }));
1823 assert_eq!(
1824 err.message(),
1825 "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."
1826 );
1827 }
1828
1829 #[tokio::test(flavor = "multi_thread")]
1830 async fn union_with_never_can_return_a_value_or_fail() {
1831 let function = r#"@settings(kclVersion = "3.0-preview")
1832fn stringOrFail(@shouldFail: bool): string | never {
1833 return if shouldFail {
1834 fail("requested failure")
1835 } else {
1836 "ok"
1837 }
1838}
1839"#;
1840
1841 let result = parse_execute(&format!("{function}\nresult = stringOrFail(false)\n"))
1842 .await
1843 .unwrap();
1844 let KclValue::String { value, .. } = get_var(&result, "result") else {
1845 panic!("expected `result` to be a string")
1846 };
1847 assert_eq!(value, "ok");
1848
1849 let err = parse_execute(&format!("{function}\nstringOrFail(true)\n"))
1850 .await
1851 .unwrap_err();
1852 assert!(matches!(&err, KclError::UserDefined { .. }));
1853 assert_eq!(err.message(), "requested failure");
1854 }
1855
1856 #[tokio::test(flavor = "multi_thread")]
1857 async fn fail_reports_user_defined_message_and_callsite_once() {
1858 let program = r#"@settings(kclVersion = "3.0-preview")
1859fail("custom failure")
1860"#;
1861
1862 let err = parse_execute(program).await.unwrap_err();
1863
1864 assert!(matches!(&err, KclError::UserDefined { .. }));
1865 assert_eq!(err.message(), "custom failure");
1866 assert_eq!(err.get_message(), "user-defined: custom failure");
1867 assert_eq!(serde_json::to_value(&err).unwrap()["kind"], "user_defined");
1868 assert_eq!(source_texts(program, &err), [r#"fail("custom failure")"#]);
1869 assert_eq!(err.backtrace().len(), 1);
1870 }
1871
1872 #[tokio::test(flavor = "multi_thread")]
1873 async fn fail_is_unavailable_before_v3_even_with_experimental_opt_in() {
1874 for version in ["1.0", "2.0"] {
1875 for opt_in in ["", ", experimentalFeatures = allow"] {
1876 let program = format!("@settings(kclVersion = {version}{opt_in})\nfail(\"custom failure\")\n");
1877 let err = parse_execute(&program).await.unwrap_err();
1878 assert!(
1879 err.message()
1880 .contains("it was added in KCL 3.0, but this program uses KCL"),
1881 "{program}: {err:#?}"
1882 );
1883 }
1884 }
1885 }
1886
1887 #[tokio::test(flavor = "multi_thread")]
1888 async fn fail_unwinds_through_nested_never_functions_once() {
1889 let program = r#"@settings(kclVersion = "3.0-preview")
1890fn inner(): never {
1891 fail("nested failure")
1892}
1893
1894fn outer(): never {
1895 inner()
1896}
1897
1898outer()
1899"#;
1900
1901 let err = parse_execute(program).await.unwrap_err();
1902
1903 assert!(matches!(&err, KclError::UserDefined { .. }));
1904 assert_eq!(err.message(), "nested failure");
1905 assert_eq!(
1906 source_texts(program, &err),
1907 [r#"fail("nested failure")"#, "inner()", "outer()"]
1908 );
1909 assert_eq!(
1910 err.backtrace()
1911 .iter()
1912 .map(|item| item.fn_name.as_deref())
1913 .collect::<Vec<_>>(),
1914 [Some("inner"), Some("outer"), None]
1915 );
1916 }
1917
1918 #[tokio::test(flavor = "multi_thread")]
1919 async fn fail_is_valid_in_a_function_with_a_value_return_type() {
1920 let function = r#"@settings(kclVersion = "3.0-preview")
1921fn valueOrFail(@shouldFail: bool): number {
1922 return if shouldFail {
1923 fail("no value")
1924 } else {
1925 42
1926 }
1927}
1928"#;
1929
1930 parse_execute(&format!("{function}\nresult = valueOrFail(false)\n"))
1931 .await
1932 .unwrap();
1933
1934 let err = parse_execute(&format!("{function}\nvalueOrFail(true)\n"))
1935 .await
1936 .unwrap_err();
1937 assert!(matches!(&err, KclError::UserDefined { .. }));
1938 assert_eq!(err.message(), "no value");
1939 }
1940
1941 #[tokio::test(flavor = "multi_thread")]
1942 async fn never_function_with_fail_or_fallthrough_is_path_dependent() {
1943 let function = r#"@settings(kclVersion = "3.0-preview")
1944fn failOrFallThrough(@shouldFail: bool): never {
1945 result = if shouldFail {
1946 fail("requested failure")
1947 } else {
1948 42
1949 }
1950}
1951"#;
1952
1953 let err = parse_execute(&format!("{function}\nfailOrFallThrough(true)\n"))
1954 .await
1955 .unwrap_err();
1956 assert!(matches!(&err, KclError::UserDefined { .. }));
1957 assert_eq!(err.message(), "requested failure");
1958
1959 let err = parse_execute(&format!("{function}\nfailOrFallThrough(false)\n"))
1960 .await
1961 .unwrap_err();
1962 assert!(matches!(&err, KclError::Type { .. }));
1963 assert_eq!(
1964 err.message(),
1965 "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."
1966 );
1967 }
1968
1969 #[tokio::test(flavor = "multi_thread")]
1970 async fn fail_argument_evaluation_errors_take_precedence() {
1971 let program = r#"@settings(kclVersion = "3.0-preview")
1972fn stop(): never {
1973 fail(missingMessage)
1974}
1975
1976stop()
1977"#;
1978
1979 let err = parse_execute(program).await.unwrap_err();
1980
1981 assert!(matches!(&err, KclError::UndefinedValue { .. }));
1982 assert_eq!(err.message(), "`missingMessage` is not defined");
1983 assert_eq!(source_texts(program, &err), ["missingMessage", "stop()"]);
1984 }
1985
1986 #[tokio::test(flavor = "multi_thread")]
1987 async fn fail_rejects_invalid_message_arguments_before_invocation() {
1988 for program in [
1989 "@settings(kclVersion = \"3.0-preview\")\nfail()\n",
1990 "@settings(kclVersion = \"3.0-preview\")\nfail(42)\n",
1991 ] {
1992 let err = parse_execute(program).await.unwrap_err();
1993 assert!(matches!(&err, KclError::Argument { .. }), "{err:?}");
1994 }
1995 }
1996
1997 #[tokio::test(flavor = "multi_thread")]
1998 async fn map_closure_error_mentions_fn_name() {
1999 let program = r#"
2000arr = ["hello"]
2001map(array = arr, f = fn(@item: number) { return item })
2002"#;
2003 let err = parse_execute(program).await.unwrap_err();
2004 assert!(
2005 err.message().contains("map closure"),
2006 "expected map closure errors to include the closure name, got: {}",
2007 err.message()
2008 );
2009 }
2010
2011 #[tokio::test(flavor = "multi_thread")]
2012 async fn array_input_arg() {
2013 let ast = r#"fn f(@input: [mm]) { return 1 }
2014f([1, 2, 3])
2015f(1, 2, 3)
2016"#;
2017 parse_execute(ast).await.unwrap();
2018 }
2019
2020 #[tokio::test(flavor = "multi_thread")]
2021 async fn extrude_tagged_body_gets_face_tags_and_keeps_legacy_bindings() {
2022 let program = r#"@settings(kclVersion = 2.0)
2023profile = sketch(on = XY) {
2024 line1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
2025 line2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
2026 line3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
2027 line4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
2028 coincident([line1.end, line2.start])
2029 coincident([line2.end, line3.start])
2030 coincident([line3.end, line4.start])
2031 coincident([line4.end, line1.start])
2032}
2033region1 = region(point = [5mm, 5mm], sketch = profile)
2034
2035body = extrude(region1, length = 5mm, tagStart = $bottom, tagEnd = $top)
2036bottomFromBody = body.faces.bottom
2037topFromBody = body.faces.top
2038lineFromSketch = region1.tags.line1
2039legacyBottom = bottom
2040legacyTop = top
2041"#;
2042
2043 let result = parse_execute(program).await.unwrap();
2044 assert_body_face_tags(&result, &["bottom", "top"], &["line1"]);
2045 assert_vars_are_tags(
2046 &result,
2047 &[
2048 "bottom",
2049 "top",
2050 "bottomFromBody",
2051 "topFromBody",
2052 "lineFromSketch",
2053 "legacyBottom",
2054 "legacyTop",
2055 ],
2056 );
2057 assert_vars_are_missing(&result, &["line1"]);
2058 }
2059
2060 #[tokio::test(flavor = "multi_thread")]
2061 async fn extrude_without_tag_arguments_does_not_get_face_tags() {
2062 let program = r#"@settings(kclVersion = 2.0)
2063profile = sketch(on = XY) {
2064 line1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
2065 line2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
2066 line3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
2067 line4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
2068 coincident([line1.end, line2.start])
2069 coincident([line2.end, line3.start])
2070 coincident([line3.end, line4.start])
2071 coincident([line4.end, line1.start])
2072}
2073region1 = region(point = [5mm, 5mm], sketch = profile)
2074
2075body = extrude(region1, length = 5mm)
2076"#;
2077
2078 let result = parse_execute(program).await.unwrap();
2079 let body = get_var(&result, "body");
2080 let KclValue::Solid { value: body } = body else {
2081 panic!("expected `body` to be a solid");
2082 };
2083
2084 assert!(
2085 body.faces.is_empty(),
2086 "body faces should only be populated for tagged calls"
2087 );
2088 }
2089
2090 #[tokio::test(flavor = "multi_thread")]
2091 async fn sketch_segment_extrude_exposes_its_generated_face() {
2092 let program = r#"@settings(defaultLengthUnit = mm)
2093sketch001 = sketch(on = XY) {
2094 line1 = line(start = [0, 0], end = [20, 0])
2095 line2 = line(start = [20, 0], end = [20, 12])
2096}
2097surface001 = extrude(
2098 sketch001.line1,
2099 length = 10,
2100 bodyType = SURFACE,
2101 method = NEW,
2102)
2103generatedFace = surface001.faces.line1
2104surface002 = extrude(
2105 {
2106 sideFaces = [surface001.faces.line1],
2107 index = 2
2108 },
2109 length = 5,
2110 bodyType = SURFACE,
2111 method = NEW,
2112)
2113"#;
2114
2115 let result = parse_execute(program).await.unwrap();
2116 let surface = get_var(&result, "surface001");
2117 let KclValue::Solid { value: surface } = surface else {
2118 panic!("expected `surface001` to be a solid");
2119 };
2120 assert!(surface.faces.contains_key("line1"));
2121 assert_vars_are_tags(&result, &["generatedFace"]);
2122 }
2123
2124 #[tokio::test(flavor = "multi_thread")]
2125 async fn revolve_tagged_body_gets_face_tags() {
2126 let program = r#"@settings(kclVersion = 2.0)
2127profile = sketch(on = XY) {
2128 side = line(start = [var 5mm, var 0mm], end = [var 5mm, var 10mm])
2129 line2 = line(start = [var 5mm, var 10mm], end = [var 6mm, var 10mm])
2130 line3 = line(start = [var 6mm, var 10mm], end = [var 6mm, var 0mm])
2131 line4 = line(start = [var 6mm, var 0mm], end = [var 5mm, var 0mm])
2132 coincident([side.end, line2.start])
2133 coincident([line2.end, line3.start])
2134 coincident([line3.end, line4.start])
2135 coincident([line4.end, side.start])
2136}
2137region1 = region(point = [5.5mm, 5mm], sketch = profile)
2138
2139body = revolve(region1, axis = Y, angle = 90deg, tagStart = $startCap, tagEnd = $endCap)
2140startFromBody = body.faces.startCap
2141endFromBody = body.faces.endCap
2142sideFromSketch = region1.tags.side
2143legacyStart = startCap
2144legacyEnd = endCap
2145"#;
2146
2147 let result = parse_execute(program).await.unwrap();
2148 assert_body_face_tags(&result, &["startCap", "endCap"], &["side"]);
2149 assert_vars_are_tags(
2150 &result,
2151 &[
2152 "startCap",
2153 "endCap",
2154 "startFromBody",
2155 "endFromBody",
2156 "sideFromSketch",
2157 "legacyStart",
2158 "legacyEnd",
2159 ],
2160 );
2161 assert_vars_are_missing(&result, &["side"]);
2162 }
2163
2164 #[tokio::test(flavor = "multi_thread")]
2165 async fn sweep_tagged_body_gets_face_tags() {
2166 let program = r#"@settings(kclVersion = 2.0)
2167profile = sketch(on = XZ) {
2168 edge1 = line(start = [var 0mm, var 0mm], end = [var 2mm, var 0mm])
2169 edge2 = line(start = [var 2mm, var 0mm], end = [var 2mm, var 2mm])
2170 edge3 = line(start = [var 2mm, var 2mm], end = [var 0mm, var 2mm])
2171 edge4 = line(start = [var 0mm, var 2mm], end = [var 0mm, var 0mm])
2172 coincident([edge1.end, edge2.start])
2173 coincident([edge2.end, edge3.start])
2174 coincident([edge3.end, edge4.start])
2175 coincident([edge4.end, edge1.start])
2176}
2177profileRegion = region(point = [1mm, 1mm], sketch = profile)
2178
2179pathSketch = sketch(on = offsetPlane(YZ, offset = -2mm)) {
2180 pathLine = line(start = [var 0mm, var 0mm], end = [var 0mm, var 5mm])
2181}
2182
2183body = sweep(profileRegion, path = pathSketch.pathLine, tagStart = $startCap, tagEnd = $endCap)
2184startFromBody = body.faces.startCap
2185endFromBody = body.faces.endCap
2186edgeFromSketch = profileRegion.tags.edge1
2187pathFromSketch = pathSketch.pathLine
2188legacyStart = startCap
2189legacyEnd = endCap
2190"#;
2191
2192 let result = parse_execute(program).await.unwrap();
2193 assert_body_face_tags(&result, &["startCap", "endCap"], &["edge1", "pathLine"]);
2194 assert_vars_are_tags(
2195 &result,
2196 &[
2197 "startCap",
2198 "endCap",
2199 "startFromBody",
2200 "endFromBody",
2201 "edgeFromSketch",
2202 "legacyStart",
2203 "legacyEnd",
2204 ],
2205 );
2206 assert_vars_are_missing(&result, &["edge1", "pathLine"]);
2207 }
2208
2209 #[tokio::test(flavor = "multi_thread")]
2210 async fn loft_tagged_body_gets_face_tags() {
2211 let program = r#"@settings(kclVersion = 2.0)
2212lowerProfile = sketch(on = XY) {
2213 edge1 = line(start = [var 0mm, var 0mm], end = [var 6mm, var 0mm])
2214 edge2 = line(start = [var 6mm, var 0mm], end = [var 6mm, var 4mm])
2215 edge3 = line(start = [var 6mm, var 4mm], end = [var 0mm, var 4mm])
2216 edge4 = line(start = [var 0mm, var 4mm], end = [var 0mm, var 0mm])
2217 coincident([edge1.end, edge2.start])
2218 coincident([edge2.end, edge3.start])
2219 coincident([edge3.end, edge4.start])
2220 coincident([edge4.end, edge1.start])
2221}
2222lowerRegion = region(point = [3mm, 2mm], sketch = lowerProfile)
2223
2224upperProfile = sketch(on = offsetPlane(XY, offset = 8mm)) {
2225 edge5 = line(start = [var 1mm, var 1mm], end = [var 5mm, var 1mm])
2226 edge6 = line(start = [var 5mm, var 1mm], end = [var 4mm, var 3mm])
2227 edge7 = line(start = [var 4mm, var 3mm], end = [var 2mm, var 3mm])
2228 edge8 = line(start = [var 2mm, var 3mm], end = [var 1mm, var 1mm])
2229 coincident([edge5.end, edge6.start])
2230 coincident([edge6.end, edge7.start])
2231 coincident([edge7.end, edge8.start])
2232 coincident([edge8.end, edge5.start])
2233}
2234upperRegion = region(point = [3mm, 2mm], sketch = upperProfile)
2235
2236body = loft([lowerRegion, upperRegion], tagStart = $startCap, tagEnd = $endCap)
2237startFromBody = body.faces.startCap
2238endFromBody = body.faces.endCap
2239edgeFromSketch = lowerRegion.tags.edge1
2240legacyStart = startCap
2241legacyEnd = endCap
2242"#;
2243
2244 let result = parse_execute(program).await.unwrap();
2245 assert_body_face_tags(&result, &["startCap", "endCap"], &["edge1"]);
2246 assert_vars_are_tags(
2247 &result,
2248 &[
2249 "startCap",
2250 "endCap",
2251 "startFromBody",
2252 "endFromBody",
2253 "edgeFromSketch",
2254 "legacyStart",
2255 "legacyEnd",
2256 ],
2257 );
2258 assert_vars_are_missing(&result, &["edge1"]);
2259 }
2260
2261 #[tokio::test(flavor = "multi_thread")]
2262 async fn chamfer_tagged_body_gets_face_tags() {
2263 let program = r#"@settings(kclVersion = 2.0)
2264profile = sketch(on = XY) {
2265 edge1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
2266 edge2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
2267 edge3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
2268 edge4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
2269 coincident([edge1.end, edge2.start])
2270 coincident([edge2.end, edge3.start])
2271 coincident([edge3.end, edge4.start])
2272 coincident([edge4.end, edge1.start])
2273}
2274profileRegion = region(point = [5mm, 5mm], sketch = profile)
2275
2276base = extrude(profileRegion, length = 5mm, tagEnd = $top)
2277body = chamfer(base, tags = getCommonEdge(faces = [profileRegion.tags.edge1, top]), length = 1mm, tag = $chamferFace)
2278chamferFromBody = body.faces.chamferFace
2279topFromBody = body.faces.top
2280edgeFromSketch = profileRegion.tags.edge1
2281legacyChamfer = chamferFace
2282legacyTop = top
2283"#;
2284
2285 let result = parse_execute(program).await.unwrap();
2286 assert_body_face_tags(&result, &["top", "chamferFace"], &["edge1"]);
2287 assert_vars_are_tags(
2288 &result,
2289 &[
2290 "top",
2291 "chamferFace",
2292 "chamferFromBody",
2293 "topFromBody",
2294 "edgeFromSketch",
2295 "legacyChamfer",
2296 "legacyTop",
2297 ],
2298 );
2299 assert_vars_are_missing(&result, &["edge1"]);
2300 }
2301
2302 #[tokio::test(flavor = "multi_thread")]
2303 async fn fillet_tagged_body_gets_face_tags() {
2304 let program = r#"@settings(kclVersion = 2.0)
2305profile = sketch(on = XY) {
2306 edge1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
2307 edge2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
2308 edge3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
2309 edge4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
2310 coincident([edge1.end, edge2.start])
2311 coincident([edge2.end, edge3.start])
2312 coincident([edge3.end, edge4.start])
2313 coincident([edge4.end, edge1.start])
2314}
2315profileRegion = region(point = [5mm, 5mm], sketch = profile)
2316
2317base = extrude(profileRegion, length = 5mm, tagEnd = $top)
2318body = fillet(base, tags = getCommonEdge(faces = [profileRegion.tags.edge1, top]), radius = 1mm, tag = $filletFace)
2319filletFromBody = body.faces.filletFace
2320topFromBody = body.faces.top
2321edgeFromSketch = profileRegion.tags.edge1
2322legacyFillet = filletFace
2323legacyTop = top
2324"#;
2325
2326 let result = parse_execute(program).await.unwrap();
2327 assert_body_face_tags(&result, &["top", "filletFace"], &["edge1"]);
2328 assert_vars_are_tags(
2329 &result,
2330 &[
2331 "top",
2332 "filletFace",
2333 "filletFromBody",
2334 "topFromBody",
2335 "edgeFromSketch",
2336 "legacyFillet",
2337 "legacyTop",
2338 ],
2339 );
2340 assert_vars_are_missing(&result, &["edge1"]);
2341 }
2342
2343 #[tokio::test(flavor = "multi_thread")]
2344 async fn accessing_body_tag_through_body_sketch_tags_warns() {
2345 let program = r#"@settings(kclVersion = 2.0)
2346profile = startSketchOn(XY)
2347 |> startProfile(at = [0, 0])
2348 |> line(end = [10, 0], tag = $line1)
2349 |> line(end = [0, 10])
2350 |> line(end = [-10, 0])
2351 |> close()
2352
2353body = extrude(profile, length = 5, tagEnd = $top)
2354topFromSketch = body.sketch.tags.top
2355topFromBody = body.faces.top
2356"#;
2357
2358 let result = parse_execute(program).await.unwrap();
2359 assert!(matches!(get_var(&result, "topFromSketch"), KclValue::TagIdentifier(_)));
2360 assert!(matches!(get_var(&result, "topFromBody"), KclValue::TagIdentifier(_)));
2361
2362 let warnings = deprecated_solid_tag_access_warnings(&result);
2363 assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
2364 assert_eq!(warnings[0].severity, Severity::Warning);
2365 assert!(warnings[0].message.contains("`top`"), "found {}", warnings[0].message);
2366 assert!(
2367 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`."),
2368 "found {}",
2369 warnings[0].message
2370 );
2371 }
2372
2373 #[tokio::test(flavor = "multi_thread")]
2374 async fn accessing_sketch_path_tag_through_body_sketch_tags_does_not_warn() {
2375 let program = r#"@settings(kclVersion = 2.0)
2376profile = startSketchOn(XY)
2377 |> startProfile(at = [0, 0])
2378 |> line(end = [10, 0], tag = $line1)
2379 |> line(end = [0, 10])
2380 |> line(end = [-10, 0])
2381 |> close()
2382
2383body = extrude(profile, length = 5, tagEnd = $top)
2384lineFromSketch = body.sketch.tags.line1
2385"#;
2386
2387 let result = parse_execute(program).await.unwrap();
2388 assert!(matches!(get_var(&result, "lineFromSketch"), KclValue::TagIdentifier(_)));
2389 let warnings = deprecated_solid_tag_access_warnings(&result);
2390 assert!(
2391 warnings.is_empty(),
2392 "sketch path tags should not get body-tag deprecation warnings: {warnings:#?}"
2393 );
2394 }
2395
2396 #[tokio::test(flavor = "multi_thread")]
2397 async fn accessing_body_tag_through_sketch_block_region_tags_warns() {
2398 let program = r#"@settings(kclVersion = 2.0)
2399profile = sketch(on = XY) {
2400 line1 = line(start = [0, 0], end = [10, 0])
2401 line2 = line(start = [10, 0], end = [10, 10])
2402 line3 = line(start = [10, 10], end = [0, 10])
2403 line4 = line(start = [0, 10], end = [0, 0])
2404}
2405
2406profileRegion = region(point = [1, 1], sketch = profile)
2407body = extrude(profileRegion, length = 5, tagEnd = $top)
2408topFromRegion = profileRegion.tags.top
2409"#;
2410
2411 let result = parse_execute(program).await.unwrap();
2412 assert!(matches!(get_var(&result, "topFromRegion"), KclValue::TagIdentifier(_)));
2413
2414 let warnings = deprecated_solid_tag_access_warnings(&result);
2415 assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
2416 assert_eq!(warnings[0].severity, Severity::Warning);
2417 assert!(warnings[0].message.contains("`top`"), "found {}", warnings[0].message);
2418 }
2419
2420 fn deprecation_warnings(result: &ExecTestResults) -> Vec<&CompilationIssue> {
2421 result
2422 .exec_state
2423 .issues()
2424 .iter()
2425 .filter(|issue| issue.message.contains("is deprecated"))
2426 .collect()
2427 }
2428
2429 #[tokio::test(flavor = "multi_thread")]
2430 async fn passing_param_deprecated_for_all_versions_warns() {
2431 let program = r#"@settings(kclVersion = 2.0)
2434fn f(
2435 @a: number,
2436 @(deprecated = true)
2437 oldArg?: number,
2438) {
2439 return a
2440}
2441x = f(1, oldArg = 2)
2442"#;
2443
2444 let result = parse_execute(program).await.unwrap();
2445 let warnings = deprecation_warnings(&result);
2446 assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
2447 assert_eq!(warnings[0].severity, Severity::Warning);
2448 assert_eq!(warnings[0].tag, crate::errors::Tag::Deprecated);
2449 assert!(
2450 warnings[0].message.contains("`f(oldArg)` is deprecated"),
2451 "found {}",
2452 warnings[0].message
2453 );
2454 }
2455
2456 #[tokio::test(flavor = "multi_thread")]
2457 async fn not_passing_deprecated_param_does_not_warn() {
2458 let program = r#"fn f(
2459 @a: number,
2460 @(deprecated = true)
2461 oldArg?: number,
2462) {
2463 return a
2464}
2465x = f(1)
2466"#;
2467
2468 let result = parse_execute(program).await.unwrap();
2469 let warnings = deprecation_warnings(&result);
2470 assert!(
2471 warnings.is_empty(),
2472 "unused deprecated parameter should not warn: {warnings:#?}"
2473 );
2474 }
2475
2476 fn unexpected_arg_errors(result: &ExecTestResults) -> Vec<&CompilationIssue> {
2477 result
2478 .exec_state
2479 .issues()
2480 .iter()
2481 .filter(|issue| issue.message.contains("is not an argument of"))
2482 .collect()
2483 }
2484
2485 #[tokio::test(flavor = "multi_thread")]
2486 async fn passing_removed_param_on_removed_version_errors_like_unknown_arg() {
2487 let program = r#"@settings(kclVersion = "3.0-preview")
2490fn f(
2491 @a: number,
2492 @(deprecated_since = "2.0", removed_in = "3.0")
2493 oldArg?: number,
2494) {
2495 return a
2496}
2497x = f(1, oldArg = 2)
2498"#;
2499
2500 let result = parse_execute(program).await.unwrap();
2501 let errors = unexpected_arg_errors(&result);
2502 assert_eq!(
2503 errors.len(),
2504 1,
2505 "expected one unknown-argument error, got {:#?}",
2506 result.issues()
2507 );
2508 assert_eq!(errors[0].severity, Severity::Error);
2509 assert_eq!(
2512 errors[0].message,
2513 "`oldArg` is not an argument of `f`; it was removed in KCL 3.0, but this program uses KCL 3.0-preview"
2514 );
2515 assert!(
2517 deprecation_warnings(&result).is_empty(),
2518 "removed parameter should not also warn: {:#?}",
2519 result.issues()
2520 );
2521 assert!(matches!(get_var(&result, "x"), KclValue::Number { value, .. } if value == 1.0));
2523 }
2524
2525 #[tokio::test(flavor = "multi_thread")]
2526 async fn passing_removed_param_before_removed_version_still_works() {
2527 let program = r#"@settings(kclVersion = 2.0)
2528fn f(
2529 @a: number,
2530 @(deprecated_since = "2.0", removed_in = "3.0")
2531 oldArg?: number,
2532) {
2533 return oldArg
2534}
2535x = f(1, oldArg = 2)
2536"#;
2537
2538 let result = parse_execute(program).await.unwrap();
2539 assert!(
2540 unexpected_arg_errors(&result).is_empty(),
2541 "parameter is not removed until 3.0: {:#?}",
2542 result.issues()
2543 );
2544 let warnings = deprecation_warnings(&result);
2545 assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
2546 assert!(
2547 warnings[0].message.contains("`f(oldArg)` is deprecated as of KCL 2.0"),
2548 "found {}",
2549 warnings[0].message
2550 );
2551 assert!(matches!(get_var(&result, "x"), KclValue::Number { value, .. } if value == 2.0));
2552 }
2553
2554 #[tokio::test(flavor = "multi_thread")]
2555 async fn removed_optional_param_binds_its_default() {
2556 let program = r#"@settings(kclVersion = "3.0-preview")
2557fn f(
2558 @(removed_in = "3.0")
2559 oldArg?: number = 7,
2560) {
2561 return oldArg
2562}
2563x = f()
2564"#;
2565
2566 let result = parse_execute(program).await.unwrap();
2567 assert!(result.issues().is_empty(), "unexpected issues: {:#?}", result.issues());
2568 assert!(matches!(get_var(&result, "x"), KclValue::Number { value, .. } if value == 7.0));
2569 }
2570
2571 #[tokio::test(flavor = "multi_thread")]
2572 async fn removed_param_is_not_matched_by_label_shorthand() {
2573 let program = r#"@settings(kclVersion = "3.0-preview")
2578fn f(
2579 @(removed_in = "3.0")
2580 oldArg?: number,
2581) {
2582 return 1
2583}
2584oldArg = 2
2585x = f(oldArg)
2586"#;
2587
2588 let err = parse_execute(program).await.unwrap_err();
2589 assert_eq!(err.message(), "This argument needs a label, but it doesn't have one");
2590 }
2591
2592 #[tokio::test(flavor = "multi_thread")]
2593 async fn passing_not_yet_added_param_errors_like_unknown_arg() {
2594 let program = r#"@settings(kclVersion = 2.0)
2595fn f(
2596 @a: number,
2597 @(added_in = "3.0")
2598 newArg?: number,
2599) {
2600 return a
2601}
2602x = f(1, newArg = 2)
2603"#;
2604
2605 let result = parse_execute(program).await.unwrap();
2606 let errors = unexpected_arg_errors(&result);
2607 assert_eq!(
2608 errors.len(),
2609 1,
2610 "expected one unknown-argument error, got {:#?}",
2611 result.issues()
2612 );
2613 assert_eq!(errors[0].severity, Severity::Error);
2614 assert_eq!(
2615 errors[0].message,
2616 "`newArg` is not an argument of `f`; it was added in KCL 3.0, but this program uses KCL 2.0"
2617 );
2618 assert!(matches!(get_var(&result, "x"), KclValue::Number { value, .. } if value == 1.0));
2620 }
2621
2622 #[tokio::test(flavor = "multi_thread")]
2623 async fn not_yet_added_param_error_reports_default_kcl_version() {
2624 let program = r#"fn f(
2627 @(added_in = "2.0")
2628 newArg?: number,
2629) {
2630 return 1
2631}
2632x = f(newArg = 2)
2633"#;
2634
2635 let result = parse_execute(program).await.unwrap();
2636 let errors = unexpected_arg_errors(&result);
2637 assert_eq!(errors.len(), 1, "got {:#?}", result.issues());
2638 assert_eq!(
2639 errors[0].message,
2640 "`newArg` is not an argument of `f`; it was added in KCL 2.0, but this program uses KCL 1.0"
2641 );
2642 }
2643
2644 #[tokio::test(flavor = "multi_thread")]
2645 async fn passing_added_param_on_or_after_added_version_works() {
2646 for (kcl_version, added_in) in [("2.0", "1.0"), ("2.0", "2.0"), ("\"3.0-preview\"", "3.0")] {
2649 let program = format!(
2650 r#"@settings(kclVersion = {kcl_version})
2651fn f(
2652 @(added_in = "{added_in}")
2653 newArg?: number,
2654) {{
2655 return newArg
2656}}
2657x = f(newArg = 2)
2658"#
2659 );
2660
2661 let result = parse_execute(&program).await.unwrap();
2662 assert!(
2663 result.issues().is_empty(),
2664 "kclVersion {kcl_version}, added_in {added_in}: {:#?}",
2665 result.issues()
2666 );
2667 assert!(
2668 matches!(get_var(&result, "x"), KclValue::Number { value, .. } if value == 2.0),
2669 "kclVersion {kcl_version}, added_in {added_in}"
2670 );
2671 }
2672 }
2673
2674 #[tokio::test(flavor = "multi_thread")]
2675 async fn not_yet_added_optional_param_binds_its_default() {
2676 let program = r#"@settings(kclVersion = 2.0)
2677fn f(
2678 @(added_in = "3.0")
2679 newArg?: number = 7,
2680) {
2681 return newArg
2682}
2683x = f()
2684"#;
2685
2686 let result = parse_execute(program).await.unwrap();
2687 assert!(result.issues().is_empty(), "unexpected issues: {:#?}", result.issues());
2688 assert!(matches!(get_var(&result, "x"), KclValue::Number { value, .. } if value == 7.0));
2689 }
2690
2691 #[tokio::test(flavor = "multi_thread")]
2692 async fn not_yet_added_param_is_not_matched_by_label_shorthand() {
2693 let program = r#"@settings(kclVersion = 2.0)
2698fn f(
2699 @(added_in = "3.0")
2700 newArg?: number,
2701) {
2702 return 1
2703}
2704newArg = 2
2705x = f(newArg)
2706"#;
2707
2708 let err = parse_execute(program).await.unwrap_err();
2709 assert_eq!(err.message(), "This argument needs a label, but it doesn't have one");
2710 }
2711
2712 #[tokio::test(flavor = "multi_thread")]
2713 async fn param_lifecycle_added_then_deprecated_then_removed() {
2714 let body = r#"fn f(
2715 @(added_in = "2.0", deprecated_since = "2.0", removed_in = "3.0")
2716 arg?: number,
2717) {
2718 return arg
2719}
2720x = f(arg = 2)
2721"#;
2722 for (kcl_version, expected_error) in [
2723 (
2724 "1.0",
2725 Some("`arg` is not an argument of `f`; it was added in KCL 2.0, but this program uses KCL 1.0"),
2726 ),
2727 ("2.0", None),
2728 (
2729 "\"3.0-preview\"",
2730 Some(
2731 "`arg` is not an argument of `f`; it was removed in KCL 3.0, but this program uses KCL 3.0-preview",
2732 ),
2733 ),
2734 ] {
2735 let program = format!("@settings(kclVersion = {kcl_version})\n{body}");
2736 let result = parse_execute(&program).await.unwrap();
2737 let errors = unexpected_arg_errors(&result);
2738 match expected_error {
2739 Some(message) => {
2740 assert_eq!(errors.len(), 1, "kclVersion {kcl_version}: {:#?}", result.issues());
2741 assert_eq!(errors[0].message, message, "kclVersion {kcl_version}");
2742 assert!(
2743 deprecation_warnings(&result).is_empty(),
2744 "kclVersion {kcl_version}: an unavailable parameter should not also warn: {:#?}",
2745 result.issues()
2746 );
2747 }
2748 None => {
2749 assert!(errors.is_empty(), "kclVersion {kcl_version}: {:#?}", result.issues());
2750 assert_eq!(
2752 deprecation_warnings(&result).len(),
2753 1,
2754 "kclVersion {kcl_version}: {:#?}",
2755 result.issues()
2756 );
2757 assert!(
2758 matches!(get_var(&result, "x"), KclValue::Number { value, .. } if value == 2.0),
2759 "kclVersion {kcl_version}"
2760 );
2761 }
2762 }
2763 }
2764 }
2765
2766 #[tokio::test(flavor = "multi_thread")]
2767 async fn stdlib_legacy_method_is_removed_in_kcl_3() {
2768 let solids = r#"left = startSketchOn(XY)
2769 |> circle(center = [0, 0], radius = 2)
2770 |> extrude(length = 1)
2771right = startSketchOn(XY)
2772 |> circle(center = [1, 0], radius = 2)
2773 |> extrude(length = 1)
2774both = union([left, right], legacyMethod = true)
2775"#;
2776
2777 let program = format!("@settings(kclVersion = \"3.0-preview\")\n{solids}");
2778 let result = parse_execute(&program).await.unwrap();
2779 let errors = unexpected_arg_errors(&result);
2780 assert_eq!(errors.len(), 1, "got {:#?}", result.issues());
2781 assert_eq!(
2782 errors[0].message,
2783 "`legacyMethod` is not an argument of `union`; it was removed in KCL 3.0, but this program uses KCL 3.0-preview"
2784 );
2785
2786 let program = format!("@settings(kclVersion = 2.0)\n{solids}");
2788 let result = parse_execute(&program).await.unwrap();
2789 assert!(unexpected_arg_errors(&result).is_empty(), "got {:#?}", result.issues());
2790 assert!(
2791 deprecation_warnings(&result)
2792 .iter()
2793 .any(|w| w.message.contains("`union(legacyMethod)` is deprecated as of KCL 2.0")),
2794 "got {:#?}",
2795 result.issues()
2796 );
2797 }
2798
2799 #[tokio::test(flavor = "multi_thread")]
2800 async fn deprecated_calls_inside_kcl_stdlib_do_not_warn() {
2801 let program = include_str!("../../tests/cube_with_hole/input.kcl");
2802
2803 let result = parse_execute(program).await.unwrap();
2804 let warnings = deprecation_warnings(&result);
2805 assert!(
2806 warnings.is_empty(),
2807 "KCL stdlib internals should not emit deprecation warnings: {warnings:#?}"
2808 );
2809 }
2810
2811 #[tokio::test(flavor = "multi_thread")]
2812 async fn deprecated_stdlib_call_from_user_code_still_warns() {
2813 let program = r#"@settings(kclVersion = 2.0)
2814plane = startSketchOn(XY)
2815"#;
2816
2817 let result = parse_execute(program).await.unwrap();
2818 let warnings = deprecation_warnings(&result);
2819 assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
2820 assert!(
2821 warnings[0].message.contains("`startSketchOn` is deprecated"),
2822 "found {}",
2823 warnings[0].message
2824 );
2825 assert_eq!(warnings[0].tag, crate::errors::Tag::Deprecated);
2826 }
2827
2828 #[tokio::test(flavor = "multi_thread")]
2829 async fn deprecated_since_warns_for_prerelease_kcl_version() {
2830 let program = r#"@settings(kclVersion = "3.0-preview")
2831plane = startSketchOn(XY)
2832"#;
2833
2834 let result = parse_execute(program).await.unwrap();
2835 let warnings = deprecation_warnings(&result);
2836 assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
2837 assert_eq!(warnings[0].severity, Severity::Warning);
2838 assert_eq!(warnings[0].tag, crate::errors::Tag::Deprecated);
2839 assert!(
2840 warnings[0]
2841 .message
2842 .contains("`startSketchOn` is deprecated as of KCL 2.0"),
2843 "found {}",
2844 warnings[0].message
2845 );
2846 }
2847
2848 #[tokio::test(flavor = "multi_thread")]
2849 async fn deprecation_version_override_does_not_change_program_version() {
2850 let program = crate::Program::parse_no_errs(
2851 r#"@settings(kclVersion = 1.0)
2852plane = startSketchOn(XY)
2853"#,
2854 )
2855 .unwrap();
2856 let exec_ctxt = ExecutorContext {
2857 engine: Arc::new(EngineManager::new_mock()),
2858 engine_batch: crate::engine::EngineBatchContext::default(),
2859 fs: crate::fs::new_file_system_handle(crate::fs::FileManager::new()),
2860 settings: Default::default(),
2861 context_type: ContextType::Mock,
2862 execution_callbacks: Default::default(),
2863 executor_kind: crate::execution::machine::ExecutorKind::resolve(),
2864 machine_call_depth_limit: crate::execution::machine::DEFAULT_MACHINE_CALL_DEPTH_LIMIT,
2865 configure_engine_render: true,
2866 };
2867 let mut exec_state = ExecState::new(&exec_ctxt);
2868 exec_state.set_deprecation_version_override(Some("2.0"));
2869
2870 exec_ctxt.run(&program, &mut exec_state).await.unwrap();
2871
2872 assert_eq!(exec_state.mod_local.settings.kcl_version, crate::KclVersion::V1);
2873 let warnings = exec_state
2874 .issues()
2875 .iter()
2876 .filter(|issue| issue.tag == crate::errors::Tag::Deprecated)
2877 .collect::<Vec<_>>();
2878 assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
2879 }
2880
2881 #[tokio::test(flavor = "multi_thread")]
2882 async fn deprecated_sketch_v1_warning_explains_sketch_solve() {
2883 let program = r#"@settings(kclVersion = 2.0)
2887exampleSketch = startSketchOn(XZ)
2888 |> startProfile(at = [0, 0])
2889 |> line(end = [10, 0])
2890"#;
2891
2892 let result = parse_execute(program).await.unwrap();
2893 let warnings = deprecation_warnings(&result);
2894 assert_eq!(
2895 warnings.len(),
2896 3,
2897 "expected one warning per sketch v1 call, got {warnings:#?}"
2898 );
2899 for warning in warnings {
2900 assert!(
2901 warning.message.contains("sketch-solve"),
2902 "expected sketch-solve context in {}",
2903 warning.message
2904 );
2905 assert!(
2906 warning
2907 .message
2908 .contains("https://zoo.dev/docs/kcl-book/sketch2d_constraints.html"),
2909 "expected docs URL in {}",
2910 warning.message
2911 );
2912 }
2913 }
2914}