Type check and coerce arguments to user functions and return values from std Rust functions (#6958)

* Shuffle around function call code

Signed-off-by: Nick Cameron <nrc@ncameron.org>

* Refactor function calls to share more code

Signed-off-by: Nick Cameron <nrc@ncameron.org>

* Hack to leave the result of revolve as a singleton rather than array

Signed-off-by: Nick Cameron <nrc@ncameron.org>

---------

Signed-off-by: Nick Cameron <nrc@ncameron.org>
This commit is contained in:
Nick Cameron
2025-05-19 16:50:15 +12:00
committed by GitHub
parent f3e9d110c0
commit b19acd550d
197 changed files with 13837 additions and 14317 deletions

View File

@ -2,18 +2,17 @@ use fnv::FnvHashMap;
use indexmap::IndexMap;
use kittycad_modeling_cmds::{
self as kcmc,
id::ModelingCmdId,
ok_response::OkModelingCmdResponse,
shared::ExtrusionFaceCapType,
websocket::{BatchResponse, OkWebSocketResponseData, WebSocketResponse},
EnableSketchMode, ModelingCmd,
};
use schemars::JsonSchema;
use serde::{ser::SerializeSeq, Serialize};
use uuid::Uuid;
use crate::{
errors::KclErrorDetails,
execution::ArtifactId,
parsing::ast::types::{Node, Program},
KclError, NodePath, SourceRange,
};
@ -58,52 +57,6 @@ impl PartialOrd for ArtifactCommand {
}
}
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, Ord, PartialOrd, Hash, ts_rs::TS, JsonSchema)]
#[ts(export_to = "Artifact.ts")]
pub struct ArtifactId(Uuid);
impl ArtifactId {
pub fn new(uuid: Uuid) -> Self {
Self(uuid)
}
}
impl From<Uuid> for ArtifactId {
fn from(uuid: Uuid) -> Self {
Self::new(uuid)
}
}
impl From<&Uuid> for ArtifactId {
fn from(uuid: &Uuid) -> Self {
Self::new(*uuid)
}
}
impl From<ArtifactId> for Uuid {
fn from(id: ArtifactId) -> Self {
id.0
}
}
impl From<&ArtifactId> for Uuid {
fn from(id: &ArtifactId) -> Self {
id.0
}
}
impl From<ModelingCmdId> for ArtifactId {
fn from(id: ModelingCmdId) -> Self {
Self::new(*id.as_ref())
}
}
impl From<&ModelingCmdId> for ArtifactId {
fn from(id: &ModelingCmdId) -> Self {
Self::new(*id.as_ref())
}
}
pub type DummyPathToNode = Vec<()>;
fn serialize_dummy_path_to_node<S>(_path_to_node: &DummyPathToNode, serializer: S) -> Result<S::Ok, S::Error>

View File

