use async_recursion::async_recursion;
use indexmap::IndexMap;
use kcl_api::Group;
use kcl_api::OpArg;
use crate::CompilationIssue;
use crate::NodePath;
use crate::NodePathExt;
use crate::SourceRange;
use crate::errors::KclError;
use crate::errors::KclErrorDetails;
use crate::execution::BodyType;
use crate::execution::ExecState;
use crate::execution::ExecutorContext;
use crate::execution::Geometry;
use crate::execution::KclValue;
use crate::execution::KclValueControlFlow;
use crate::execution::Metadata;
use crate::execution::Solid;
use crate::execution::StatementKind;
use crate::execution::TagEngineInfo;
use crate::execution::TagIdentifier;
use crate::execution::annotations;
use crate::execution::cad_op::Operation;
use crate::execution::cad_op::op_from_kcl_value;
use crate::execution::control_continue;
use crate::execution::kcl_value::FunctionBody;
use crate::execution::kcl_value::FunctionSource;
use crate::execution::kcl_value::NamedParam;
use crate::execution::kcl_value::ParamUnavailable;
use crate::execution::memory;
use crate::execution::types::CoercionMode;
use crate::execution::types::RuntimeType;
use crate::parsing::ast::types::CallExpressionKw;
use crate::parsing::ast::types::Node;
use crate::parsing::ast::types::Type;
use crate::std::ConsumedSolidArgCheck;
use crate::std::RegionBehavior;
use crate::std::StaleRegionPolicy;
use crate::std::region_consumption::PendingRegionConsumption;
use crate::std::region_consumption::prepare_region_consumption;
use crate::std::region_consumption::record_consumed_regions;
use crate::std::region_consumption::validate_region_args_not_consumed;
use crate::std::region_consumption::warn_if_region_args_consumed;
use crate::std::solid_consumption::validate_value_not_consumed;
use crate::std::solid_consumption::warn_if_value_consumed_for_deprecated_call;
#[derive(Debug, Clone)]
pub struct Args<Status: ArgsStatus = Desugared> {
pub fn_name: Option<String>,
pub unlabeled: Vec<(Option<String>, Arg)>,
pub labeled: IndexMap<String, Arg>,
pub source_range: SourceRange,
pub node_path: Option<NodePath>,
pub ctx: ExecutorContext,
pub pipe_value: Option<Arg>,
_status: std::marker::PhantomData<Status>,
}
pub trait ArgsStatus: std::fmt::Debug + Clone {}
#[derive(Debug, Clone)]
pub struct Sugary;
impl ArgsStatus for Sugary {}
#[derive(Debug, Clone)]
pub struct Desugared;
impl ArgsStatus for Desugared {}
impl Args<Sugary> {
pub fn new(
labeled: IndexMap<String, Arg>,
unlabeled: Vec<(Option<String>, Arg)>,
source_range: SourceRange,
node_path: Option<NodePath>,
exec_state: &mut ExecState,
ctx: ExecutorContext,
fn_name: Option<String>,
) -> Args<Sugary> {
Args {
fn_name,
labeled,
unlabeled,
source_range,
node_path,
ctx,
pipe_value: exec_state.pipe_value().map(|v| Arg::new(v.clone(), source_range)),
_status: std::marker::PhantomData,
}
}
}
impl<Status: ArgsStatus> Args<Status> {
pub fn len(&self) -> usize {
self.labeled.len() + self.unlabeled.len()
}
pub fn is_empty(&self) -> bool {
self.labeled.is_empty() && self.unlabeled.is_empty()
}
}
impl Args<Desugared> {
pub fn new_no_args(
source_range: SourceRange,
node_path: Option<NodePath>,
ctx: ExecutorContext,
fn_name: Option<String>,
) -> Args {
Args {
fn_name,
unlabeled: Default::default(),
labeled: Default::default(),
source_range,
node_path,
ctx,
pipe_value: None,
_status: std::marker::PhantomData,
}
}
pub(crate) fn unlabeled_kw_arg_unconverted(&self) -> Option<&Arg> {
self.unlabeled.first().map(|(_, a)| a)
}
}
#[derive(Debug, Clone)]
pub struct Arg {
pub value: KclValue,
pub source_range: SourceRange,
}
impl Arg {
pub fn new(value: KclValue, source_range: SourceRange) -> Self {
Self { value, source_range }
}
pub fn synthetic(value: KclValue) -> Self {
Self {
value,
source_range: SourceRange::synthetic(),
}
}
pub fn source_ranges(&self) -> Vec<SourceRange> {
vec![self.source_range]
}
}
impl Node<CallExpressionKw> {
#[async_recursion]
pub(super) async fn execute(
&self,
exec_state: &mut ExecState,
ctx: &ExecutorContext,
) -> Result<KclValueControlFlow, KclError> {
let fn_name = &self.callee;
let callsite: SourceRange = self.into();
let func: KclValue = fn_name.get_result(exec_state, ctx).await?;
let Some(fn_src) = func.as_function() else {
return Err(KclError::new_semantic(KclErrorDetails::new(
"cannot call this because it isn't a function".to_string(),
vec![callsite],
)));
};
let mut fn_args = IndexMap::with_capacity(self.arguments.len());
let mut unlabeled = Vec::new();
if let Some(ref arg_expr) = self.unlabeled {
let source_range = SourceRange::from(arg_expr.clone());
let metadata = Metadata { source_range };
let value_cf = ctx
.execute_expr(arg_expr, exec_state, &metadata, &[], StatementKind::Expression)
.await?;
let value = control_continue!(value_cf);
let label = arg_expr.ident_name().map(str::to_owned);
unlabeled.push((label, Arg::new(value, source_range)))
}
for arg_expr in &self.arguments {
let source_range = SourceRange::from(arg_expr.arg.clone());
let metadata = Metadata { source_range };
let value_cf = ctx
.execute_expr(&arg_expr.arg, exec_state, &metadata, &[], StatementKind::Expression)
.await?;
let value = control_continue!(value_cf);
let arg = Arg::new(value, source_range);
match &arg_expr.label {
Some(l) => {
fn_args.insert(l.name.clone(), arg);
}
None => {
unlabeled.push((arg_expr.arg.ident_name().map(str::to_owned), arg));
}
}
}
let args = Args::new(
fn_args,
unlabeled,
callsite,
self.node_path.clone(),
exec_state,
ctx.clone(),
Some(fn_name.name.name.clone()),
);
let return_value = fn_src
.call_kw(Some(fn_name.to_string()), exec_state, ctx, args, callsite)
.await
.map_err(|e| {
e.add_unwind_location(Some(fn_name.to_string()), callsite)
})?;
let result = return_value.ok_or_else(move || {
let mut source_ranges: Vec<SourceRange> = vec![callsite];
if let KclValue::Function { meta, .. } = func {
source_ranges = meta.iter().map(|m| m.source_range).collect();
};
KclError::new_undefined_value(
KclErrorDetails::new(
format!("Result of user-defined function {fn_name} is undefined"),
source_ranges,
),
None,
)
})?;
Ok(result)
}
}
const SKETCH_V1_MIGRATION_HELP: &str = "It is part of the legacy sketch API (sketch v1), which is replaced by the sketch-solve API.
See https://zoo.dev/docs/kcl-book/sketch2d_constraints.html for an introduction to sketch-solve with examples.
Draw 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()`. ";
fn migration_help(fn_src: &FunctionSource) -> Option<&'static str> {
let name = &fn_src.std_props.as_ref()?.name;
name.starts_with("std::sketch::").then_some(SKETCH_V1_MIGRATION_HELP)
}
impl FunctionSource {
pub(crate) async fn call_kw(
&self,
fn_name: Option<String>,
exec_state: &mut ExecState,
ctx: &ExecutorContext,
args: Args<Sugary>,
callsite: SourceRange,
) -> Result<Option<KclValueControlFlow>, KclError> {
exec_state.inc_call_stack_size(callsite)?;
let result = self.inner_call_kw(fn_name, exec_state, ctx, args, callsite).await;
exec_state.dec_call_stack_size(callsite)?;
result
}
async fn inner_call_kw(
&self,
fn_name: Option<String>,
exec_state: &mut ExecState,
ctx: &ExecutorContext,
args: Args<Sugary>,
callsite: SourceRange,
) -> Result<Option<KclValueControlFlow>, KclError> {
let (state, args) = self.call_setup(&fn_name, exec_state, args, callsite)?;
let result = match &self.body {
FunctionBody::Rust(f) => f(exec_state, args).await.map(Some),
FunctionBody::Kcl(_) => {
if let Err(e) = assign_args_to_params_kw(self, args, exec_state) {
return Err(Self::call_abort_on_arg_binding_failure(state, e, exec_state));
}
let block_result = ctx.exec_block(&self.ast.body, exec_state, BodyType::Block).await;
self.kcl_body_result(block_result, exec_state)
}
};
self.call_finish(state, result, exec_state)
}
pub(super) fn call_setup(
&self,
fn_name: &Option<String>,
exec_state: &mut ExecState,
args: Args<Sugary>,
callsite: SourceRange,
) -> Result<(CallState, Args), KclError> {
let warn_on_deprecated_usage = !exec_state.mod_local.inside_stdlib;
if warn_on_deprecated_usage {
let subject = match &fn_name {
Some(n) => format!("`{n}`"),
None => "This function".to_owned(),
};
let message = if self.deprecated {
Some(match migration_help(self) {
Some(help) => format!("{subject} is deprecated. {help}"),
None => format!("{subject} is deprecated, see the docs for a recommended replacement"),
})
} else if let Some(since) = &self.deprecated_since
&& annotations::version_ge(exec_state.deprecation_version(), since)
{
Some(match migration_help(self) {
Some(help) => format!("{subject} is deprecated as of KCL {since}. {help}"),
None => {
format!(
"{subject} is deprecated as of KCL {since}. See the docs for a recommended replacement."
)
}
})
} else {
None
};
if let Some(message) = message {
let mut issue = CompilationIssue::err(callsite, message);
issue.tag = crate::errors::Tag::Deprecated;
exec_state.warn(issue, annotations::WARN_DEPRECATED);
}
}
if self.experimental {
exec_state.warn_experimental(
&match &fn_name {
Some(n) => format!("`{n}`"),
None => "This function".to_owned(),
},
callsite,
);
}
let args = type_check_params_kw(fn_name.as_deref(), self, args, exec_state)?;
let face_tag_names = face_tag_names_for_call(self, &args);
let pending_region_consumption = prepare_region_consumption(
self.std_props
.as_ref()
.map_or(RegionBehavior::WarnOnConsumed, |props| props.region_behavior),
&args,
exec_state,
)?;
for (label, arg) in &args.labeled {
let Some(param) = self.named_args.get(label.as_str()) else {
continue;
};
if param.experimental {
exec_state.warn_experimental(
&match &fn_name {
Some(f) => format!("`{f}({label})`"),
None => label.to_owned(),
},
arg.source_range,
);
}
let deprecation_suffix = if !warn_on_deprecated_usage {
None
} else if param.deprecated {
Some("is deprecated, see the docs for a recommended replacement".to_owned())
} else if let Some(since) = ¶m.deprecated_since
&& annotations::version_ge(exec_state.deprecation_version(), since)
{
Some(format!(
"is deprecated as of KCL {since}. See the docs for a recommended replacement."
))
} else {
None
};
if let Some(suffix) = deprecation_suffix {
let qualified = match &fn_name {
Some(f) => format!("`{f}({label})`"),
None => format!("`{label}`"),
};
let mut issue = CompilationIssue::err(arg.source_range, format!("{qualified} {suffix}"));
issue.tag = crate::errors::Tag::Deprecated;
exec_state.warn(issue, annotations::WARN_DEPRECATED);
}
}
self.body.prep_mem(exec_state)?;
let would_trace_stdlib_internals = exec_state.mod_local.inside_stdlib && self.is_std();
let should_track_operation = !would_trace_stdlib_internals && self.include_in_feature_tree;
let op = if should_track_operation {
let op_labeled_args = args
.labeled
.iter()
.map(|(k, arg)| (k.clone(), OpArg::new(op_from_kcl_value(&arg.value), arg.source_range)))
.collect();
if self.is_std() {
Some(Operation::StdLibCall {
name: fn_name.clone().unwrap_or_else(|| "unknown function".to_owned()),
unlabeled_arg: args
.unlabeled_kw_arg_unconverted()
.map(|arg| OpArg::new(op_from_kcl_value(&arg.value), arg.source_range)),
labeled_args: op_labeled_args,
node_path: NodePath::placeholder(),
source_range: callsite,
stdlib_entry_source_range: exec_state.mod_local.stdlib_entry_source_range,
is_error: false,
})
} else {
exec_state.push_op(Operation::GroupBegin {
group: Group::FunctionCall {
name: fn_name.clone(),
function_source_range: self.ast.as_source_range(),
unlabeled_arg: args
.unlabeled_kw_arg_unconverted()
.map(|arg| OpArg::new(op_from_kcl_value(&arg.value), arg.source_range)),
labeled_args: op_labeled_args,
},
node_path: NodePath::placeholder(),
source_range: callsite,
});
None
}
} else {
None
};
let is_calling_into_stdlib = match &self.body {
FunctionBody::Rust(_) => true,
FunctionBody::Kcl(_) => self.is_std(),
};
let is_crossing_into_stdlib = is_calling_into_stdlib && !exec_state.mod_local.inside_stdlib;
let is_crossing_out_of_stdlib = !is_calling_into_stdlib && exec_state.mod_local.inside_stdlib;
let stdlib_entry_source_range = if is_crossing_into_stdlib {
Some(callsite)
} else if is_crossing_out_of_stdlib {
None
} else {
exec_state.mod_local.stdlib_entry_source_range
};
let prev_inside_stdlib = std::mem::replace(&mut exec_state.mod_local.inside_stdlib, is_calling_into_stdlib);
let prev_stdlib_entry_source_range = std::mem::replace(
&mut exec_state.mod_local.stdlib_entry_source_range,
stdlib_entry_source_range,
);
Ok((
CallState {
prev_inside_stdlib,
prev_stdlib_entry_source_range,
op,
should_track_operation,
is_calling_into_stdlib,
face_tag_names,
pending_region_consumption,
},
args,
))
}
pub(super) fn kcl_body_result(
&self,
block_result: Result<Option<KclValueControlFlow>, KclError>,
exec_state: &mut ExecState,
) -> Result<Option<KclValueControlFlow>, KclError> {
block_result.map(|cf| {
if let Some(cf) = cf
&& cf.is_some_return()
{
return Some(cf);
}
exec_state
.stack()
.get(memory::RETURN_NAME, self.ast.as_source_range())
.ok()
.map(KclValue::continue_)
})
}
pub(super) fn call_abort_on_arg_binding_failure(
state: CallState,
e: KclError,
exec_state: &mut ExecState,
) -> KclError {
exec_state.mod_local.inside_stdlib = state.prev_inside_stdlib;
match exec_state.mut_stack().pop_env() {
Ok(_) => e,
Err(pop_err) => pop_err,
}
}
pub(super) fn call_finish(
&self,
state: CallState,
result: Result<Option<KclValueControlFlow>, KclError>,
exec_state: &mut ExecState,
) -> Result<Option<KclValueControlFlow>, KclError> {
let CallState {
prev_inside_stdlib,
prev_stdlib_entry_source_range,
op,
should_track_operation,
is_calling_into_stdlib,
face_tag_names,
pending_region_consumption,
} = state;
exec_state.mod_local.inside_stdlib = prev_inside_stdlib;
exec_state.mod_local.stdlib_entry_source_range = prev_stdlib_entry_source_range;
exec_state.mut_stack().pop_env()?;
if result.is_ok()
&& let Some(pending_region_consumption) = pending_region_consumption
{
record_consumed_regions(exec_state, pending_region_consumption);
}
if should_track_operation {
if let Some(mut op) = op {
op.set_std_lib_call_is_error(result.is_err());
exec_state.push_op(op);
} else if !is_calling_into_stdlib {
exec_state.push_op(Operation::GroupEnd);
}
}
let mut result = match result {
Ok(Some(value)) => {
if value.is_exit() {
return Ok(Some(value));
} else {
Ok(Some(value.into_value()))
}
}
Ok(None) => Ok(None),
Err(e) => Err(e),
};
if self.is_std()
&& let Ok(Some(result)) = &mut result
{
update_memory_for_tags_of_geometry(result, exec_state)?;
if !face_tag_names.is_empty() {
attach_face_tags_to_geometry(result, exec_state, &face_tag_names);
}
}
coerce_result_type(result, self, exec_state).map(|r| r.map(KclValue::continue_))
}
}
#[derive(Debug)]
pub(super) struct CallState {
prev_inside_stdlib: bool,
prev_stdlib_entry_source_range: Option<SourceRange>,
op: Option<Operation>,
should_track_operation: bool,
is_calling_into_stdlib: bool,
face_tag_names: Vec<String>,
pending_region_consumption: Option<PendingRegionConsumption>,
}
impl FunctionBody {
fn prep_mem(&self, exec_state: &mut ExecState) -> Result<(), KclError> {
match self {
FunctionBody::Rust(_) => exec_state.mut_stack().push_new_root_env(true),
FunctionBody::Kcl(memory) => exec_state.mut_stack().push_new_env_for_call(*memory),
}
}
}
fn might_be_legacy_sketch(value: &KclValue) -> bool {
match value {
KclValue::Uuid { .. } => false,
KclValue::Bool { .. } => false,
KclValue::Number { .. } => false,
KclValue::String { .. } => false,
KclValue::Enum { .. } => false,
KclValue::SketchVar { .. } => false,
KclValue::SketchConstraint { .. } => false,
KclValue::Tuple { value, .. } => value.iter().any(might_be_legacy_sketch),
KclValue::HomArray { value, .. } => value.iter().any(might_be_legacy_sketch),
KclValue::Object { value, .. } => value.values().any(might_be_legacy_sketch),
KclValue::TagIdentifier(_) => false,
KclValue::TagDeclarator(_) => false,
KclValue::GdtAnnotation { .. } => false,
KclValue::CameraView { .. } => false,
KclValue::NamedView { .. } => false,
KclValue::Plane { .. } => false,
KclValue::Face { .. } => false,
KclValue::BoundedEdge { .. } => false,
KclValue::Segment { .. } => false,
KclValue::Sketch { value: sketch } => sketch.origin_sketch_id.is_none(),
KclValue::Solid { value: solid } => solid
.sketch()
.map(|sketch| sketch.origin_sketch_id.is_none())
.unwrap_or(true),
KclValue::Helix { .. } => false,
KclValue::ImportedGeometry(_) => false,
KclValue::Function { .. } => false,
KclValue::Module { .. } => false,
KclValue::Type { .. } => false,
KclValue::KclNone { .. } => false,
}
}
fn face_tag_names_for_call(fn_def: &FunctionSource, args: &Args<Desugared>) -> Vec<String> {
let Some(std_props) = &fn_def.std_props else {
return Vec::new();
};
if !std_function_allows_face_tags(&std_props.name) {
return Vec::new();
}
args.labeled
.iter()
.filter(|(label, _)| matches!(label.as_str(), "tag" | "tagStart" | "tagEnd"))
.filter_map(|(_, arg)| match &arg.value {
KclValue::TagDeclarator(tag) => Some(tag.name.clone()),
_ => None,
})
.collect()
}
fn std_function_allows_face_tags(std_fn_name: &str) -> bool {
matches!(
std_fn_name,
"std::sketch::extrude"
| "std::solid::chamfer"
| "std::solid::fillet"
| "std::sketch::sweep"
| "std::sketch::loft"
| "std::sketch::revolve"
)
}
fn attach_face_tags_to_geometry(result: &mut KclValue, exec_state: &ExecState, tag_names: &[String]) {
match result {
KclValue::Solid { value } => attach_face_tags_to_solid(value, exec_state, tag_names),
KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
for v in value {
attach_face_tags_to_geometry(v, exec_state, tag_names);
}
}
_ => {}
}
}
fn attach_face_tags_to_solid(solid: &mut Solid, exec_state: &ExecState, tag_names: &[String]) {
let surfaces = solid.value.clone();
for surface in surfaces {
let Some(tag) = surface.get_tag() else {
continue;
};
if !tag_names.iter().any(|tag_name| tag_name == &tag.name) {
continue;
}
let tag_id = solid
.sketch()
.and_then(|sketch| sketch.tags.get(&tag.name))
.cloned()
.unwrap_or_else(|| {
let mut solid_copy = solid.clone();
clear_tags_from_solid_copy(&mut solid_copy);
TagIdentifier {
value: tag.name.clone(),
info: vec![(
exec_state.stack().current_epoch(),
TagEngineInfo {
id: surface.get_id(),
surface: Some(surface.clone()),
path: None,
geometry: Geometry::Solid(solid_copy),
},
)],
meta: vec![Metadata {
source_range: tag.clone().into(),
}],
}
});
match solid.faces.get_mut(&tag.name) {
Some(existing_tag) => existing_tag.merge_info(&tag_id),
None => {
solid.faces.insert(tag.name.clone(), tag_id);
}
}
}
}
fn clear_tags_from_solid_copy(solid: &mut Solid) {
if let Some(sketch) = solid.sketch_mut() {
sketch.tags.clear(); }
solid.faces.clear();
}
fn update_memory_for_tags_of_geometry(result: &mut KclValue, exec_state: &mut ExecState) -> Result<(), KclError> {
let might_be_legacy = might_be_legacy_sketch(&*result);
match result {
KclValue::Sketch { value } if might_be_legacy => {
for (name, tag) in value.tags.iter() {
if exec_state.stack().cur_frame_contains(name)? {
exec_state.mut_stack().update(name, |v, _| {
if let Some(existing_tag) = v.as_mut_tag() {
existing_tag.merge_info(tag);
}
})?;
} else {
exec_state.mut_stack().add(
name.to_owned(),
KclValue::TagIdentifier(Box::new(tag.clone())),
SourceRange::default(),
)?;
}
}
}
KclValue::Solid { value } => {
if value.sketch().is_none() {
return Ok(());
};
let surfaces: Vec<_> = value
.value
.iter()
.filter(|surface| surface.get_tag().is_some())
.cloned()
.collect();
let solid_copies: Vec<Box<Solid>> = surfaces.iter().map(|_| value.clone()).collect();
let Some(sketch) = value.sketch_mut() else {
return Ok(());
};
for (v, mut solid_copy) in surfaces.iter().zip(solid_copies) {
clear_tags_from_solid_copy(&mut solid_copy);
if let Some(tag) = v.get_tag() {
let mut is_part_of_sketch = false;
let tag_id = if let Some(t) = sketch.tags.get(&tag.name) {
is_part_of_sketch = true;
let mut t = t.clone();
let Some(info) = t.get_cur_info() else {
return Err(KclError::new_internal(KclErrorDetails::new(
format!("Tag {} does not have path info", tag.name),
vec![tag.into()],
)));
};
let mut info = info.clone();
info.id = v.get_id();
info.surface = Some(v.clone());
info.geometry = Geometry::Solid(*solid_copy);
t.info.push((exec_state.stack().current_epoch(), info));
t
} else {
TagIdentifier {
value: tag.name.clone(),
info: vec![(
exec_state.stack().current_epoch(),
TagEngineInfo {
id: v.get_id(),
surface: Some(v.clone()),
path: None,
geometry: Geometry::Solid(*solid_copy),
},
)],
meta: vec![Metadata {
source_range: tag.clone().into(),
}],
}
};
sketch.merge_tags(Some(&tag_id).into_iter());
if exec_state.stack().cur_frame_contains(&tag.name)? {
exec_state.mut_stack().update(&tag.name, |v, _| {
if let Some(existing_tag) = v.as_mut_tag() {
existing_tag.merge_info(&tag_id);
}
})?;
} else if might_be_legacy || !is_part_of_sketch {
exec_state.mut_stack().add(
tag.name.clone(),
KclValue::TagIdentifier(Box::new(tag_id)),
SourceRange::default(),
)?;
}
}
}
if let Some(sketch) = value.sketch() {
if sketch.tags.is_empty() {
return Ok(());
}
let sketch_tags: Vec<_> = sketch.tags.values().cloned().collect();
let sketches_to_update: Vec<_> = exec_state.stack().find_keys_in_current_env(|v| match v {
KclValue::Sketch { value: sk } => sk.original_id == sketch.original_id,
_ => false,
})?;
for k in sketches_to_update {
exec_state.mut_stack().update(&k, |v, _| {
if let Some(sketch) = v.as_mut_sketch() {
sketch.merge_tags(sketch_tags.iter());
}
})?;
}
}
}
KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
for v in value {
update_memory_for_tags_of_geometry(v, exec_state)?;
}
}
_ => {}
}
Ok(())
}
fn type_err_str(expected: &Type, found: &KclValue, source_range: &SourceRange, exec_state: &mut ExecState) -> String {
fn strip_backticks(s: &str) -> &str {
let mut result = s;
if s.starts_with('`') {
result = &result[1..]
}
if s.ends_with('`') {
result = &result[..result.len() - 1]
}
result
}
let expected_human = expected.human_friendly_type();
let expected_ty = expected.to_string();
let expected_str =
if expected_human == expected_ty || expected_human == format!("a value with type `{expected_ty}`") {
format!("a value with type `{expected_ty}`")
} else {
format!("{expected_human} (`{expected_ty}`)")
};
let found_human = found.human_friendly_type();
let found_ty = found.principal_type_string();
let found_str = if found_human == found_ty || found_human == format!("a {}", strip_backticks(&found_ty)) {
format!("a value with type {found_ty}")
} else {
format!("{found_human} (with type {found_ty})")
};
let mut result = format!("{expected_str}, but found {found_str}.");
if found.is_unknown_number() {
exec_state.clear_units_warnings(source_range);
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`.");
}
result
}
pub(crate) fn unexpected_kw_arg_message(label: &str, callee_name: Option<&str>) -> String {
format!(
"`{label}` is not an argument of {}",
callee_name
.map(|n| format!("`{n}`"))
.unwrap_or_else(|| "this function".to_owned()),
)
}
fn unavailable_kw_arg_message(
label: &str,
callee_name: Option<&str>,
reason: ParamUnavailable<'_>,
program_version: &str,
) -> String {
let base = unexpected_kw_arg_message(label, callee_name);
match reason {
ParamUnavailable::NotYetAdded(added) => {
format!("{base}; it was added in KCL {added}, but this program uses KCL {program_version}")
}
ParamUnavailable::Removed(removed) => {
format!("{base}; it was removed in KCL {removed}, but this program uses KCL {program_version}")
}
}
}
fn resolved_signature_type<'a>(
resolved: Option<&'a RuntimeType>,
written: &Type,
source_range: SourceRange,
) -> Result<&'a RuntimeType, KclError> {
resolved.ok_or_else(|| {
KclError::new_internal(KclErrorDetails::new(
format!(
"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."
),
vec![source_range],
))
})
}
fn type_check_params_kw(
fn_name: Option<&str>,
fn_def: &FunctionSource,
mut args: Args<Sugary>,
exec_state: &mut ExecState,
) -> Result<Args<Desugared>, KclError> {
let fn_name = fn_name.or(args.fn_name.as_deref());
let mut result = Args::new_no_args(
args.source_range,
args.node_path.clone(),
args.ctx,
fn_name.map(|f| f.to_string()).or_else(|| args.fn_name.clone()),
);
if let Some((Some(label), _)) = args.unlabeled.first()
&& args.unlabeled.len() == 1
&& (fn_def.input_arg.is_none() || args.pipe_value.is_some())
&& fn_def.active_named_arg(label, exec_state).is_some()
&& !args.labeled.contains_key(label)
{
let Some((label, arg)) = args.unlabeled.pop() else {
let message = "Expected unlabeled arg to be present".to_owned();
debug_assert!(false, "{}", &message);
return Err(KclError::new_internal(KclErrorDetails::new(
message,
vec![args.source_range],
)));
};
args.labeled.insert(label.unwrap(), arg);
}
let (labeled_unlabeled, unlabeled_unlabeled) = args.unlabeled.into_iter().partition(|(l, _)| {
if let Some(l) = l
&& fn_def.active_named_arg(l, exec_state).is_some()
&& !args.labeled.contains_key(l)
{
true
} else {
false
}
});
args.unlabeled = unlabeled_unlabeled;
for (l, arg) in labeled_unlabeled {
let previous = args.labeled.insert(l.unwrap(), arg);
debug_assert!(previous.is_none());
}
if let Some((name, ty)) = &fn_def.input_arg {
if args.unlabeled.is_empty() {
if let Some(pipe) = args.pipe_value {
result.unlabeled = vec![(None, pipe)];
} else if let Some(arg) = args.labeled.swap_remove(name) {
exec_state.err(CompilationIssue::err(
arg.source_range,
format!(
"{} expects an unlabeled first argument (`@{name}`), but it is labelled in the call. You might try removing the `{name} = `",
fn_name
.map(|n| format!("The function `{n}`"))
.unwrap_or_else(|| "This function".to_owned()),
),
));
result.unlabeled = vec![(Some(name.clone()), arg)];
} else {
return Err(KclError::new_argument(KclErrorDetails::new(
"This function expects an unlabeled first parameter, but you haven't passed it one.".to_owned(),
fn_def.ast.as_source_ranges(),
)));
}
} else if args.unlabeled.len() == 1
&& let Some(unlabeled_arg) = args.unlabeled.pop()
{
let mut arg = unlabeled_arg.1;
if let Some(ty) = ty {
let rty = resolved_signature_type(fn_def.resolved_input_ty.as_ref(), ty, arg.source_range)?;
arg.value = arg
.value
.coerce(rty, CoercionMode::implicit(), exec_state)
.map_err(|_| {
KclError::new_argument(KclErrorDetails::new(
format!(
"The input argument of {} requires {}",
fn_name
.map(|n| format!("`{n}`"))
.unwrap_or_else(|| "this function".to_owned()),
type_err_str(ty, &arg.value, &arg.source_range, exec_state),
),
vec![arg.source_range],
))
})?;
}
result.unlabeled = vec![(None, arg)]
} else {
if let Some(Type::Array { len, .. }) = ty {
if len.satisfied(args.unlabeled.len(), false).is_none() {
exec_state.err(CompilationIssue::err(
args.source_range,
format!(
"{} expects an array input argument with {} elements",
fn_name
.map(|n| format!("The function `{n}`"))
.unwrap_or_else(|| "This function".to_owned()),
len.human_friendly_type(),
),
));
}
let source_range = SourceRange::merge(args.unlabeled.iter().map(|(_, a)| a.source_range));
exec_state.warn_experimental("array input arguments", source_range);
result.unlabeled = vec![(
None,
Arg {
source_range,
value: KclValue::HomArray {
value: args.unlabeled.drain(..).map(|(_, a)| a.value).collect(),
ty: RuntimeType::any(),
},
},
)]
}
}
}
if !args.unlabeled.is_empty() {
let actuals = args.labeled.keys();
let formals: Vec<_> = fn_def
.active_named_args(exec_state)
.filter_map(|(name, _)| {
if actuals.clone().any(|a| a == name) {
return None;
}
Some(format!("`{name}`"))
})
.collect();
let suggestion = if formals.is_empty() {
String::new()
} else {
format!("; suggested labels: {}", formals.join(", "))
};
let mut errors = args.unlabeled.iter().map(|(_, arg)| {
CompilationIssue::err(
arg.source_range,
format!("This argument needs a label, but it doesn't have one{suggestion}"),
)
});
let first = errors.next().unwrap();
errors.for_each(|e| exec_state.err(e));
return Err(KclError::new_argument(first.into()));
}
for (label, mut arg) in args.labeled {
let param = fn_def.named_args.get(&label);
match param.map(|param| (param, param.unavailable_reason(exec_state))) {
Some((
NamedParam {
experimental: _,
added_in: _,
deprecated: _,
deprecated_since: _,
removed_in: _,
default_value: def,
ty,
resolved_ty,
},
None,
)) => {
if !(def.is_some() && matches!(arg.value, KclValue::KclNone { .. })) {
if let Some(ty) = ty {
let rty = resolved_signature_type(resolved_ty.as_ref(), ty, arg.source_range)?;
arg.value = arg
.value
.coerce(
rty,
CoercionMode::implicit(),
exec_state,
)
.map_err(|e| {
let mut message = format!(
"{label} requires {}",
type_err_str(ty, &arg.value, &arg.source_range, exec_state),
);
if let Some(ty) = e.explicit_coercion {
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}`");
}
KclError::new_argument(KclErrorDetails::new(
message,
vec![arg.source_range],
))
})?;
}
result.labeled.insert(label, arg);
}
}
Some((_, Some(reason))) => {
let message = unavailable_kw_arg_message(&label, fn_name, reason, exec_state.kcl_version().as_str());
exec_state.err(CompilationIssue::err(arg.source_range, message));
}
None => {
exec_state.err(CompilationIssue::err(
arg.source_range,
unexpected_kw_arg_message(&label, fn_name),
));
}
}
}
let consumed_solid_arg_check = fn_def
.std_props
.as_ref()
.map_or(ConsumedSolidArgCheck::Error, |props| props.consumed_solid_arg_check);
if matches!(fn_def.body, FunctionBody::Rust(_))
&& let Some(props) = fn_def.std_props.as_ref()
{
match props.region_behavior.stale_region_policy() {
Some(StaleRegionPolicy::Error) => validate_region_args_not_consumed(&result, exec_state)?,
Some(StaleRegionPolicy::Warning) => {
warn_if_region_args_consumed(&result, exec_state, &props.name)?;
}
None => {}
}
}
match consumed_solid_arg_check {
ConsumedSolidArgCheck::Error => {
result
.unlabeled
.iter()
.map(|(_, arg)| arg)
.chain(result.labeled.values())
.try_for_each(|arg| validate_value_not_consumed(&arg.value, exec_state, arg.source_range))?;
}
ConsumedSolidArgCheck::WarnDeprecated => {
let std_fn_name = fn_def
.std_props
.as_ref()
.map(|props| props.name.as_str())
.unwrap_or("function");
for arg in result
.unlabeled
.iter()
.map(|(_, arg)| arg)
.chain(result.labeled.values())
{
warn_if_value_consumed_for_deprecated_call(&arg.value, exec_state, arg.source_range, std_fn_name)?;
}
}
}
Ok(result)
}
pub(super) fn assign_args_to_params_kw(
fn_def: &FunctionSource,
args: Args<Desugared>,
exec_state: &mut ExecState,
) -> Result<(), KclError> {
let source_ranges = fn_def.ast.as_source_ranges();
for (name, param) in fn_def.named_args.iter() {
let arg = args.labeled.get(name);
match arg {
Some(arg) => {
exec_state.mut_stack().add(
name.clone(),
arg.value.clone(),
arg.source_ranges().pop().unwrap_or(SourceRange::synthetic()),
)?;
}
None => match ¶m.default_value {
Some(default_val) => {
let value = KclValue::from_default_param(default_val.clone(), exec_state);
exec_state
.mut_stack()
.add(name.clone(), value, default_val.source_range())?;
}
None => {
return Err(KclError::new_argument(KclErrorDetails::new(
format!("This function requires a parameter {name}, but you haven't passed it one."),
source_ranges,
)));
}
},
}
}
if let Some((param_name, _)) = &fn_def.input_arg {
let Some(unlabeled) = args.unlabeled_kw_arg_unconverted() else {
debug_assert!(false, "Bad args");
return Err(KclError::new_internal(KclErrorDetails::new(
"Desugared arguments are inconsistent".to_owned(),
source_ranges,
)));
};
exec_state.mut_stack().add(
param_name.clone(),
unlabeled.value.clone(),
unlabeled.source_ranges().pop().unwrap_or(SourceRange::synthetic()),
)?;
}
Ok(())
}
fn coerce_result_type(
result: Result<Option<KclValue>, KclError>,
fn_def: &FunctionSource,
exec_state: &mut ExecState,
) -> Result<Option<KclValue>, KclError> {
let result = result?;
let Some(ret_ty) = &fn_def.return_type else {
return Ok(result);
};
let ty = resolved_signature_type(
fn_def.resolved_return_ty.as_ref(),
&ret_ty.inner,
ret_ty.as_source_range(),
)?;
if ty.subtype(&RuntimeType::never()) {
let message = if result.is_some() {
"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."
} else {
"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."
};
return Err(KclError::new_type(KclErrorDetails::new(
message.to_owned(),
ret_ty.as_source_ranges(),
)));
}
let Some(val) = result else {
return Ok(None);
};
let val = val.coerce(ty, CoercionMode::implicit(), exec_state).map_err(|_| {
KclError::new_type(KclErrorDetails::new(
format!(
"This function requires its result to be {}",
type_err_str(ret_ty, &val, &(&val).into(), exec_state)
),
ret_ty.as_source_ranges(),
))
})?;
Ok(Some(val))
}
#[cfg(test)]
mod test {
use std::sync::Arc;
use super::*;
use crate::engine::engine_manager::EngineManager;
use crate::errors::Severity;
use crate::execution::ContextType;
use crate::execution::EnvironmentRef;
use crate::execution::ExecTestResults;
use crate::execution::memory::Stack;
use crate::execution::parse_execute;
use crate::execution::types::NumericType;
use crate::execution::types::NumericTypeExt;
use crate::parsing::ast::types::DefaultParamVal;
use crate::parsing::ast::types::FunctionExpression;
use crate::parsing::ast::types::Identifier;
use crate::parsing::ast::types::Parameter;
use crate::parsing::ast::types::Program;
fn source_texts<'a>(program: &'a str, error: &KclError) -> Vec<&'a str> {
error
.source_ranges()
.into_iter()
.map(|range| &program[range.start()..range.end()])
.collect()
}
fn get_var(result: &ExecTestResults, name: &str) -> KclValue {
result
.exec_state
.stack()
.memory
.get_from_owned(name, result.mem_env, SourceRange::default(), 0)
.unwrap_or_else(|err| panic!("expected variable `{name}` to exist: {err:?}"))
}
fn var_exists(result: &ExecTestResults, name: &str) -> bool {
result
.exec_state
.stack()
.memory
.get_from_owned(name, result.mem_env, SourceRange::default(), 0)
.is_ok()
}
fn assert_vars_are_tags(result: &ExecTestResults, names: &[&str]) {
for name in names {
assert!(
matches!(get_var(result, name), KclValue::TagIdentifier(_)),
"expected variable `{name}` to be a tag identifier"
);
}
}
fn assert_vars_are_missing(result: &ExecTestResults, names: &[&str]) {
for name in names {
assert!(!var_exists(result, name), "expected variable `{name}` to be absent");
}
}
fn assert_body_face_tags(result: &ExecTestResults, expected: &[&str], unexpected: &[&str]) {
let body = get_var(result, "body");
let KclValue::Solid { value: body } = body else {
panic!("expected `body` to be a solid");
};
for tag in expected {
assert!(body.faces.contains_key(*tag), "expected body.faces to contain `{tag}`");
}
for tag in unexpected {
assert!(
!body.faces.contains_key(*tag),
"expected body.faces not to contain sketch tag `{tag}`"
);
}
}
fn deprecated_solid_tag_access_warnings(result: &ExecTestResults) -> Vec<&CompilationIssue> {
result
.exec_state
.issues()
.iter()
.filter(|issue| issue.message.contains("Accessing solid-created face"))
.collect()
}
#[tokio::test(flavor = "multi_thread")]
async fn test_assign_args_to_params() {
fn mem(number: usize) -> KclValue {
KclValue::Number {
value: number as f64,
ty: NumericType::count(),
meta: Default::default(),
}
}
fn ident(s: &'static str) -> Node<Identifier> {
Node::no_src(Identifier {
name: s.to_owned(),
digest: None,
})
}
fn opt_param(s: &'static str) -> Parameter {
Parameter {
experimental: false,
added_in: None,
deprecated: false,
deprecated_since: None,
removed_in: None,
identifier: ident(s),
param_type: None,
default_value: Some(DefaultParamVal::none()),
labeled: true,
digest: None,
}
}
fn req_param(s: &'static str) -> Parameter {
Parameter {
experimental: false,
added_in: None,
deprecated: false,
deprecated_since: None,
removed_in: None,
identifier: ident(s),
param_type: None,
default_value: None,
labeled: true,
digest: None,
}
}
fn additional_program_memory(items: &[(String, KclValue)]) -> Stack {
let mut program_memory = Stack::new_for_tests();
for (name, item) in items {
program_memory
.add(name.clone(), item.clone(), SourceRange::default())
.unwrap();
}
program_memory
}
for (test_name, params, args, expected) in [
("empty", Vec::new(), Vec::new(), Ok(additional_program_memory(&[]))),
(
"all params required, and all given, should be OK",
vec![req_param("x")],
vec![("x", mem(1))],
Ok(additional_program_memory(&[("x".to_owned(), mem(1))])),
),
(
"all params required, none given, should error",
vec![req_param("x")],
vec![],
Err(KclError::new_argument(KclErrorDetails::new(
"This function requires a parameter x, but you haven't passed it one.".to_owned(),
vec![SourceRange::default()],
))),
),
(
"all params optional, none given, should be OK",
vec![opt_param("x")],
vec![],
Ok(additional_program_memory(&[("x".to_owned(), KclValue::none())])),
),
(
"mixed params, too few given",
vec![req_param("x"), opt_param("y")],
vec![],
Err(KclError::new_argument(KclErrorDetails::new(
"This function requires a parameter x, but you haven't passed it one.".to_owned(),
vec![SourceRange::default()],
))),
),
(
"mixed params, minimum given, should be OK",
vec![req_param("x"), opt_param("y")],
vec![("x", mem(1))],
Ok(additional_program_memory(&[
("x".to_owned(), mem(1)),
("y".to_owned(), KclValue::none()),
])),
),
(
"mixed params, maximum given, should be OK",
vec![req_param("x"), opt_param("y")],
vec![("x", mem(1)), ("y", mem(2))],
Ok(additional_program_memory(&[
("x".to_owned(), mem(1)),
("y".to_owned(), mem(2)),
])),
),
] {
let func_expr = Node::no_src(FunctionExpression {
name: None,
params,
body: Program::empty(),
return_type: None,
digest: None,
});
let func_src = FunctionSource::kcl(
crate::parsing::ast::types::BoxNode::new(func_expr),
EnvironmentRef::dummy(),
crate::execution::kcl_value::KclFunctionSourceParams {
std_props: None,
experimental: false,
include_in_feature_tree: false,
},
);
let labeled = args
.iter()
.map(|(name, value)| {
let arg = Arg::new(value.clone(), SourceRange::default());
((*name).to_owned(), arg)
})
.collect::<IndexMap<_, _>>();
let exec_ctxt = ExecutorContext {
engine: Arc::new(EngineManager::new_mock()),
engine_batch: crate::engine::EngineBatchContext::default(),
fs: crate::fs::new_file_system_handle(crate::fs::FileManager::new()),
settings: Default::default(),
context_type: ContextType::Mock,
execution_callbacks: Default::default(),
executor_kind: crate::execution::machine::ExecutorKind::resolve(),
machine_call_depth_limit: crate::execution::machine::DEFAULT_MACHINE_CALL_DEPTH_LIMIT,
};
let mut exec_state = ExecState::new(&exec_ctxt);
exec_state.mod_local.stack = Stack::new_for_tests();
let args = Args {
fn_name: Some("test".to_owned()),
labeled,
unlabeled: Vec::new(),
source_range: SourceRange::default(),
node_path: None,
ctx: exec_ctxt,
pipe_value: None,
_status: std::marker::PhantomData,
};
let actual = assign_args_to_params_kw(&func_src, args, &mut exec_state).map(|_| exec_state.mod_local.stack);
assert_eq!(
actual, expected,
"failed test '{test_name}':\ngot {actual:?}\nbut expected\n{expected:?}"
);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn type_check_user_args() {
let program = r#"fn makeMessage(prefix: string, suffix: string) {
return prefix + suffix
}
msg1 = makeMessage(prefix = "world", suffix = " hello")
msg2 = makeMessage(prefix = 1, suffix = 3)"#;
let err = parse_execute(program).await.unwrap_err();
assert_eq!(
err.message(),
"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`."
)
}
#[tokio::test(flavor = "multi_thread")]
async fn never_function_cannot_return_a_value() {
let program = r#"@settings(experimentalFeatures = allow)
fn bad(): never {
return 42
}
bad()
"#;
let err = parse_execute(program).await.unwrap_err();
assert!(matches!(&err, KclError::Type { .. }));
assert_eq!(
err.message(),
"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."
);
}
#[tokio::test(flavor = "multi_thread")]
async fn never_function_cannot_fall_through() {
let program = r#"@settings(experimentalFeatures = allow)
fn alsoBad(): never {
x = 42
}
alsoBad()
"#;
let err = parse_execute(program).await.unwrap_err();
assert!(matches!(&err, KclError::Type { .. }));
assert_eq!(
err.message(),
"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."
);
}
#[tokio::test(flavor = "multi_thread")]
async fn never_union_function_cannot_return_a_value() {
let program = r#"@settings(experimentalFeatures = allow)
fn bad(): never | never {
return 42
}
bad()
"#;
let err = parse_execute(program).await.unwrap_err();
assert!(matches!(&err, KclError::Type { .. }));
assert_eq!(
err.message(),
"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."
);
}
#[tokio::test(flavor = "multi_thread")]
async fn never_union_function_cannot_fall_through() {
let program = r#"@settings(experimentalFeatures = allow)
fn alsoBad(): never | never {
x = 42
}
alsoBad()
"#;
let err = parse_execute(program).await.unwrap_err();
assert!(matches!(&err, KclError::Type { .. }));
assert_eq!(
err.message(),
"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."
);
}
#[tokio::test(flavor = "multi_thread")]
async fn never_function_contract_is_path_dependent() {
let function = r#"@settings(experimentalFeatures = allow)
fn failOrReturn(@shouldFail: bool): never {
return if shouldFail {
fail("requested failure")
} else {
42
}
}
"#;
let err = parse_execute(&format!("{function}\nfailOrReturn(true)\n"))
.await
.unwrap_err();
assert!(matches!(&err, KclError::UserDefined { .. }));
assert_eq!(err.message(), "requested failure");
let err = parse_execute(&format!("{function}\nfailOrReturn(false)\n"))
.await
.unwrap_err();
assert!(matches!(&err, KclError::Type { .. }));
assert_eq!(
err.message(),
"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."
);
}
#[tokio::test(flavor = "multi_thread")]
async fn never_type_alias_contract_is_path_dependent() {
let function = r#"@settings(experimentalFeatures = allow)
type impossible = never
fn failOrReturn(@shouldFail: bool): impossible {
return if shouldFail {
fail("requested failure")
} else {
42
}
}
"#;
let err = parse_execute(&format!("{function}\nfailOrReturn(true)\n"))
.await
.unwrap_err();
assert!(matches!(&err, KclError::UserDefined { .. }));
assert_eq!(err.message(), "requested failure");
let err = parse_execute(&format!("{function}\nfailOrReturn(false)\n"))
.await
.unwrap_err();
assert!(matches!(&err, KclError::Type { .. }));
assert_eq!(
err.message(),
"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."
);
}
#[tokio::test(flavor = "multi_thread")]
async fn union_with_never_can_return_a_value_or_fail() {
let function = r#"@settings(experimentalFeatures = allow)
fn stringOrFail(@shouldFail: bool): string | never {
return if shouldFail {
fail("requested failure")
} else {
"ok"
}
}
"#;
let result = parse_execute(&format!("{function}\nresult = stringOrFail(false)\n"))
.await
.unwrap();
let KclValue::String { value, .. } = get_var(&result, "result") else {
panic!("expected `result` to be a string")
};
assert_eq!(value, "ok");
let err = parse_execute(&format!("{function}\nstringOrFail(true)\n"))
.await
.unwrap_err();
assert!(matches!(&err, KclError::UserDefined { .. }));
assert_eq!(err.message(), "requested failure");
}
#[tokio::test(flavor = "multi_thread")]
async fn fail_reports_user_defined_message_and_callsite_once() {
let program = r#"@settings(experimentalFeatures = allow)
fail("custom failure")
"#;
let err = parse_execute(program).await.unwrap_err();
assert!(matches!(&err, KclError::UserDefined { .. }));
assert_eq!(err.message(), "custom failure");
assert_eq!(err.get_message(), "user-defined: custom failure");
assert_eq!(serde_json::to_value(&err).unwrap()["kind"], "user_defined");
assert_eq!(source_texts(program, &err), [r#"fail("custom failure")"#]);
assert_eq!(err.backtrace().len(), 1);
}
#[tokio::test(flavor = "multi_thread")]
async fn fail_unwinds_through_nested_never_functions_once() {
let program = r#"@settings(experimentalFeatures = allow)
fn inner(): never {
fail("nested failure")
}
fn outer(): never {
inner()
}
outer()
"#;
let err = parse_execute(program).await.unwrap_err();
assert!(matches!(&err, KclError::UserDefined { .. }));
assert_eq!(err.message(), "nested failure");
assert_eq!(
source_texts(program, &err),
[r#"fail("nested failure")"#, "inner()", "outer()"]
);
assert_eq!(
err.backtrace()
.iter()
.map(|item| item.fn_name.as_deref())
.collect::<Vec<_>>(),
[Some("inner"), Some("outer"), None]
);
}
#[tokio::test(flavor = "multi_thread")]
async fn fail_is_valid_in_a_function_with_a_value_return_type() {
let function = r#"@settings(experimentalFeatures = allow)
fn valueOrFail(@shouldFail: bool): number {
return if shouldFail {
fail("no value")
} else {
42
}
}
"#;
parse_execute(&format!("{function}\nresult = valueOrFail(false)\n"))
.await
.unwrap();
let err = parse_execute(&format!("{function}\nvalueOrFail(true)\n"))
.await
.unwrap_err();
assert!(matches!(&err, KclError::UserDefined { .. }));
assert_eq!(err.message(), "no value");
}
#[tokio::test(flavor = "multi_thread")]
async fn never_function_with_fail_or_fallthrough_is_path_dependent() {
let function = r#"@settings(experimentalFeatures = allow)
fn failOrFallThrough(@shouldFail: bool): never {
result = if shouldFail {
fail("requested failure")
} else {
42
}
}
"#;
let err = parse_execute(&format!("{function}\nfailOrFallThrough(true)\n"))
.await
.unwrap_err();
assert!(matches!(&err, KclError::UserDefined { .. }));
assert_eq!(err.message(), "requested failure");
let err = parse_execute(&format!("{function}\nfailOrFallThrough(false)\n"))
.await
.unwrap_err();
assert!(matches!(&err, KclError::Type { .. }));
assert_eq!(
err.message(),
"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."
);
}
#[tokio::test(flavor = "multi_thread")]
async fn fail_argument_evaluation_errors_take_precedence() {
let program = r#"@settings(experimentalFeatures = allow)
fn stop(): never {
fail(missingMessage)
}
stop()
"#;
let err = parse_execute(program).await.unwrap_err();
assert!(matches!(&err, KclError::UndefinedValue { .. }));
assert_eq!(err.message(), "`missingMessage` is not defined");
assert_eq!(source_texts(program, &err), ["missingMessage", "stop()"]);
}
#[tokio::test(flavor = "multi_thread")]
async fn fail_rejects_invalid_message_arguments_before_invocation() {
for program in [
"@settings(experimentalFeatures = allow)\nfail()\n",
"@settings(experimentalFeatures = allow)\nfail(42)\n",
] {
let err = parse_execute(program).await.unwrap_err();
assert!(matches!(&err, KclError::Argument { .. }), "{err:?}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn map_closure_error_mentions_fn_name() {
let program = r#"
arr = ["hello"]
map(array = arr, f = fn(@item: number) { return item })
"#;
let err = parse_execute(program).await.unwrap_err();
assert!(
err.message().contains("map closure"),
"expected map closure errors to include the closure name, got: {}",
err.message()
);
}
#[tokio::test(flavor = "multi_thread")]
async fn array_input_arg() {
let ast = r#"fn f(@input: [mm]) { return 1 }
f([1, 2, 3])
f(1, 2, 3)
"#;
parse_execute(ast).await.unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn extrude_tagged_body_gets_face_tags_and_keeps_legacy_bindings() {
let program = r#"@settings(kclVersion = 2.0)
profile = sketch(on = XY) {
line1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
line2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
line3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
line4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
coincident([line1.end, line2.start])
coincident([line2.end, line3.start])
coincident([line3.end, line4.start])
coincident([line4.end, line1.start])
}
region1 = region(point = [5mm, 5mm], sketch = profile)
body = extrude(region1, length = 5mm, tagStart = $bottom, tagEnd = $top)
bottomFromBody = body.faces.bottom
topFromBody = body.faces.top
lineFromSketch = region1.tags.line1
legacyBottom = bottom
legacyTop = top
"#;
let result = parse_execute(program).await.unwrap();
assert_body_face_tags(&result, &["bottom", "top"], &["line1"]);
assert_vars_are_tags(
&result,
&[
"bottom",
"top",
"bottomFromBody",
"topFromBody",
"lineFromSketch",
"legacyBottom",
"legacyTop",
],
);
assert_vars_are_missing(&result, &["line1"]);
}
#[tokio::test(flavor = "multi_thread")]
async fn extrude_without_tag_arguments_does_not_get_face_tags() {
let program = r#"@settings(kclVersion = 2.0)
profile = sketch(on = XY) {
line1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
line2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
line3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
line4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
coincident([line1.end, line2.start])
coincident([line2.end, line3.start])
coincident([line3.end, line4.start])
coincident([line4.end, line1.start])
}
region1 = region(point = [5mm, 5mm], sketch = profile)
body = extrude(region1, length = 5mm)
"#;
let result = parse_execute(program).await.unwrap();
let body = get_var(&result, "body");
let KclValue::Solid { value: body } = body else {
panic!("expected `body` to be a solid");
};
assert!(
body.faces.is_empty(),
"body faces should only be populated for tagged calls"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn revolve_tagged_body_gets_face_tags() {
let program = r#"@settings(kclVersion = 2.0)
profile = sketch(on = XY) {
side = line(start = [var 5mm, var 0mm], end = [var 5mm, var 10mm])
line2 = line(start = [var 5mm, var 10mm], end = [var 6mm, var 10mm])
line3 = line(start = [var 6mm, var 10mm], end = [var 6mm, var 0mm])
line4 = line(start = [var 6mm, var 0mm], end = [var 5mm, var 0mm])
coincident([side.end, line2.start])
coincident([line2.end, line3.start])
coincident([line3.end, line4.start])
coincident([line4.end, side.start])
}
region1 = region(point = [5.5mm, 5mm], sketch = profile)
body = revolve(region1, axis = Y, angle = 90deg, tagStart = $startCap, tagEnd = $endCap)
startFromBody = body.faces.startCap
endFromBody = body.faces.endCap
sideFromSketch = region1.tags.side
legacyStart = startCap
legacyEnd = endCap
"#;
let result = parse_execute(program).await.unwrap();
assert_body_face_tags(&result, &["startCap", "endCap"], &["side"]);
assert_vars_are_tags(
&result,
&[
"startCap",
"endCap",
"startFromBody",
"endFromBody",
"sideFromSketch",
"legacyStart",
"legacyEnd",
],
);
assert_vars_are_missing(&result, &["side"]);
}
#[tokio::test(flavor = "multi_thread")]
async fn sweep_tagged_body_gets_face_tags() {
let program = r#"@settings(kclVersion = 2.0)
profile = sketch(on = XZ) {
edge1 = line(start = [var 0mm, var 0mm], end = [var 2mm, var 0mm])
edge2 = line(start = [var 2mm, var 0mm], end = [var 2mm, var 2mm])
edge3 = line(start = [var 2mm, var 2mm], end = [var 0mm, var 2mm])
edge4 = line(start = [var 0mm, var 2mm], end = [var 0mm, var 0mm])
coincident([edge1.end, edge2.start])
coincident([edge2.end, edge3.start])
coincident([edge3.end, edge4.start])
coincident([edge4.end, edge1.start])
}
profileRegion = region(point = [1mm, 1mm], sketch = profile)
pathSketch = sketch(on = offsetPlane(YZ, offset = -2mm)) {
pathLine = line(start = [var 0mm, var 0mm], end = [var 0mm, var 5mm])
}
body = sweep(profileRegion, path = pathSketch.pathLine, tagStart = $startCap, tagEnd = $endCap)
startFromBody = body.faces.startCap
endFromBody = body.faces.endCap
edgeFromSketch = profileRegion.tags.edge1
pathFromSketch = pathSketch.pathLine
legacyStart = startCap
legacyEnd = endCap
"#;
let result = parse_execute(program).await.unwrap();
assert_body_face_tags(&result, &["startCap", "endCap"], &["edge1", "pathLine"]);
assert_vars_are_tags(
&result,
&[
"startCap",
"endCap",
"startFromBody",
"endFromBody",
"edgeFromSketch",
"legacyStart",
"legacyEnd",
],
);
assert_vars_are_missing(&result, &["edge1", "pathLine"]);
}
#[tokio::test(flavor = "multi_thread")]
async fn loft_tagged_body_gets_face_tags() {
let program = r#"@settings(kclVersion = 2.0)
lowerProfile = sketch(on = XY) {
edge1 = line(start = [var 0mm, var 0mm], end = [var 6mm, var 0mm])
edge2 = line(start = [var 6mm, var 0mm], end = [var 6mm, var 4mm])
edge3 = line(start = [var 6mm, var 4mm], end = [var 0mm, var 4mm])
edge4 = line(start = [var 0mm, var 4mm], end = [var 0mm, var 0mm])
coincident([edge1.end, edge2.start])
coincident([edge2.end, edge3.start])
coincident([edge3.end, edge4.start])
coincident([edge4.end, edge1.start])
}
lowerRegion = region(point = [3mm, 2mm], sketch = lowerProfile)
upperProfile = sketch(on = offsetPlane(XY, offset = 8mm)) {
edge5 = line(start = [var 1mm, var 1mm], end = [var 5mm, var 1mm])
edge6 = line(start = [var 5mm, var 1mm], end = [var 4mm, var 3mm])
edge7 = line(start = [var 4mm, var 3mm], end = [var 2mm, var 3mm])
edge8 = line(start = [var 2mm, var 3mm], end = [var 1mm, var 1mm])
coincident([edge5.end, edge6.start])
coincident([edge6.end, edge7.start])
coincident([edge7.end, edge8.start])
coincident([edge8.end, edge5.start])
}
upperRegion = region(point = [3mm, 2mm], sketch = upperProfile)
body = loft([lowerRegion, upperRegion], tagStart = $startCap, tagEnd = $endCap)
startFromBody = body.faces.startCap
endFromBody = body.faces.endCap
edgeFromSketch = lowerRegion.tags.edge1
legacyStart = startCap
legacyEnd = endCap
"#;
let result = parse_execute(program).await.unwrap();
assert_body_face_tags(&result, &["startCap", "endCap"], &["edge1"]);
assert_vars_are_tags(
&result,
&[
"startCap",
"endCap",
"startFromBody",
"endFromBody",
"edgeFromSketch",
"legacyStart",
"legacyEnd",
],
);
assert_vars_are_missing(&result, &["edge1"]);
}
#[tokio::test(flavor = "multi_thread")]
async fn chamfer_tagged_body_gets_face_tags() {
let program = r#"@settings(kclVersion = 2.0)
profile = sketch(on = XY) {
edge1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
edge2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
edge3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
edge4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
coincident([edge1.end, edge2.start])
coincident([edge2.end, edge3.start])
coincident([edge3.end, edge4.start])
coincident([edge4.end, edge1.start])
}
profileRegion = region(point = [5mm, 5mm], sketch = profile)
base = extrude(profileRegion, length = 5mm, tagEnd = $top)
body = chamfer(base, tags = getCommonEdge(faces = [profileRegion.tags.edge1, top]), length = 1mm, tag = $chamferFace)
chamferFromBody = body.faces.chamferFace
topFromBody = body.faces.top
edgeFromSketch = profileRegion.tags.edge1
legacyChamfer = chamferFace
legacyTop = top
"#;
let result = parse_execute(program).await.unwrap();
assert_body_face_tags(&result, &["top", "chamferFace"], &["edge1"]);
assert_vars_are_tags(
&result,
&[
"top",
"chamferFace",
"chamferFromBody",
"topFromBody",
"edgeFromSketch",
"legacyChamfer",
"legacyTop",
],
);
assert_vars_are_missing(&result, &["edge1"]);
}
#[tokio::test(flavor = "multi_thread")]
async fn fillet_tagged_body_gets_face_tags() {
let program = r#"@settings(kclVersion = 2.0)
profile = sketch(on = XY) {
edge1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
edge2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
edge3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
edge4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
coincident([edge1.end, edge2.start])
coincident([edge2.end, edge3.start])
coincident([edge3.end, edge4.start])
coincident([edge4.end, edge1.start])
}
profileRegion = region(point = [5mm, 5mm], sketch = profile)
base = extrude(profileRegion, length = 5mm, tagEnd = $top)
body = fillet(base, tags = getCommonEdge(faces = [profileRegion.tags.edge1, top]), radius = 1mm, tag = $filletFace)
filletFromBody = body.faces.filletFace
topFromBody = body.faces.top
edgeFromSketch = profileRegion.tags.edge1
legacyFillet = filletFace
legacyTop = top
"#;
let result = parse_execute(program).await.unwrap();
assert_body_face_tags(&result, &["top", "filletFace"], &["edge1"]);
assert_vars_are_tags(
&result,
&[
"top",
"filletFace",
"filletFromBody",
"topFromBody",
"edgeFromSketch",
"legacyFillet",
"legacyTop",
],
);
assert_vars_are_missing(&result, &["edge1"]);
}
#[tokio::test(flavor = "multi_thread")]
async fn accessing_body_tag_through_body_sketch_tags_warns() {
let program = r#"@settings(kclVersion = 2.0)
profile = startSketchOn(XY)
|> startProfile(at = [0, 0])
|> line(end = [10, 0], tag = $line1)
|> line(end = [0, 10])
|> line(end = [-10, 0])
|> close()
body = extrude(profile, length = 5, tagEnd = $top)
topFromSketch = body.sketch.tags.top
topFromBody = body.faces.top
"#;
let result = parse_execute(program).await.unwrap();
assert!(matches!(get_var(&result, "topFromSketch"), KclValue::TagIdentifier(_)));
assert!(matches!(get_var(&result, "topFromBody"), KclValue::TagIdentifier(_)));
let warnings = deprecated_solid_tag_access_warnings(&result);
assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
assert_eq!(warnings[0].severity, Severity::Warning);
assert!(warnings[0].message.contains("`top`"), "found {}", warnings[0].message);
assert!(
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`."),
"found {}",
warnings[0].message
);
}
#[tokio::test(flavor = "multi_thread")]
async fn accessing_sketch_path_tag_through_body_sketch_tags_does_not_warn() {
let program = r#"@settings(kclVersion = 2.0)
profile = startSketchOn(XY)
|> startProfile(at = [0, 0])
|> line(end = [10, 0], tag = $line1)
|> line(end = [0, 10])
|> line(end = [-10, 0])
|> close()
body = extrude(profile, length = 5, tagEnd = $top)
lineFromSketch = body.sketch.tags.line1
"#;
let result = parse_execute(program).await.unwrap();
assert!(matches!(get_var(&result, "lineFromSketch"), KclValue::TagIdentifier(_)));
let warnings = deprecated_solid_tag_access_warnings(&result);
assert!(
warnings.is_empty(),
"sketch path tags should not get body-tag deprecation warnings: {warnings:#?}"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn accessing_body_tag_through_sketch_block_region_tags_warns() {
let program = r#"@settings(kclVersion = 2.0)
profile = sketch(on = XY) {
line1 = line(start = [0, 0], end = [10, 0])
line2 = line(start = [10, 0], end = [10, 10])
line3 = line(start = [10, 10], end = [0, 10])
line4 = line(start = [0, 10], end = [0, 0])
}
profileRegion = region(point = [1, 1], sketch = profile)
body = extrude(profileRegion, length = 5, tagEnd = $top)
topFromRegion = profileRegion.tags.top
"#;
let result = parse_execute(program).await.unwrap();
assert!(matches!(get_var(&result, "topFromRegion"), KclValue::TagIdentifier(_)));
let warnings = deprecated_solid_tag_access_warnings(&result);
assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
assert_eq!(warnings[0].severity, Severity::Warning);
assert!(warnings[0].message.contains("`top`"), "found {}", warnings[0].message);
}
fn deprecation_warnings(result: &ExecTestResults) -> Vec<&CompilationIssue> {
result
.exec_state
.issues()
.iter()
.filter(|issue| issue.message.contains("is deprecated"))
.collect()
}
#[tokio::test(flavor = "multi_thread")]
async fn passing_param_deprecated_for_all_versions_warns() {
let program = r#"@settings(kclVersion = 2.0)
fn f(
@a: number,
@(deprecated = true)
oldArg?: number,
) {
return a
}
x = f(1, oldArg = 2)
"#;
let result = parse_execute(program).await.unwrap();
let warnings = deprecation_warnings(&result);
assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
assert_eq!(warnings[0].severity, Severity::Warning);
assert_eq!(warnings[0].tag, crate::errors::Tag::Deprecated);
assert!(
warnings[0].message.contains("`f(oldArg)` is deprecated"),
"found {}",
warnings[0].message
);
}
#[tokio::test(flavor = "multi_thread")]
async fn not_passing_deprecated_param_does_not_warn() {
let program = r#"fn f(
@a: number,
@(deprecated = true)
oldArg?: number,
) {
return a
}
x = f(1)
"#;
let result = parse_execute(program).await.unwrap();
let warnings = deprecation_warnings(&result);
assert!(
warnings.is_empty(),
"unused deprecated parameter should not warn: {warnings:#?}"
);
}
fn unexpected_arg_errors(result: &ExecTestResults) -> Vec<&CompilationIssue> {
result
.exec_state
.issues()
.iter()
.filter(|issue| issue.message.contains("is not an argument of"))
.collect()
}
#[tokio::test(flavor = "multi_thread")]
async fn passing_removed_param_on_removed_version_errors_like_unknown_arg() {
let program = r#"@settings(kclVersion = "3.0-preview")
fn f(
@a: number,
@(deprecated_since = "2.0", removed_in = "3.0")
oldArg?: number,
) {
return a
}
x = f(1, oldArg = 2)
"#;
let result = parse_execute(program).await.unwrap();
let errors = unexpected_arg_errors(&result);
assert_eq!(
errors.len(),
1,
"expected one unknown-argument error, got {:#?}",
result.issues()
);
assert_eq!(errors[0].severity, Severity::Error);
assert_eq!(
errors[0].message,
"`oldArg` is not an argument of `f`; it was removed in KCL 3.0, but this program uses KCL 3.0-preview"
);
assert!(
deprecation_warnings(&result).is_empty(),
"removed parameter should not also warn: {:#?}",
result.issues()
);
assert!(matches!(get_var(&result, "x"), KclValue::Number { value, .. } if value == 1.0));
}
#[tokio::test(flavor = "multi_thread")]
async fn passing_removed_param_before_removed_version_still_works() {
let program = r#"@settings(kclVersion = 2.0)
fn f(
@a: number,
@(deprecated_since = "2.0", removed_in = "3.0")
oldArg?: number,
) {
return oldArg
}
x = f(1, oldArg = 2)
"#;
let result = parse_execute(program).await.unwrap();
assert!(
unexpected_arg_errors(&result).is_empty(),
"parameter is not removed until 3.0: {:#?}",
result.issues()
);
let warnings = deprecation_warnings(&result);
assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
assert!(
warnings[0].message.contains("`f(oldArg)` is deprecated as of KCL 2.0"),
"found {}",
warnings[0].message
);
assert!(matches!(get_var(&result, "x"), KclValue::Number { value, .. } if value == 2.0));
}
#[tokio::test(flavor = "multi_thread")]
async fn removed_optional_param_binds_its_default() {
let program = r#"@settings(kclVersion = "3.0-preview")
fn f(
@(removed_in = "3.0")
oldArg?: number = 7,
) {
return oldArg
}
x = f()
"#;
let result = parse_execute(program).await.unwrap();
assert!(result.issues().is_empty(), "unexpected issues: {:#?}", result.issues());
assert!(matches!(get_var(&result, "x"), KclValue::Number { value, .. } if value == 7.0));
}
#[tokio::test(flavor = "multi_thread")]
async fn removed_param_is_not_matched_by_label_shorthand() {
let program = r#"@settings(kclVersion = "3.0-preview")
fn f(
@(removed_in = "3.0")
oldArg?: number,
) {
return 1
}
oldArg = 2
x = f(oldArg)
"#;
let err = parse_execute(program).await.unwrap_err();
assert_eq!(err.message(), "This argument needs a label, but it doesn't have one");
}
#[tokio::test(flavor = "multi_thread")]
async fn passing_not_yet_added_param_errors_like_unknown_arg() {
let program = r#"@settings(kclVersion = 2.0)
fn f(
@a: number,
@(added_in = "3.0")
newArg?: number,
) {
return a
}
x = f(1, newArg = 2)
"#;
let result = parse_execute(program).await.unwrap();
let errors = unexpected_arg_errors(&result);
assert_eq!(
errors.len(),
1,
"expected one unknown-argument error, got {:#?}",
result.issues()
);
assert_eq!(errors[0].severity, Severity::Error);
assert_eq!(
errors[0].message,
"`newArg` is not an argument of `f`; it was added in KCL 3.0, but this program uses KCL 2.0"
);
assert!(matches!(get_var(&result, "x"), KclValue::Number { value, .. } if value == 1.0));
}
#[tokio::test(flavor = "multi_thread")]
async fn not_yet_added_param_error_reports_default_kcl_version() {
let program = r#"fn f(
@(added_in = "2.0")
newArg?: number,
) {
return 1
}
x = f(newArg = 2)
"#;
let result = parse_execute(program).await.unwrap();
let errors = unexpected_arg_errors(&result);
assert_eq!(errors.len(), 1, "got {:#?}", result.issues());
assert_eq!(
errors[0].message,
"`newArg` is not an argument of `f`; it was added in KCL 2.0, but this program uses KCL 1.0"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn passing_added_param_on_or_after_added_version_works() {
for (kcl_version, added_in) in [("2.0", "1.0"), ("2.0", "2.0"), ("\"3.0-preview\"", "3.0")] {
let program = format!(
r#"@settings(kclVersion = {kcl_version})
fn f(
@(added_in = "{added_in}")
newArg?: number,
) {{
return newArg
}}
x = f(newArg = 2)
"#
);
let result = parse_execute(&program).await.unwrap();
assert!(
result.issues().is_empty(),
"kclVersion {kcl_version}, added_in {added_in}: {:#?}",
result.issues()
);
assert!(
matches!(get_var(&result, "x"), KclValue::Number { value, .. } if value == 2.0),
"kclVersion {kcl_version}, added_in {added_in}"
);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn not_yet_added_optional_param_binds_its_default() {
let program = r#"@settings(kclVersion = 2.0)
fn f(
@(added_in = "3.0")
newArg?: number = 7,
) {
return newArg
}
x = f()
"#;
let result = parse_execute(program).await.unwrap();
assert!(result.issues().is_empty(), "unexpected issues: {:#?}", result.issues());
assert!(matches!(get_var(&result, "x"), KclValue::Number { value, .. } if value == 7.0));
}
#[tokio::test(flavor = "multi_thread")]
async fn not_yet_added_param_is_not_matched_by_label_shorthand() {
let program = r#"@settings(kclVersion = 2.0)
fn f(
@(added_in = "3.0")
newArg?: number,
) {
return 1
}
newArg = 2
x = f(newArg)
"#;
let err = parse_execute(program).await.unwrap_err();
assert_eq!(err.message(), "This argument needs a label, but it doesn't have one");
}
#[tokio::test(flavor = "multi_thread")]
async fn param_lifecycle_added_then_deprecated_then_removed() {
let body = r#"fn f(
@(added_in = "2.0", deprecated_since = "2.0", removed_in = "3.0")
arg?: number,
) {
return arg
}
x = f(arg = 2)
"#;
for (kcl_version, expected_error) in [
(
"1.0",
Some("`arg` is not an argument of `f`; it was added in KCL 2.0, but this program uses KCL 1.0"),
),
("2.0", None),
(
"\"3.0-preview\"",
Some(
"`arg` is not an argument of `f`; it was removed in KCL 3.0, but this program uses KCL 3.0-preview",
),
),
] {
let program = format!("@settings(kclVersion = {kcl_version})\n{body}");
let result = parse_execute(&program).await.unwrap();
let errors = unexpected_arg_errors(&result);
match expected_error {
Some(message) => {
assert_eq!(errors.len(), 1, "kclVersion {kcl_version}: {:#?}", result.issues());
assert_eq!(errors[0].message, message, "kclVersion {kcl_version}");
assert!(
deprecation_warnings(&result).is_empty(),
"kclVersion {kcl_version}: an unavailable parameter should not also warn: {:#?}",
result.issues()
);
}
None => {
assert!(errors.is_empty(), "kclVersion {kcl_version}: {:#?}", result.issues());
assert_eq!(
deprecation_warnings(&result).len(),
1,
"kclVersion {kcl_version}: {:#?}",
result.issues()
);
assert!(
matches!(get_var(&result, "x"), KclValue::Number { value, .. } if value == 2.0),
"kclVersion {kcl_version}"
);
}
}
}
}
#[tokio::test(flavor = "multi_thread")]
async fn stdlib_legacy_method_is_removed_in_kcl_3() {
let solids = r#"left = startSketchOn(XY)
|> circle(center = [0, 0], radius = 2)
|> extrude(length = 1)
right = startSketchOn(XY)
|> circle(center = [1, 0], radius = 2)
|> extrude(length = 1)
both = union([left, right], legacyMethod = true)
"#;
let program = format!("@settings(kclVersion = \"3.0-preview\")\n{solids}");
let result = parse_execute(&program).await.unwrap();
let errors = unexpected_arg_errors(&result);
assert_eq!(errors.len(), 1, "got {:#?}", result.issues());
assert_eq!(
errors[0].message,
"`legacyMethod` is not an argument of `union`; it was removed in KCL 3.0, but this program uses KCL 3.0-preview"
);
let program = format!("@settings(kclVersion = 2.0)\n{solids}");
let result = parse_execute(&program).await.unwrap();
assert!(unexpected_arg_errors(&result).is_empty(), "got {:#?}", result.issues());
assert!(
deprecation_warnings(&result)
.iter()
.any(|w| w.message.contains("`union(legacyMethod)` is deprecated as of KCL 2.0")),
"got {:#?}",
result.issues()
);
}
#[tokio::test(flavor = "multi_thread")]
async fn deprecated_calls_inside_kcl_stdlib_do_not_warn() {
let program = include_str!("../../tests/cube_with_hole/input.kcl");
let result = parse_execute(program).await.unwrap();
let warnings = deprecation_warnings(&result);
assert!(
warnings.is_empty(),
"KCL stdlib internals should not emit deprecation warnings: {warnings:#?}"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn deprecated_stdlib_call_from_user_code_still_warns() {
let program = r#"@settings(kclVersion = 2.0)
plane = startSketchOn(XY)
"#;
let result = parse_execute(program).await.unwrap();
let warnings = deprecation_warnings(&result);
assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
assert!(
warnings[0].message.contains("`startSketchOn` is deprecated"),
"found {}",
warnings[0].message
);
assert_eq!(warnings[0].tag, crate::errors::Tag::Deprecated);
}
#[tokio::test(flavor = "multi_thread")]
async fn deprecated_since_warns_for_prerelease_kcl_version() {
let program = r#"@settings(kclVersion = "3.0-preview")
plane = startSketchOn(XY)
"#;
let result = parse_execute(program).await.unwrap();
let warnings = deprecation_warnings(&result);
assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
assert_eq!(warnings[0].severity, Severity::Warning);
assert_eq!(warnings[0].tag, crate::errors::Tag::Deprecated);
assert!(
warnings[0]
.message
.contains("`startSketchOn` is deprecated as of KCL 2.0"),
"found {}",
warnings[0].message
);
}
#[tokio::test(flavor = "multi_thread")]
async fn deprecation_version_override_does_not_change_program_version() {
let program = crate::Program::parse_no_errs(
r#"@settings(kclVersion = 1.0)
plane = startSketchOn(XY)
"#,
)
.unwrap();
let exec_ctxt = ExecutorContext {
engine: Arc::new(EngineManager::new_mock()),
engine_batch: crate::engine::EngineBatchContext::default(),
fs: crate::fs::new_file_system_handle(crate::fs::FileManager::new()),
settings: Default::default(),
context_type: ContextType::Mock,
execution_callbacks: Default::default(),
executor_kind: crate::execution::machine::ExecutorKind::resolve(),
machine_call_depth_limit: crate::execution::machine::DEFAULT_MACHINE_CALL_DEPTH_LIMIT,
};
let mut exec_state = ExecState::new(&exec_ctxt);
exec_state.set_deprecation_version_override(Some("2.0"));
exec_ctxt.run(&program, &mut exec_state).await.unwrap();
assert_eq!(exec_state.mod_local.settings.kcl_version, crate::KclVersion::V1);
let warnings = exec_state
.issues()
.iter()
.filter(|issue| issue.tag == crate::errors::Tag::Deprecated)
.collect::<Vec<_>>();
assert_eq!(warnings.len(), 1, "expected one deprecation warning, got {warnings:#?}");
}
#[tokio::test(flavor = "multi_thread")]
async fn deprecated_sketch_v1_warning_explains_sketch_solve() {
let program = r#"@settings(kclVersion = 2.0)
exampleSketch = startSketchOn(XZ)
|> startProfile(at = [0, 0])
|> line(end = [10, 0])
"#;
let result = parse_execute(program).await.unwrap();
let warnings = deprecation_warnings(&result);
assert_eq!(
warnings.len(),
3,
"expected one warning per sketch v1 call, got {warnings:#?}"
);
for warning in warnings {
assert!(
warning.message.contains("sketch-solve"),
"expected sketch-solve context in {}",
warning.message
);
assert!(
warning
.message
.contains("https://zoo.dev/docs/kcl-book/sketch2d_constraints.html"),
"expected docs URL in {}",
warning.message
);
}
}
}