@ -3,7 +3,7 @@ use schemars::JsonSchema;
use serde::Serialize;
use super::{types::NumericType, ArtifactId, KclValue};
use crate::{docs::StdLibFn, ModuleId, SourceRange};
use crate::{ModuleId, SourceRange};
/// A CAD modeling operation for display in the feature tree, AKA operations
/// timeline.
@ -13,21 +13,6 @@ use crate::{docs::StdLibFn, ModuleId, SourceRange};
pub enum Operation {
#[serde(rename_all = "camelCase")]
StdLibCall {
/// The standard library function being called.
#[serde(flatten)]
std_lib_fn: StdLibFnRef,
/// The unlabeled argument to the function.
unlabeled_arg: Option<OpArg>,
/// The labeled keyword arguments to the function.
labeled_args: IndexMap<String, OpArg>,
/// The source range of the operation in the source code.
source_range: SourceRange,
/// True if the operation resulted in an error.
#[serde(default, skip_serializing_if = "is_false")]
is_error: bool,
},
#[serde(rename_all = "camelCase")]
KclStdLibCall {
name: String,
/// The unlabeled argument to the function.
unlabeled_arg: Option<OpArg>,
@ -57,19 +42,12 @@ impl PartialOrd for Operation {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(match (self, other) {
(Self::StdLibCall { source_range: a, .. }, Self::StdLibCall { source_range: b, .. }) => a.cmp(b),
(Self::StdLibCall { source_range: a, .. }, Self::KclStdLibCall { source_range: b, .. }) => a.cmp(b),
(Self::StdLibCall { source_range: a, .. }, Self::GroupBegin { source_range: b, .. }) => a.cmp(b),
(Self::StdLibCall { .. }, Self::GroupEnd) => std::cmp::Ordering::Less,
(Self::KclStdLibCall { source_range: a, .. }, Self::KclStdLibCall { source_range: b, .. }) => a.cmp(b),
(Self::KclStdLibCall { source_range: a, .. }, Self::StdLibCall { source_range: b, .. }) => a.cmp(b),
(Self::KclStdLibCall { source_range: a, .. }, Self::GroupBegin { source_range: b, .. }) => a.cmp(b),
(Self::KclStdLibCall { .. }, Self::GroupEnd) => std::cmp::Ordering::Less,
(Self::GroupBegin { source_range: a, .. }, Self::GroupBegin { source_range: b, .. }) => a.cmp(b),
(Self::GroupBegin { source_range: a, .. }, Self::StdLibCall { source_range: b, .. }) => a.cmp(b),
(Self::GroupBegin { source_range: a, .. }, Self::KclStdLibCall { source_range: b, .. }) => a.cmp(b),
(Self::GroupBegin { .. }, Self::GroupEnd) => std::cmp::Ordering::Less,
(Self::GroupEnd, Self::StdLibCall { .. }) => std::cmp::Ordering::Greater,
(Self::GroupEnd, Self::KclStdLibCall { .. }) => std::cmp::Ordering::Greater,
(Self::GroupEnd, Self::GroupBegin { .. }) => std::cmp::Ordering::Greater,
(Self::GroupEnd, Self::GroupEnd) => std::cmp::Ordering::Equal,
})
@ -81,7 +59,6 @@ impl Operation {
pub(crate) fn set_std_lib_call_is_error(&mut self, is_err: bool) {
match self {
Self::StdLibCall { ref mut is_error, .. } => *is_error = is_err,
Self::KclStdLibCall { ref mut is_error, .. } => *is_error = is_err,
Self::GroupBegin { .. } | Self::GroupEnd => {}
}
}
@ -107,6 +84,7 @@ pub enum Group {
labeled_args: IndexMap<String, OpArg>,
},
/// A whole-module import use.
#[allow(dead_code)]
#[serde(rename_all = "camelCase")]
ModuleInstance {
/// The name of the module being used.
@ -135,54 +113,6 @@ impl OpArg {
}
}
/// A reference to a standard library function. This exists to implement
/// `PartialEq` and `Eq` for `Operation`.
#[derive(Debug, Clone, Serialize, ts_rs::TS, JsonSchema)]
#[ts(export_to = "Operation.ts")]
#[serde(rename_all = "camelCase")]
pub struct StdLibFnRef {
// The following doc comment gets inlined into Operation, overriding what's
// there, in the generated TS. We serialize to its name. Renaming the
// field to "name" allows it to match the other variant.
/// The standard library function being called.
#[serde(
rename = "name",
serialize_with = "std_lib_fn_name",
deserialize_with = "std_lib_fn_from_name"
)]
#[ts(type = "string", rename = "name")]
pub std_lib_fn: Box<dyn StdLibFn>,
}
impl StdLibFnRef {
pub(crate) fn new(std_lib_fn: Box<dyn StdLibFn>) -> Self {
Self { std_lib_fn }
}
}
impl From<&Box<dyn StdLibFn>> for StdLibFnRef {
fn from(std_lib_fn: &Box<dyn StdLibFn>) -> Self {
Self::new(std_lib_fn.clone())
}
}
impl PartialEq for StdLibFnRef {
fn eq(&self, other: &Self) -> bool {
self.std_lib_fn.name() == other.std_lib_fn.name()
}
}
impl Eq for StdLibFnRef {}
#[expect(clippy::borrowed_box, reason = "Explicit Box is needed for serde")]
fn std_lib_fn_name<S>(std_lib_fn: &Box<dyn StdLibFn>, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let name = std_lib_fn.name();
serializer.serialize_str(&name)
}
fn is_false(b: &bool) -> bool {
!*b
}

View File

@ -1,42 +1,32 @@
use std::collections::HashMap;
use async_recursion::async_recursion;
use indexmap::IndexMap;
#[cfg(feature = "artifact-graph")]
use crate::execution::cad_op::{Group, OpArg, OpKclValue, Operation};
use crate::{
errors::{KclError, KclErrorDetails},
execution::{
annotations,
fn_call::Args,
kcl_value::{FunctionSource, TypeDef},
memory,
state::ModuleState,
types::{NumericType, PrimitiveType, RuntimeType},
BodyType, EnvironmentRef, ExecState, ExecutorContext, KclValue, Metadata, PlaneType, TagEngineInfo,
BodyType, EnvironmentRef, ExecState, ExecutorContext, KclValue, Metadata, PlaneType, StatementKind,
TagIdentifier,
},
fmt,
modules::{ModuleId, ModulePath, ModuleRepr},
parsing::ast::types::{
Annotation, ArrayExpression, ArrayRangeExpression, AscribedExpression, BinaryExpression, BinaryOperator,
BinaryPart, BodyItem, CallExpressionKw, Expr, FunctionExpression, IfExpression, ImportPath, ImportSelector,
ItemVisibility, LiteralIdentifier, LiteralValue, MemberExpression, MemberObject, Name, Node, NodeRef,
ObjectExpression, PipeExpression, Program, TagDeclarator, Type, UnaryExpression, UnaryOperator,
BinaryPart, BodyItem, Expr, IfExpression, ImportPath, ImportSelector, ItemVisibility, LiteralIdentifier,
LiteralValue, MemberExpression, MemberObject, Name, Node, NodeRef, ObjectExpression, PipeExpression, Program,
TagDeclarator, Type, UnaryExpression, UnaryOperator,
},
source_range::SourceRange,
std::{
args::{Arg, Args, KwArgs, TyF64},
FunctionKind,
},
std::args::TyF64,
CompilationError,
};
enum StatementKind<'a> {
Declaration { name: &'a str },
Expression,
}
impl<'a> StatementKind<'a> {
fn expect_name(&self) -> &'a str {
match self {
@ -594,7 +584,7 @@ impl ExecutorContext {
}
#[async_recursion]
async fn execute_expr<'a: 'async_recursion>(
pub(super) async fn execute_expr<'a: 'async_recursion>(
&self,
init: &Expr,
exec_state: &mut ExecState,
@ -787,7 +777,7 @@ impl BinaryPart {
}
impl Node<Name> {
async fn get_result<'a>(
pub(super) async fn get_result<'a>(
&self,
exec_state: &'a mut ExecState,
ctx: &ExecutorContext,
@ -1305,300 +1295,6 @@ async fn inner_execute_pipe_body(
Ok(final_output)
}
impl Node<CallExpressionKw> {
#[async_recursion]
pub async fn execute(&self, exec_state: &mut ExecState, ctx: &ExecutorContext) -> Result<KclValue, KclError> {
let fn_name = &self.callee;
let callsite: SourceRange = self.into();
// Build a hashmap from argument labels to the final evaluated values.
let mut fn_args = IndexMap::with_capacity(self.arguments.len());
let mut errors = Vec::new();
for arg_expr in &self.arguments {
let source_range = SourceRange::from(arg_expr.arg.clone());
let metadata = Metadata { source_range };
let value = ctx
.execute_expr(&arg_expr.arg, exec_state, &metadata, &[], StatementKind::Expression)
.await?;
let arg = Arg::new(value, source_range);
match &arg_expr.label {
Some(l) => {
fn_args.insert(l.name.clone(), arg);
}
None => {
if let Some(id) = arg_expr.arg.ident_name() {
fn_args.insert(id.to_owned(), arg);
} else {
errors.push(arg);
}
}
}
}
// Evaluate the unlabeled first param, if any exists.
let unlabeled = if let Some(ref arg_expr) = self.unlabeled {
let source_range = SourceRange::from(arg_expr.clone());
let metadata = Metadata { source_range };
let value = ctx
.execute_expr(arg_expr, exec_state, &metadata, &[], StatementKind::Expression)
.await?;
let label = arg_expr.ident_name().map(str::to_owned);
Some((label, Arg::new(value, source_range)))
} else {
None
};
let mut args = Args::new_kw(
KwArgs {
unlabeled,
labeled: fn_args,
errors,
},
self.into(),
ctx.clone(),
exec_state.pipe_value().map(|v| Arg::new(v.clone(), callsite)),
);
match ctx.stdlib.get_either(fn_name) {
FunctionKind::Core(func) => {
if func.deprecated() {
exec_state.warn(CompilationError::err(
self.callee.as_source_range(),
format!("`{fn_name}` is deprecated, see the docs for a recommended replacement"),
));
}
let formals = func.args(false);
// If it's possible the input arg was meant to be labelled and we probably don't want to use
// it as the input arg, then treat it as labelled.
if let Some((Some(label), _)) = &args.kw_args.unlabeled {
if (formals.iter().all(|a| a.label_required) || exec_state.pipe_value().is_some())
&& formals.iter().any(|a| &a.name == label && a.label_required)
&& !args.kw_args.labeled.contains_key(label)
{
let (label, arg) = args.kw_args.unlabeled.take().unwrap();
args.kw_args.labeled.insert(label.unwrap(), arg);
}
}
#[cfg(feature = "artifact-graph")]
let op = if func.feature_tree_operation() {
let op_labeled_args = args
.kw_args
.labeled
.iter()
.map(|(k, arg)| (k.clone(), OpArg::new(OpKclValue::from(&arg.value), arg.source_range)))
.collect();
Some(Operation::StdLibCall {
std_lib_fn: (&func).into(),
unlabeled_arg: args
.unlabeled_kw_arg_unconverted()
.map(|arg| OpArg::new(OpKclValue::from(&arg.value), arg.source_range)),
labeled_args: op_labeled_args,
source_range: callsite,
is_error: false,
})
} else {
None
};
for (label, arg) in &args.kw_args.labeled {
match formals.iter().find(|p| &p.name == label) {
Some(p) => {
if !p.label_required {
exec_state.err(CompilationError::err(
arg.source_range,
format!(
"The function `{fn_name}` expects an unlabeled first parameter (`{label}`), but it is labelled in the call"
),
));
}
}
None => {
exec_state.err(CompilationError::err(
arg.source_range,
format!("`{label}` is not an argument of `{fn_name}`"),
));
}
}
}
// Attempt to call the function.
let mut return_value = {
// Don't early-return in this block.
exec_state.mut_stack().push_new_env_for_rust_call();
let result = func.std_lib_fn()(exec_state, args).await;
exec_state.mut_stack().pop_env();
#[cfg(feature = "artifact-graph")]
if let Some(mut op) = op {
op.set_std_lib_call_is_error(result.is_err());
// Track call operation. We do this after the call
// since things like patternTransform may call user code
// before running, and we will likely want to use the
// return value. The call takes ownership of the args,
// so we need to build the op before the call.
exec_state.global.operations.push(op);
}
result
}?;
update_memory_for_tags_of_geometry(&mut return_value, exec_state)?;
Ok(return_value)
}
FunctionKind::UserDefined => {
// Clone the function so that we can use a mutable reference to
// exec_state.
let func = fn_name.get_result(exec_state, ctx).await?.clone();
let Some(fn_src) = func.as_fn() else {
return Err(KclError::Semantic(KclErrorDetails {
message: "cannot call this because it isn't a function".to_string(),
source_ranges: vec![callsite],
}));
};
let return_value = fn_src
.call_kw(Some(fn_name.to_string()), exec_state, ctx, args, callsite)
.await
.map_err(|e| {
// Add the call expression to the source ranges.
e.add_source_ranges(vec![callsite])
})?;
let result = return_value.ok_or_else(move || {
let mut source_ranges: Vec<SourceRange> = vec![callsite];
// We want to send the source range of the original function.
if let KclValue::Function { meta, .. } = func {
source_ranges = meta.iter().map(|m| m.source_range).collect();
};
KclError::UndefinedValue(KclErrorDetails {
message: format!("Result of user-defined function {} is undefined", fn_name),
source_ranges,
})
})?;
Ok(result)
}
}
}
}
fn update_memory_for_tags_of_geometry(result: &mut KclValue, exec_state: &mut ExecState) -> Result<(), KclError> {
// If the return result is a sketch or solid, we want to update the
// memory for the tags of the group.
// TODO: This could probably be done in a better way, but as of now this was my only idea
// and it works.
match result {
KclValue::Sketch { value } => {
for (name, tag) in value.tags.iter() {
if exec_state.stack().cur_frame_contains(name) {
exec_state.mut_stack().update(name, |v, _| {
v.as_mut_tag().unwrap().merge_info(tag);
});
} else {
exec_state
.mut_stack()
.add(
name.to_owned(),
KclValue::TagIdentifier(Box::new(tag.clone())),
SourceRange::default(),
)
.unwrap();
}
}
}
KclValue::Solid { ref mut value } => {
for v in &value.value {
if let Some(tag) = v.get_tag() {
// Get the past tag and update it.
let tag_id = if let Some(t) = value.sketch.tags.get(&tag.name) {
let mut t = t.clone();
let Some(info) = t.get_cur_info() else {
return Err(KclError::Internal(KclErrorDetails {
message: format!("Tag {} does not have path info", tag.name),
source_ranges: vec![tag.into()],
}));
};
let mut info = info.clone();
info.surface = Some(v.clone());
info.sketch = value.id;
t.info.push((exec_state.stack().current_epoch(), info));
t
} else {
// It's probably a fillet or a chamfer.
// Initialize it.
TagIdentifier {
value: tag.name.clone(),
info: vec![(
exec_state.stack().current_epoch(),
TagEngineInfo {
id: v.get_id(),
surface: Some(v.clone()),
path: None,
sketch: value.id,
},
)],
meta: vec![Metadata {
source_range: tag.clone().into(),
}],
}
};
// update the sketch tags.
value.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, _| {
v.as_mut_tag().unwrap().merge_info(&tag_id);
});
} else {
exec_state
.mut_stack()
.add(
tag.name.clone(),
KclValue::TagIdentifier(Box::new(tag_id)),
SourceRange::default(),
)
.unwrap();
}
}
}
// Find the stale sketch in memory and update it.
if !value.sketch.tags.is_empty() {
let sketches_to_update: Vec<_> = exec_state
.stack()
.find_keys_in_current_env(|v| match v {
KclValue::Sketch { value: sk } => sk.original_id == value.sketch.original_id,
_ => false,
})
.cloned()
.collect();
for k in sketches_to_update {
exec_state.mut_stack().update(&k, |v, _| {
let sketch = v.as_mut_sketch().unwrap();
sketch.merge_tags(value.sketch.tags.values());
});
}
}
}
KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
for v in value {
update_memory_for_tags_of_geometry(v, exec_state)?;
}
}
_ => {}
}
Ok(())
}
impl Node<TagDeclarator> {
pub async fn execute(&self, exec_state: &mut ExecState) -> Result<KclValue, KclError> {
let memory_item = KclValue::TagIdentifier(Box::new(TagIdentifier {
@ -1893,409 +1589,6 @@ impl Node<PipeExpression> {
}
}
fn type_check_params_kw(
fn_name: Option<&str>,
function_expression: NodeRef<'_, FunctionExpression>,
args: &mut KwArgs,
exec_state: &mut ExecState,
) -> Result<(), KclError> {
// If it's possible the input arg was meant to be labelled and we probably don't want to use
// it as the input arg, then treat it as labelled.
if let Some((Some(label), _)) = &args.unlabeled {
if (function_expression.params.iter().all(|p| p.labeled) || exec_state.pipe_value().is_some())
&& function_expression
.params
.iter()
.any(|p| &p.identifier.name == label && p.labeled)
&& !args.labeled.contains_key(label)
{
let (label, arg) = args.unlabeled.take().unwrap();
args.labeled.insert(label.unwrap(), arg);
}
}
for (label, arg) in &mut args.labeled {
match function_expression.params.iter().find(|p| &p.identifier.name == label) {
Some(p) => {
if !p.labeled {
exec_state.err(CompilationError::err(
arg.source_range,
format!(
"{} expects an unlabeled first parameter (`{label}`), but it is labelled in the call",
fn_name
.map(|n| format!("The function `{}`", n))
.unwrap_or_else(|| "This function".to_owned()),
),
));
}
if let Some(ty) = &p.type_ {
arg.value = arg
.value
.coerce(
&RuntimeType::from_parsed(ty.inner.clone(), exec_state, arg.source_range).map_err(|e| KclError::Semantic(e.into()))?,
exec_state,
)
.map_err(|e| {
let mut message = format!(
"{label} requires a value with type `{}`, but found {}",
ty.inner,
arg.value.human_friendly_type(),
);
if let Some(ty) = e.explicit_coercion {
// TODO if we have access to the AST for the argument we could choose which example to suggest.
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(): number({ty})`");
}
KclError::Semantic(KclErrorDetails {
message,
source_ranges: vec![arg.source_range],
})
})?;
}
}
None => {
exec_state.err(CompilationError::err(
arg.source_range,
format!(
"`{label}` is not an argument of {}",
fn_name
.map(|n| format!("`{}`", n))
.unwrap_or_else(|| "this function".to_owned()),
),
));
}
}
}
if !args.errors.is_empty() {
let actuals = args.labeled.keys();
let formals: Vec<_> = function_expression
.params
.iter()
.filter_map(|p| {
if !p.labeled {
return None;
}
let name = &p.identifier.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.errors.iter().map(|e| {
CompilationError::err(
e.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::Semantic(first.into()));
}
if let Some(arg) = &mut args.unlabeled {
if let Some(p) = function_expression.params.iter().find(|p| !p.labeled) {
if let Some(ty) = &p.type_ {
arg.1.value = arg
.1
.value
.coerce(
&RuntimeType::from_parsed(ty.inner.clone(), exec_state, arg.1.source_range)
.map_err(|e| KclError::Semantic(e.into()))?,
exec_state,
)
.map_err(|_| {
KclError::Semantic(KclErrorDetails {
message: format!(
"The input argument of {} requires a value with type `{}`, but found {}",
fn_name
.map(|n| format!("`{}`", n))
.unwrap_or_else(|| "this function".to_owned()),
ty.inner,
arg.1.value.human_friendly_type()
),
source_ranges: vec![arg.1.source_range],
})
})?;
}
}
}
Ok(())
}
fn assign_args_to_params_kw(
fn_name: Option<&str>,
function_expression: NodeRef<'_, FunctionExpression>,
mut args: Args,
exec_state: &mut ExecState,
) -> Result<(), KclError> {
type_check_params_kw(fn_name, function_expression, &mut args.kw_args, exec_state)?;
// Add the arguments to the memory. A new call frame should have already
// been created.
let source_ranges = vec![function_expression.into()];
for param in function_expression.params.iter() {
if param.labeled {
let arg = args.kw_args.labeled.get(&param.identifier.name);
let arg_val = match arg {
Some(arg) => arg.value.clone(),
None => match param.default_value {
Some(ref default_val) => KclValue::from_default_param(default_val.clone(), exec_state),
None => {
return Err(KclError::Semantic(KclErrorDetails {
source_ranges,
message: format!(
"This function requires a parameter {}, but you haven't passed it one.",
param.identifier.name
),
}));
}
},
};
exec_state
.mut_stack()
.add(param.identifier.name.clone(), arg_val, (&param.identifier).into())?;
} else {
let unlabelled = args.unlabeled_kw_arg_unconverted();
let Some(unlabeled) = unlabelled else {
let param_name = &param.identifier.name;
return Err(if args.kw_args.labeled.contains_key(param_name) {
KclError::Semantic(KclErrorDetails {
source_ranges,
message: format!("The function does declare a parameter named '{param_name}', but this parameter doesn't use a label. Try removing the `{param_name}:`"),
})
} else {
KclError::Semantic(KclErrorDetails {
source_ranges,
message: "This function expects an unlabeled first parameter, but you haven't passed it one."
.to_owned(),
})
});
};
exec_state.mut_stack().add(
param.identifier.name.clone(),
unlabeled.value.clone(),
(&param.identifier).into(),
)?;
}
}
Ok(())
}
fn coerce_result_type(
result: Result<Option<KclValue>, KclError>,
function_expression: NodeRef<'_, FunctionExpression>,
exec_state: &mut ExecState,
) -> Result<Option<KclValue>, KclError> {
if let Ok(Some(val)) = result {
if let Some(ret_ty) = &function_expression.return_type {
let ty = RuntimeType::from_parsed(ret_ty.inner.clone(), exec_state, ret_ty.as_source_range())
.map_err(|e| KclError::Semantic(e.into()))?;
let val = val.coerce(&ty, exec_state).map_err(|_| {
KclError::Semantic(KclErrorDetails {
message: format!(
"This function requires its result to be of type `{}`, but found {}",
ty.human_friendly_type(),
val.human_friendly_type(),
),
source_ranges: ret_ty.as_source_ranges(),
})
})?;
Ok(Some(val))
} else {
Ok(Some(val))
}
} else {
result
}
}
async fn call_user_defined_function_kw(
fn_name: Option<&str>,
args: Args,
memory: EnvironmentRef,
function_expression: NodeRef<'_, FunctionExpression>,
exec_state: &mut ExecState,
ctx: &ExecutorContext,
) -> Result<Option<KclValue>, KclError> {
// Create a new environment to execute the function body in so that local
// variables shadow variables in the parent scope. The new environment's
// parent should be the environment of the closure.
exec_state.mut_stack().push_new_env_for_call(memory);
if let Err(e) = assign_args_to_params_kw(fn_name, function_expression, args, exec_state) {
exec_state.mut_stack().pop_env();
return Err(e);
}
// Execute the function body using the memory we just created.
let result = ctx
.exec_block(&function_expression.body, exec_state, BodyType::Block)
.await;
let mut result = result.map(|_| {
exec_state
.stack()
.get(memory::RETURN_NAME, function_expression.as_source_range())
.ok()
.cloned()
});
result = coerce_result_type(result, function_expression, exec_state);
// Restore the previous memory.
exec_state.mut_stack().pop_env();
result
}
impl FunctionSource {
pub async fn call_kw(
&self,
fn_name: Option<String>,
exec_state: &mut ExecState,
ctx: &ExecutorContext,
mut args: Args,
callsite: SourceRange,
) -> Result<Option<KclValue>, KclError> {
match self {
FunctionSource::Std { func, ast, props } => {
if props.deprecated {
exec_state.warn(CompilationError::err(
callsite,
format!(
"`{}` is deprecated, see the docs for a recommended replacement",
props.name
),
));
}
type_check_params_kw(Some(&props.name), ast, &mut args.kw_args, exec_state)?;
if let Some(arg) = &mut args.kw_args.unlabeled {
if let Some(p) = ast.params.iter().find(|p| !p.labeled) {
if let Some(ty) = &p.type_ {
arg.1.value = arg
.1
.value
.coerce(
&RuntimeType::from_parsed(ty.inner.clone(), exec_state, arg.1.source_range)
.map_err(|e| KclError::Semantic(e.into()))?,
exec_state,
)
.map_err(|_| {
KclError::Semantic(KclErrorDetails {
message: format!(
"The input argument of {} requires a value with type `{}`, but found {}",
props.name,
ty.inner,
arg.1.value.human_friendly_type(),
),
source_ranges: vec![callsite],
})
})?;
}
}
}
#[cfg(feature = "artifact-graph")]
let op = if props.include_in_feature_tree {
let op_labeled_args = args
.kw_args
.labeled
.iter()
.map(|(k, arg)| (k.clone(), OpArg::new(OpKclValue::from(&arg.value), arg.source_range)))
.collect();
Some(Operation::KclStdLibCall {
name: fn_name.unwrap_or_default(),
unlabeled_arg: args
.unlabeled_kw_arg_unconverted()
.map(|arg| OpArg::new(OpKclValue::from(&arg.value), arg.source_range)),
labeled_args: op_labeled_args,
source_range: callsite,
is_error: false,
})
} else {
None
};
// Attempt to call the function.
exec_state.mut_stack().push_new_env_for_rust_call();
let mut result = {
// Don't early-return in this block.
let result = func(exec_state, args).await;
exec_state.mut_stack().pop_env();
#[cfg(feature = "artifact-graph")]
if let Some(mut op) = op {
op.set_std_lib_call_is_error(result.is_err());
// Track call operation. We do this after the call
// since things like patternTransform may call user code
// before running, and we will likely want to use the
// return value. The call takes ownership of the args,
// so we need to build the op before the call.
exec_state.global.operations.push(op);
}
result
}?;
update_memory_for_tags_of_geometry(&mut result, exec_state)?;
Ok(Some(result))
}
FunctionSource::User { ast, memory, .. } => {
// Track call operation.
#[cfg(feature = "artifact-graph")]
{
let op_labeled_args = args
.kw_args
.labeled
.iter()
.map(|(k, arg)| (k.clone(), OpArg::new(OpKclValue::from(&arg.value), arg.source_range)))
.collect();
exec_state.global.operations.push(Operation::GroupBegin {
group: Group::FunctionCall {
name: fn_name.clone(),
function_source_range: ast.as_source_range(),
unlabeled_arg: args
.kw_args
.unlabeled
.as_ref()
.map(|arg| OpArg::new(OpKclValue::from(&arg.1.value), arg.1.source_range)),
labeled_args: op_labeled_args,
},
source_range: callsite,
});
}
let result =
call_user_defined_function_kw(fn_name.as_deref(), args, *memory, ast, exec_state, ctx).await;
// Track return operation.
#[cfg(feature = "artifact-graph")]
exec_state.global.operations.push(Operation::GroupEnd);
result
}
FunctionSource::None => unreachable!(),
}
}
}
#[cfg(test)]
mod test {
use std::sync::Arc;
@ -2305,151 +1598,10 @@ mod test {
use super::*;
use crate::{
exec::UnitType,
execution::{memory::Stack, parse_execute, ContextType},
parsing::ast::types::{DefaultParamVal, Identifier, Parameter},
execution::{parse_execute, ContextType},
ExecutorSettings, UnitLen,
};
#[tokio::test(flavor = "multi_thread")]
async fn test_assign_args_to_params() {
// Set up a little framework for this test.
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 {
identifier: ident(s),
type_: None,
default_value: Some(DefaultParamVal::none()),
labeled: true,
digest: None,
}
}
fn req_param(s: &'static str) -> Parameter {
Parameter {
identifier: ident(s),
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
}
// Declare the test cases.
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::Semantic(KclErrorDetails {
source_ranges: vec![SourceRange::default()],
message: "This function requires a parameter x, but you haven't passed it one.".to_owned(),
})),
),
(
"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::Semantic(KclErrorDetails {
source_ranges: vec![SourceRange::default()],
message: "This function requires a parameter x, but you haven't passed it one.".to_owned(),
})),
),
(
"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)),
])),
),
] {
// Run each test.
let func_expr = &Node::no_src(FunctionExpression {
params,
body: Program::empty(),
return_type: None,
digest: None,
});
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(Box::new(
crate::engine::conn_mock::EngineConnection::new().await.unwrap(),
)),
fs: Arc::new(crate::fs::FileManager::new()),
stdlib: Arc::new(crate::std::StdLib::new()),
settings: Default::default(),
context_type: ContextType::Mock,
};
let mut exec_state = ExecState::new(&exec_ctxt);
exec_state.mod_local.stack = Stack::new_for_tests();
let args = Args::new_kw(
KwArgs {
unlabeled: None,
labeled,
errors: Vec::new(),
},
SourceRange::default(),
exec_ctxt,
None,
);
let actual =
assign_args_to_params_kw(None, func_expr, 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 ascription() {
let program = r#"

View File

@ -0,0 +1,979 @@
use async_recursion::async_recursion;
use indexmap::IndexMap;
use crate::execution::cad_op::{Group, OpArg, OpKclValue, Operation};
use crate::{
docs::StdLibFn,
errors::{KclError, KclErrorDetails},
execution::{
kcl_value::FunctionSource, memory, types::RuntimeType, BodyType, ExecState, ExecutorContext, KclValue,
Metadata, StatementKind, TagEngineInfo, TagIdentifier,
},
parsing::ast::types::{CallExpressionKw, DefaultParamVal, FunctionExpression, Node, Program, Type},
source_range::SourceRange,
std::StdFn,
CompilationError,
};
use super::types::ArrayLen;
use super::EnvironmentRef;
#[derive(Debug, Clone)]
pub struct Args {
/// Positional args.
pub args: Vec<Arg>,
/// Keyword arguments
pub kw_args: KwArgs,
pub source_range: SourceRange,
pub ctx: ExecutorContext,
/// If this call happens inside a pipe (|>) expression, this holds the LHS of that |>.
/// Otherwise it's None.
pub pipe_value: Option<Arg>,
}
impl Args {
pub fn new(args: Vec<Arg>, source_range: SourceRange, ctx: ExecutorContext, pipe_value: Option<Arg>) -> Self {
Self {
args,
kw_args: Default::default(),
source_range,
ctx,
pipe_value,
}
}
/// Collect the given keyword arguments.
pub fn new_kw(kw_args: KwArgs, source_range: SourceRange, ctx: ExecutorContext, pipe_value: Option<Arg>) -> Self {
Self {
args: Default::default(),
kw_args,
source_range,
ctx,
pipe_value,
}
}
/// Get the unlabeled keyword argument. If not set, returns None.
pub(crate) fn unlabeled_kw_arg_unconverted(&self) -> Option<&Arg> {
self.kw_args
.unlabeled
.as_ref()
.map(|(_, a)| a)
.or(self.args.first())
.or(self.pipe_value.as_ref())
}
}
#[derive(Debug, Clone)]
pub struct Arg {
/// The evaluated argument.
pub value: KclValue,
/// The source range of the unevaluated argument.
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]
}
}
#[derive(Debug, Clone, Default)]
pub struct KwArgs {
/// Unlabeled keyword args. Currently only the first arg can be unlabeled.
/// If the argument was a local variable, then the first element of the tuple is its name
/// which may be used to treat this arg as a labelled arg.
pub unlabeled: Option<(Option<String>, Arg)>,
/// Labeled args.
pub labeled: IndexMap<String, Arg>,
pub errors: Vec<Arg>,
}
impl KwArgs {
/// How many arguments are there?
pub fn len(&self) -> usize {
self.labeled.len() + if self.unlabeled.is_some() { 1 } else { 0 }
}
/// Are there no arguments?
pub fn is_empty(&self) -> bool {
self.labeled.len() == 0 && self.unlabeled.is_none()
}
}
struct FunctionDefinition<'a> {
input_arg: Option<(String, Option<Type>)>,
named_args: IndexMap<String, (Option<DefaultParamVal>, Option<Type>)>,
return_type: Option<Node<Type>>,
deprecated: bool,
include_in_feature_tree: bool,
is_std: bool,
body: FunctionBody<'a>,
}
#[derive(Debug)]
enum FunctionBody<'a> {
Rust(StdFn),
Kcl(&'a Node<Program>, EnvironmentRef),
}
impl<'a> From<&'a FunctionSource> for FunctionDefinition<'a> {
fn from(value: &'a FunctionSource) -> Self {
#[allow(clippy::type_complexity)]
fn args_from_ast(
ast: &FunctionExpression,
) -> (
Option<(String, Option<Type>)>,
IndexMap<String, (Option<DefaultParamVal>, Option<Type>)>,
) {
let mut input_arg = None;
let mut named_args = IndexMap::new();
for p in &ast.params {
if !p.labeled {
input_arg = Some((p.identifier.name.clone(), p.type_.as_ref().map(|t| t.inner.clone())));
continue;
}
named_args.insert(
p.identifier.name.clone(),
(p.default_value.clone(), p.type_.as_ref().map(|t| t.inner.clone())),
);
}
(input_arg, named_args)
}
match value {
FunctionSource::Std { func, ast, props } => {
let (input_arg, named_args) = args_from_ast(ast);
FunctionDefinition {
input_arg,
named_args,
return_type: ast.return_type.clone(),
deprecated: props.deprecated,
include_in_feature_tree: props.include_in_feature_tree,
is_std: true,
body: FunctionBody::Rust(*func),
}
}
FunctionSource::User { ast, memory, .. } => {
let (input_arg, named_args) = args_from_ast(ast);
FunctionDefinition {
input_arg,
named_args,
return_type: ast.return_type.clone(),
deprecated: false,
include_in_feature_tree: true,
// TODO I think this might be wrong for pure Rust std functions
is_std: false,
body: FunctionBody::Kcl(&ast.body, *memory),
}
}
FunctionSource::None => unreachable!(),
}
}
}
impl From<&dyn StdLibFn> for FunctionDefinition<'static> {
fn from(value: &dyn StdLibFn) -> Self {
let mut input_arg = None;
let mut named_args = IndexMap::new();
for a in value.args(false) {
if !a.label_required {
input_arg = Some((a.name.clone(), None));
continue;
}
named_args.insert(
a.name.clone(),
(
if a.required {
None
} else {
Some(DefaultParamVal::none())
},
None,
),
);
}
FunctionDefinition {
input_arg,
named_args,
return_type: None,
deprecated: value.deprecated(),
include_in_feature_tree: value.feature_tree_operation(),
is_std: true,
body: FunctionBody::Rust(value.std_lib_fn()),
}
}
}
impl Node<CallExpressionKw> {
#[async_recursion]
pub async fn execute(&self, exec_state: &mut ExecState, ctx: &ExecutorContext) -> Result<KclValue, KclError> {
let fn_name = &self.callee;
let callsite: SourceRange = self.into();
// Build a hashmap from argument labels to the final evaluated values.
let mut fn_args = IndexMap::with_capacity(self.arguments.len());
let mut errors = Vec::new();
for arg_expr in &self.arguments {
let source_range = SourceRange::from(arg_expr.arg.clone());
let metadata = Metadata { source_range };
let value = ctx
.execute_expr(&arg_expr.arg, exec_state, &metadata, &[], StatementKind::Expression)
.await?;
let arg = Arg::new(value, source_range);
match &arg_expr.label {
Some(l) => {
fn_args.insert(l.name.clone(), arg);
}
None => {
if let Some(id) = arg_expr.arg.ident_name() {
fn_args.insert(id.to_owned(), arg);
} else {
errors.push(arg);
}
}
}
}
// Evaluate the unlabeled first param, if any exists.
let unlabeled = if let Some(ref arg_expr) = self.unlabeled {
let source_range = SourceRange::from(arg_expr.clone());
let metadata = Metadata { source_range };
let value = ctx
.execute_expr(arg_expr, exec_state, &metadata, &[], StatementKind::Expression)
.await?;
let label = arg_expr.ident_name().map(str::to_owned);
Some((label, Arg::new(value, source_range)))
} else {
None
};
let args = Args::new_kw(
KwArgs {
unlabeled,
labeled: fn_args,
errors,
},
self.into(),
ctx.clone(),
exec_state.pipe_value().map(|v| Arg::new(v.clone(), callsite)),
);
match ctx.stdlib.get_rust_function(fn_name) {
Some(func) => {
let def: FunctionDefinition = (&*func).into();
// All std lib functions return a value, so the unwrap is safe.
def.call_kw(Some(func.name()), exec_state, ctx, args, callsite)
.await
.map(Option::unwrap)
}
None => {
// Clone the function so that we can use a mutable reference to
// exec_state.
let func = fn_name.get_result(exec_state, ctx).await?.clone();
let Some(fn_src) = func.as_fn() else {
return Err(KclError::Semantic(KclErrorDetails {
message: "cannot call this because it isn't a function".to_string(),
source_ranges: vec![callsite],
}));
};
let return_value = fn_src
.call_kw(Some(fn_name.to_string()), exec_state, ctx, args, callsite)
.await
.map_err(|e| {
// Add the call expression to the source ranges.
e.add_source_ranges(vec![callsite])
})?;
let result = return_value.ok_or_else(move || {
let mut source_ranges: Vec<SourceRange> = vec![callsite];
// We want to send the source range of the original function.
if let KclValue::Function { meta, .. } = func {
source_ranges = meta.iter().map(|m| m.source_range).collect();
};
KclError::UndefinedValue(KclErrorDetails {
message: format!("Result of user-defined function {} is undefined", fn_name),
source_ranges,
})
})?;
Ok(result)
}
}
}
}
impl FunctionDefinition<'_> {
pub async fn call_kw(
&self,
fn_name: Option<String>,
exec_state: &mut ExecState,
ctx: &ExecutorContext,
mut args: Args,
callsite: SourceRange,
) -> Result<Option<KclValue>, KclError> {
if self.deprecated {
exec_state.warn(CompilationError::err(
callsite,
format!(
"{} is deprecated, see the docs for a recommended replacement",
match &fn_name {
Some(n) => format!("`{n}`"),
None => "This function".to_owned(),
}
),
));
}
type_check_params_kw(fn_name.as_deref(), self, &mut args.kw_args, exec_state)?;
// Don't early return until the stack frame is popped!
self.body.prep_mem(exec_state);
let op = if self.include_in_feature_tree {
let op_labeled_args = args
.kw_args
.labeled
.iter()
.map(|(k, arg)| (k.clone(), OpArg::new(OpKclValue::from(&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(OpKclValue::from(&arg.value), arg.source_range)),
labeled_args: op_labeled_args,
source_range: callsite,
is_error: false,
})
} else {
exec_state.push_op(Operation::GroupBegin {
group: Group::FunctionCall {
name: fn_name.clone(),
function_source_range: self.as_source_range().unwrap(),
unlabeled_arg: args
.kw_args
.unlabeled
.as_ref()
.map(|arg| OpArg::new(OpKclValue::from(&arg.1.value), arg.1.source_range)),
labeled_args: op_labeled_args,
},
source_range: callsite,
});
None
}
} else {
None
};
let mut result = match &self.body {
FunctionBody::Rust(f) => f(exec_state, args).await.map(Some),
FunctionBody::Kcl(f, _) => {
if let Err(e) = assign_args_to_params_kw(self, args, exec_state) {
exec_state.mut_stack().pop_env();
return Err(e);
}
ctx.exec_block(f, exec_state, BodyType::Block).await.map(|_| {
exec_state
.stack()
.get(memory::RETURN_NAME, f.as_source_range())
.ok()
.cloned()
})
}
};
exec_state.mut_stack().pop_env();
if let Some(mut op) = op {
op.set_std_lib_call_is_error(result.is_err());
// Track call operation. We do this after the call
// since things like patternTransform may call user code
// before running, and we will likely want to use the
// return value. The call takes ownership of the args,
// so we need to build the op before the call.
exec_state.push_op(op);
} else if !self.is_std {
exec_state.push_op(Operation::GroupEnd);
}
if self.is_std {
if let Ok(Some(result)) = &mut result {
update_memory_for_tags_of_geometry(result, exec_state)?;
}
}
coerce_result_type(result, self, exec_state)
}
// Postcondition: result.is_some() if function is not in the standard library.
fn as_source_range(&self) -> Option<SourceRange> {
match &self.body {
FunctionBody::Rust(_) => None,
FunctionBody::Kcl(p, _) => Some(p.as_source_range()),
}
}
}
impl FunctionBody<'_> {
fn prep_mem(&self, exec_state: &mut ExecState) {
match self {
FunctionBody::Rust(_) => exec_state.mut_stack().push_new_env_for_rust_call(),
FunctionBody::Kcl(_, memory) => exec_state.mut_stack().push_new_env_for_call(*memory),
}
}
}
impl FunctionSource {
pub async fn call_kw(
&self,
fn_name: Option<String>,
exec_state: &mut ExecState,
ctx: &ExecutorContext,
args: Args,
callsite: SourceRange,
) -> Result<Option<KclValue>, KclError> {
let def: FunctionDefinition = self.into();
def.call_kw(fn_name, exec_state, ctx, args, callsite).await
}
}
fn update_memory_for_tags_of_geometry(result: &mut KclValue, exec_state: &mut ExecState) -> Result<(), KclError> {
// If the return result is a sketch or solid, we want to update the
// memory for the tags of the group.
// TODO: This could probably be done in a better way, but as of now this was my only idea
// and it works.
match result {
KclValue::Sketch { value } => {
for (name, tag) in value.tags.iter() {
if exec_state.stack().cur_frame_contains(name) {
exec_state.mut_stack().update(name, |v, _| {
v.as_mut_tag().unwrap().merge_info(tag);
});
} else {
exec_state
.mut_stack()
.add(
name.to_owned(),
KclValue::TagIdentifier(Box::new(tag.clone())),
SourceRange::default(),
)
.unwrap();
}
}
}
KclValue::Solid { ref mut value } => {
for v in &value.value {
if let Some(tag) = v.get_tag() {
// Get the past tag and update it.
let tag_id = if let Some(t) = value.sketch.tags.get(&tag.name) {
let mut t = t.clone();
let Some(info) = t.get_cur_info() else {
return Err(KclError::Internal(KclErrorDetails {
message: format!("Tag {} does not have path info", tag.name),
source_ranges: vec![tag.into()],
}));
};
let mut info = info.clone();
info.surface = Some(v.clone());
info.sketch = value.id;
t.info.push((exec_state.stack().current_epoch(), info));
t
} else {
// It's probably a fillet or a chamfer.
// Initialize it.
TagIdentifier {
value: tag.name.clone(),
info: vec![(
exec_state.stack().current_epoch(),
TagEngineInfo {
id: v.get_id(),
surface: Some(v.clone()),
path: None,
sketch: value.id,
},
)],
meta: vec![Metadata {
source_range: tag.clone().into(),
}],
}
};
// update the sketch tags.
value.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, _| {
v.as_mut_tag().unwrap().merge_info(&tag_id);
});
} else {
exec_state
.mut_stack()
.add(
tag.name.clone(),
KclValue::TagIdentifier(Box::new(tag_id)),
SourceRange::default(),
)
.unwrap();
}
}
}
// Find the stale sketch in memory and update it.
if !value.sketch.tags.is_empty() {
let sketches_to_update: Vec<_> = exec_state
.stack()
.find_keys_in_current_env(|v| match v {
KclValue::Sketch { value: sk } => sk.original_id == value.sketch.original_id,
_ => false,
})
.cloned()
.collect();
for k in sketches_to_update {
exec_state.mut_stack().update(&k, |v, _| {
let sketch = v.as_mut_sketch().unwrap();
sketch.merge_tags(value.sketch.tags.values());
});
}
}
}
KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
for v in value {
update_memory_for_tags_of_geometry(v, exec_state)?;
}
}
_ => {}
}
Ok(())
}
fn type_check_params_kw(
fn_name: Option<&str>,
fn_def: &FunctionDefinition<'_>,
args: &mut KwArgs,
exec_state: &mut ExecState,
) -> Result<(), KclError> {
// If it's possible the input arg was meant to be labelled and we probably don't want to use
// it as the input arg, then treat it as labelled.
if let Some((Some(label), _)) = &args.unlabeled {
if (fn_def.input_arg.is_none() || exec_state.pipe_value().is_some())
&& fn_def.named_args.iter().any(|p| p.0 == label)
&& !args.labeled.contains_key(label)
{
let (label, arg) = args.unlabeled.take().unwrap();
args.labeled.insert(label.unwrap(), arg);
}
}
for (label, arg) in &mut args.labeled {
match fn_def.named_args.get(label) {
Some((_, ty)) => {
if let Some(ty) = ty {
arg.value = arg
.value
.coerce(
&RuntimeType::from_parsed(ty.clone(), exec_state, arg.source_range).map_err(|e| KclError::Semantic(e.into()))?,
exec_state,
)
.map_err(|e| {
let mut message = format!(
"{label} requires a value with type `{}`, but found {}",
ty,
arg.value.human_friendly_type(),
);
if let Some(ty) = e.explicit_coercion {
// TODO if we have access to the AST for the argument we could choose which example to suggest.
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(): number({ty})`");
}
KclError::Semantic(KclErrorDetails {
message,
source_ranges: vec![arg.source_range],
})
})?;
}
}
None => {
exec_state.err(CompilationError::err(
arg.source_range,
format!(
"`{label}` is not an argument of {}",
fn_name
.map(|n| format!("`{}`", n))
.unwrap_or_else(|| "this function".to_owned()),
),
));
}
}
}
if !args.errors.is_empty() {
let actuals = args.labeled.keys();
let formals: Vec<_> = fn_def
.named_args
.keys()
.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.errors.iter().map(|e| {
CompilationError::err(
e.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::Semantic(first.into()));
}
if let Some(arg) = &mut args.unlabeled {
if let Some((_, Some(ty))) = &fn_def.input_arg {
arg.1.value = arg
.1
.value
.coerce(
&RuntimeType::from_parsed(ty.clone(), exec_state, arg.1.source_range)
.map_err(|e| KclError::Semantic(e.into()))?,
exec_state,
)
.map_err(|_| {
KclError::Semantic(KclErrorDetails {
message: format!(
"The input argument of {} requires a value with type `{}`, but found {}",
fn_name
.map(|n| format!("`{}`", n))
.unwrap_or_else(|| "this function".to_owned()),
ty,
arg.1.value.human_friendly_type()
),
source_ranges: vec![arg.1.source_range],
})
})?;
}
} else if let Some((name, _)) = &fn_def.input_arg {
if let Some(arg) = args.labeled.get(name) {
exec_state.err(CompilationError::err(
arg.source_range,
format!(
"{} expects an unlabeled first parameter (`@{name}`), but it is labelled in the call",
fn_name
.map(|n| format!("The function `{}`", n))
.unwrap_or_else(|| "This function".to_owned()),
),
));
}
}
Ok(())
}
fn assign_args_to_params_kw(
fn_def: &FunctionDefinition<'_>,
args: Args,
exec_state: &mut ExecState,
) -> Result<(), KclError> {
// Add the arguments to the memory. A new call frame should have already
// been created.
let source_ranges = fn_def.as_source_range().into_iter().collect();
for (name, (default, _)) in fn_def.named_args.iter() {
let arg = args.kw_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 default {
Some(ref 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::Semantic(KclErrorDetails {
source_ranges,
message: format!(
"This function requires a parameter {}, but you haven't passed it one.",
name
),
}));
}
},
}
}
if let Some((param_name, _)) = &fn_def.input_arg {
let unlabelled = args.unlabeled_kw_arg_unconverted();
let Some(unlabeled) = unlabelled else {
return Err(if args.kw_args.labeled.contains_key(param_name) {
KclError::Semantic(KclErrorDetails {
source_ranges,
message: format!("The function does declare a parameter named '{param_name}', but this parameter doesn't use a label. Try removing the `{param_name}:`"),
})
} else {
KclError::Semantic(KclErrorDetails {
source_ranges,
message: "This function expects an unlabeled first parameter, but you haven't passed it one."
.to_owned(),
})
});
};
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: &FunctionDefinition<'_>,
exec_state: &mut ExecState,
) -> Result<Option<KclValue>, KclError> {
if let Ok(Some(val)) = result {
if let Some(ret_ty) = &fn_def.return_type {
let mut ty = RuntimeType::from_parsed(ret_ty.inner.clone(), exec_state, ret_ty.as_source_range())
.map_err(|e| KclError::Semantic(e.into()))?;
// Treat `[T; 1+]` as `T | [T; 1+]` (which can't yet be expressed in our syntax of types).
// This is a very specific hack which exists because some std functions can produce arrays
// but usually only make a singleton and the frontend expects the singleton.
// If we can make the frontend work on arrays (or at least arrays of length 1), then this
// can be removed.
// I believe this is safe, since anywhere which requires an array should coerce the singleton
// to an array and we only do this hack for return values.
if let RuntimeType::Array(inner, ArrayLen::NonEmpty) = &ty {
ty = RuntimeType::Union(vec![(**inner).clone(), ty]);
}
let val = val.coerce(&ty, exec_state).map_err(|_| {
KclError::Semantic(KclErrorDetails {
message: format!(
"This function requires its result to be of type `{}`, but found {}",
ty.human_friendly_type(),
val.human_friendly_type(),
),
source_ranges: ret_ty.as_source_ranges(),
})
})?;
Ok(Some(val))
} else {
Ok(Some(val))
}
} else {
result
}
}
#[cfg(test)]
mod test {
use std::sync::Arc;
use super::*;
use crate::{
execution::{memory::Stack, parse_execute, types::NumericType, ContextType},
parsing::ast::types::{DefaultParamVal, Identifier, Parameter},
};
#[tokio::test(flavor = "multi_thread")]
async fn test_assign_args_to_params() {
// Set up a little framework for this test.
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 {
identifier: ident(s),
type_: None,
default_value: Some(DefaultParamVal::none()),
labeled: true,
digest: None,
}
}
fn req_param(s: &'static str) -> Parameter {
Parameter {
identifier: ident(s),
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
}
// Declare the test cases.
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::Semantic(KclErrorDetails {
source_ranges: vec![SourceRange::default()],
message: "This function requires a parameter x, but you haven't passed it one.".to_owned(),
})),
),
(
"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::Semantic(KclErrorDetails {
source_ranges: vec![SourceRange::default()],
message: "This function requires a parameter x, but you haven't passed it one.".to_owned(),
})),
),
(
"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)),
])),
),
] {
// Run each test.
let func_expr = Node::no_src(FunctionExpression {
params,
body: Program::empty(),
return_type: None,
digest: None,
});
let func_src = FunctionSource::User {
ast: Box::new(func_expr),
settings: Default::default(),
memory: EnvironmentRef::dummy(),
};
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(Box::new(
crate::engine::conn_mock::EngineConnection::new().await.unwrap(),
)),
fs: Arc::new(crate::fs::FileManager::new()),
stdlib: Arc::new(crate::std::StdLib::new()),
settings: Default::default(),
context_type: ContextType::Mock,
};
let mut exec_state = ExecState::new(&exec_ctxt);
exec_state.mod_local.stack = Stack::new_for_tests();
let args = Args::new_kw(
KwArgs {
unlabeled: None,
labeled,
errors: Vec::new(),
},
SourceRange::default(),
exec_ctxt,
None,
);
let actual = assign_args_to_params_kw(&(&func_src).into(), 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 number(default units)"
)
}
}

View File

@ -8,12 +8,12 @@ use parse_display::{Display, FromStr};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[cfg(feature = "artifact-graph")]
use crate::execution::ArtifactId;
use crate::{
engine::{PlaneName, DEFAULT_PLANE_INFO},
errors::{KclError, KclErrorDetails},
execution::{types::NumericType, ExecState, ExecutorContext, Metadata, TagEngineInfo, TagIdentifier, UnitLen},
execution::{
types::NumericType, ArtifactId, ExecState, ExecutorContext, Metadata, TagEngineInfo, TagIdentifier, UnitLen,
},
parsing::ast::types::{Node, NodeRef, TagDeclarator, TagNode},
std::{args::TyF64, sketch::PlaneData},
};
@ -256,7 +256,6 @@ pub struct Helix {
/// The id of the helix.
pub value: uuid::Uuid,
/// The artifact ID.
#[cfg(feature = "artifact-graph")]
pub artifact_id: ArtifactId,
/// Number of revolutions.
pub revolutions: f64,
@ -278,7 +277,6 @@ pub struct Plane {
/// The id of the plane.
pub id: uuid::Uuid,
/// The artifact ID.
#[cfg(feature = "artifact-graph")]
pub artifact_id: ArtifactId,
// The code for the plane either a string or custom.
pub value: PlaneType,
@ -508,7 +506,6 @@ impl Plane {
let id = exec_state.next_uuid();
Ok(Plane {
id,
#[cfg(feature = "artifact-graph")]
artifact_id: id.into(),
info: PlaneInfo::try_from(value.clone())?,
value: value.into(),
@ -530,7 +527,6 @@ pub struct Face {
/// The id of the face.
pub id: uuid::Uuid,
/// The artifact ID.
#[cfg(feature = "artifact-graph")]
pub artifact_id: ArtifactId,
/// The tag of the face.
pub value: String,
@ -584,7 +580,6 @@ pub struct Sketch {
pub tags: IndexMap<String, TagIdentifier>,
/// The original id of the sketch. This stays the same even if the sketch is
/// is sketched on face etc.
#[cfg(feature = "artifact-graph")]
pub artifact_id: ArtifactId,
#[ts(skip)]
pub original_id: uuid::Uuid,
@ -748,7 +743,6 @@ pub struct Solid {
/// The id of the solid.
pub id: uuid::Uuid,
/// The artifact ID of the solid. Unlike `id`, this doesn't change.
#[cfg(feature = "artifact-graph")]
pub artifact_id: ArtifactId,
/// The extrude surfaces.
pub value: Vec<ExtrudeSurface>,

View File

@ -352,8 +352,8 @@ impl KclValue {
pub(crate) fn from_default_param(param: DefaultParamVal, exec_state: &mut ExecState) -> Self {
match param {
DefaultParamVal::Literal(lit) => Self::from_literal(lit, exec_state),
DefaultParamVal::KclNone(none) => KclValue::KclNone {
value: none,
DefaultParamVal::KclNone(value) => KclValue::KclNone {
value,
meta: Default::default(),
},
}

View File

@ -820,7 +820,7 @@ impl PartialEq for Stack {
pub struct EnvironmentRef(usize, usize);
impl EnvironmentRef {
fn dummy() -> Self {
pub fn dummy() -> Self {
Self(usize::MAX, 0)
}

View File

@ -4,9 +4,7 @@ use std::sync::Arc;
use anyhow::Result;
#[cfg(feature = "artifact-graph")]
pub use artifact::{
Artifact, ArtifactCommand, ArtifactGraph, ArtifactId, CodeRef, StartSketchOnFace, StartSketchOnPlane,
};
pub use artifact::{Artifact, ArtifactCommand, ArtifactGraph, CodeRef, StartSketchOnFace, StartSketchOnPlane};
use cache::OldAstState;
pub use cache::{bust_cache, clear_mem_cache};
#[cfg(feature = "artifact-graph")]
@ -22,11 +20,12 @@ use kcmc::{
websocket::{ModelingSessionData, OkWebSocketResponseData},
ImageFormat, ModelingCmd,
};
use kittycad_modeling_cmds as kcmc;
use kittycad_modeling_cmds::{self as kcmc, id::ModelingCmdId};
pub use memory::EnvironmentRef;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
pub use state::{ExecState, MetaSettings};
use uuid::Uuid;
#[cfg(feature = "artifact-graph")]
use crate::execution::artifact::build_artifact_graph;
@ -51,9 +50,9 @@ pub(crate) mod annotations;
#[cfg(feature = "artifact-graph")]
mod artifact;
pub(crate) mod cache;
#[cfg(feature = "artifact-graph")]
mod cad_op;
mod exec_ast;
pub mod fn_call;
mod geometry;
mod id_generator;
mod import;
@ -63,6 +62,11 @@ mod state;
pub mod typed_path;
pub(crate) mod types;
enum StatementKind<'a> {
Declaration { name: &'a str },
Expression,
}
/// Outcome of executing a program. This is used in TS.
#[derive(Debug, Clone, Serialize, ts_rs::TS, PartialEq)]
#[ts(export)]
@ -1324,6 +1328,51 @@ impl ExecutorContext {
}
}
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, Ord, PartialOrd, Hash, ts_rs::TS, JsonSchema)]
pub struct ArtifactId(Uuid);
impl ArtifactId {
pub fn new(uuid: Uuid) -> Self {
Self(uuid)
}
}
impl From<Uuid> for ArtifactId {
fn from(uuid: Uuid) -> Self {
Self::new(uuid)
}
}
impl From<&Uuid> for ArtifactId {
fn from(uuid: &Uuid) -> Self {
Self::new(*uuid)
}
}
impl From<ArtifactId> for Uuid {
fn from(id: ArtifactId) -> Self {
id.0
}
}
impl From<&ArtifactId> for Uuid {
fn from(id: &ArtifactId) -> Self {
id.0
}
}
impl From<ModelingCmdId> for ArtifactId {
fn from(id: ModelingCmdId) -> Self {
Self::new(*id.as_ref())
}
}
impl From<&ModelingCmdId> for ArtifactId {
fn from(id: &ModelingCmdId) -> Self {
Self::new(*id.as_ref())
}
}
#[cfg(test)]
pub(crate) async fn parse_execute(code: &str) -> Result<ExecTestResults, KclError> {
parse_execute_with_project_dir(code, None).await

View File

@ -9,11 +9,12 @@ use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[cfg(feature = "artifact-graph")]
use crate::execution::{Artifact, ArtifactCommand, ArtifactGraph, ArtifactId, Operation};
use crate::execution::{Artifact, ArtifactCommand, ArtifactGraph, ArtifactId};
use crate::{
errors::{KclError, KclErrorDetails, Severity},
execution::{
annotations,
cad_op::Operation,
id_generator::IdGenerator,
memory::{ProgramMemory, Stack},
types,
@ -201,6 +202,13 @@ impl ExecState {
self.global.artifacts.insert(id, artifact);
}
pub(crate) fn push_op(&mut self, op: Operation) {
#[cfg(feature = "artifact-graph")]
self.global.operations.push(op);
#[cfg(not(feature = "artifact-graph"))]
drop(op);
}
pub(super) fn next_module_id(&self) -> ModuleId {
ModuleId::from_usize(self.global.path_to_source_id.len())
}

View File

@ -1112,7 +1112,6 @@ impl KclValue {
let id = exec_state.mod_local.id_generator.next_uuid();
let plane = Plane {
id,
#[cfg(feature = "artifact-graph")]
artifact_id: id.into(),
info: PlaneInfo {
origin,