Fix the KCL any type and array coercion incorrectly nesting (#6816)
* Add sim test for any type * Fix doc comments to match code * Add array ascription tests * Commit new test output * Fix to not panic when type is undefined * Fix to not panic on use of the any type * Update test and generated output * Fix error message after rebase * Fix subtype of any * Fix KCL to use new keyword args * Fix to not nest MixedArray in HomArray * Update output * Remove all creation of MixedArray and use HomArray instead * Rename MixedArray to Tuple * Fix to coerce arrays the way tuples are done * Restructure to appease the type signature extraction * Fix TS unit test * Update output after switch to HomArray * Update docs * Fix to remove edge case when creating points * Update docs with broken point signature * Fix display of tuples to not collide with arrays * Change push to an array with type mismatch to be an error * Add sim test for push type error * Fix acription to more general array element type * Fix to coerce point types * Change array push to not error when item type differs * Fix coercion tests * Change to only flatten as a last resort and remove flattening tuples * Contort code to appease doc generation * Update docs * Fix coerce axes * Fix flattening test to test arrays instead of tuples * Remove special subtype case for singleton coercion
This commit is contained in:
@ -278,7 +278,7 @@ impl From<&KclValue> for OpKclValue {
|
||||
ty: ty.clone(),
|
||||
},
|
||||
KclValue::String { value, .. } => Self::String { value: value.clone() },
|
||||
KclValue::MixedArray { value, .. } | KclValue::HomArray { value, .. } => {
|
||||
KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
|
||||
let value = value.iter().map(Self::from).collect();
|
||||
Self::Array { value }
|
||||
}
|
||||
|
@ -876,11 +876,7 @@ impl Node<MemberExpression> {
|
||||
source_ranges: vec![self.clone().into()],
|
||||
}))
|
||||
}
|
||||
(
|
||||
KclValue::MixedArray { value: arr, .. } | KclValue::HomArray { value: arr, .. },
|
||||
Property::UInt(index),
|
||||
_,
|
||||
) => {
|
||||
(KclValue::HomArray { value: arr, .. }, Property::UInt(index), _) => {
|
||||
let value_of_arr = arr.get(index);
|
||||
if let Some(value) = value_of_arr {
|
||||
Ok(value.to_owned())
|
||||
@ -891,7 +887,7 @@ impl Node<MemberExpression> {
|
||||
}))
|
||||
}
|
||||
}
|
||||
(KclValue::MixedArray { .. } | KclValue::HomArray { .. }, p, _) => {
|
||||
(KclValue::HomArray { .. }, p, _) => {
|
||||
let t = p.type_name();
|
||||
let article = article_for(t);
|
||||
Err(KclError::Semantic(KclErrorDetails {
|
||||
@ -1179,7 +1175,7 @@ impl Node<UnaryExpression> {
|
||||
};
|
||||
|
||||
let direction = match direction {
|
||||
KclValue::MixedArray { value: values, meta } => {
|
||||
KclValue::Tuple { value: values, meta } => {
|
||||
let values = values
|
||||
.iter()
|
||||
.map(|v| match v {
|
||||
@ -1192,7 +1188,7 @@ impl Node<UnaryExpression> {
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
KclValue::MixedArray {
|
||||
KclValue::Tuple {
|
||||
value: values,
|
||||
meta: meta.clone(),
|
||||
}
|
||||
@ -1560,7 +1556,7 @@ fn update_memory_for_tags_of_geometry(result: &mut KclValue, exec_state: &mut Ex
|
||||
}
|
||||
}
|
||||
}
|
||||
KclValue::MixedArray { value, .. } | KclValue::HomArray { value, .. } => {
|
||||
KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
|
||||
for v in value {
|
||||
update_memory_for_tags_of_geometry(v, exec_state)?;
|
||||
}
|
||||
@ -1604,9 +1600,9 @@ impl Node<ArrayExpression> {
|
||||
results.push(value);
|
||||
}
|
||||
|
||||
Ok(KclValue::MixedArray {
|
||||
Ok(KclValue::HomArray {
|
||||
value: results,
|
||||
meta: vec![self.into()],
|
||||
ty: RuntimeType::Primitive(PrimitiveType::Any),
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -1653,7 +1649,8 @@ impl Node<ArrayRangeExpression> {
|
||||
let meta = vec![Metadata {
|
||||
source_range: self.into(),
|
||||
}];
|
||||
Ok(KclValue::MixedArray {
|
||||
|
||||
Ok(KclValue::HomArray {
|
||||
value: range
|
||||
.into_iter()
|
||||
.map(|num| KclValue::Number {
|
||||
@ -1662,7 +1659,7 @@ impl Node<ArrayRangeExpression> {
|
||||
meta: meta.clone(),
|
||||
})
|
||||
.collect(),
|
||||
meta,
|
||||
ty: RuntimeType::Primitive(PrimitiveType::Number(NumericType::count())),
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -1877,7 +1874,7 @@ fn type_check_params_kw(
|
||||
arg.value = arg
|
||||
.value
|
||||
.coerce(
|
||||
&RuntimeType::from_parsed(ty.inner.clone(), exec_state, arg.source_range).unwrap(),
|
||||
&RuntimeType::from_parsed(ty.inner.clone(), exec_state, arg.source_range).map_err(|e| KclError::Semantic(e.into()))?,
|
||||
exec_state,
|
||||
)
|
||||
.map_err(|e| {
|
||||
@ -1955,7 +1952,8 @@ fn type_check_params_kw(
|
||||
arg.value = arg
|
||||
.value
|
||||
.coerce(
|
||||
&RuntimeType::from_parsed(ty.inner.clone(), exec_state, arg.source_range).unwrap(),
|
||||
&RuntimeType::from_parsed(ty.inner.clone(), exec_state, arg.source_range)
|
||||
.map_err(|e| KclError::Semantic(e.into()))?,
|
||||
exec_state,
|
||||
)
|
||||
.map_err(|_| {
|
||||
@ -2134,7 +2132,8 @@ impl FunctionSource {
|
||||
arg.value = arg
|
||||
.value
|
||||
.coerce(
|
||||
&RuntimeType::from_parsed(ty.inner.clone(), exec_state, arg.source_range).unwrap(),
|
||||
&RuntimeType::from_parsed(ty.inner.clone(), exec_state, arg.source_range)
|
||||
.map_err(|e| KclError::Semantic(e.into()))?,
|
||||
exec_state,
|
||||
)
|
||||
.map_err(|_| {
|
||||
@ -2244,9 +2243,10 @@ mod test {
|
||||
|
||||
use super::*;
|
||||
use crate::{
|
||||
exec::UnitType,
|
||||
execution::{memory::Stack, parse_execute, ContextType},
|
||||
parsing::ast::types::{DefaultParamVal, Identifier, Parameter},
|
||||
ExecutorSettings,
|
||||
ExecutorSettings, UnitLen,
|
||||
};
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@ -2400,6 +2400,7 @@ p = {
|
||||
yAxis = { x = 0, y = 1, z = 0 },
|
||||
zAxis = { x = 0, y = 0, z = 1 }
|
||||
}: Plane
|
||||
arr1 = [42]: [number(cm)]
|
||||
"#;
|
||||
|
||||
let result = parse_execute(program).await.unwrap();
|
||||
@ -2410,6 +2411,24 @@ p = {
|
||||
.unwrap(),
|
||||
KclValue::Plane { .. }
|
||||
));
|
||||
let arr1 = mem
|
||||
.memory
|
||||
.get_from("arr1", result.mem_env, SourceRange::default(), 0)
|
||||
.unwrap();
|
||||
if let KclValue::HomArray { value, ty } = arr1 {
|
||||
assert_eq!(value.len(), 1, "Expected Vec with specific length: found {:?}", value);
|
||||
assert_eq!(*ty, RuntimeType::known_length(UnitLen::Cm));
|
||||
// Compare, ignoring meta.
|
||||
if let KclValue::Number { value, ty, .. } = &value[0] {
|
||||
// Converted from mm to cm.
|
||||
assert_eq!(*value, 4.2);
|
||||
assert_eq!(*ty, NumericType::Known(UnitType::Length(UnitLen::Cm)));
|
||||
} else {
|
||||
panic!("Expected a number; found {:?}", value[0]);
|
||||
}
|
||||
} else {
|
||||
panic!("Expected HomArray; found {arr1:?}");
|
||||
}
|
||||
|
||||
let program = r#"
|
||||
a = 42: string
|
||||
@ -2428,6 +2447,28 @@ a = 42: Plane
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("could not coerce number value to type Plane"));
|
||||
|
||||
let program = r#"
|
||||
arr = [0]: [string]
|
||||
"#;
|
||||
let result = parse_execute(program).await;
|
||||
let err = result.unwrap_err();
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("could not coerce array (list) value to type [string]"),
|
||||
"Expected error but found {err:?}"
|
||||
);
|
||||
|
||||
let program = r#"
|
||||
mixedArr = [0, "a"]: [number(mm)]
|
||||
"#;
|
||||
let result = parse_execute(program).await;
|
||||
let err = result.unwrap_err();
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("could not coerce array (list) value to type [number(mm)]"),
|
||||
"Expected error but found {err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
|
@ -1239,6 +1239,20 @@ impl Path {
|
||||
[TyF64::new(p[0], ty.clone()), TyF64::new(p[1], ty)]
|
||||
}
|
||||
|
||||
/// The path segment start point and its type.
|
||||
pub fn start_point_components(&self) -> ([f64; 2], NumericType) {
|
||||
let p = &self.get_base().from;
|
||||
let ty: NumericType = self.get_base().units.into();
|
||||
(*p, ty)
|
||||
}
|
||||
|
||||
/// The path segment end point and its type.
|
||||
pub fn end_point_components(&self) -> ([f64; 2], NumericType) {
|
||||
let p = &self.get_base().to;
|
||||
let ty: NumericType = self.get_base().units.into();
|
||||
(*p, ty)
|
||||
}
|
||||
|
||||
/// Length of this path segment, in cartesian plane.
|
||||
pub fn length(&self) -> TyF64 {
|
||||
let n = match self {
|
||||
|
@ -48,7 +48,7 @@ pub enum KclValue {
|
||||
#[serde(skip)]
|
||||
meta: Vec<Metadata>,
|
||||
},
|
||||
MixedArray {
|
||||
Tuple {
|
||||
value: Vec<KclValue>,
|
||||
#[serde(skip)]
|
||||
meta: Vec<Metadata>,
|
||||
@ -197,7 +197,7 @@ impl From<KclValue> for Vec<SourceRange> {
|
||||
KclValue::Bool { meta, .. } => to_vec_sr(&meta),
|
||||
KclValue::Number { meta, .. } => to_vec_sr(&meta),
|
||||
KclValue::String { meta, .. } => to_vec_sr(&meta),
|
||||
KclValue::MixedArray { meta, .. } => to_vec_sr(&meta),
|
||||
KclValue::Tuple { meta, .. } => to_vec_sr(&meta),
|
||||
KclValue::HomArray { value, .. } => value.iter().flat_map(Into::<Vec<SourceRange>>::into).collect(),
|
||||
KclValue::Object { meta, .. } => to_vec_sr(&meta),
|
||||
KclValue::Module { meta, .. } => to_vec_sr(&meta),
|
||||
@ -228,7 +228,7 @@ impl From<&KclValue> for Vec<SourceRange> {
|
||||
KclValue::Number { meta, .. } => to_vec_sr(meta),
|
||||
KclValue::String { meta, .. } => to_vec_sr(meta),
|
||||
KclValue::Uuid { meta, .. } => to_vec_sr(meta),
|
||||
KclValue::MixedArray { meta, .. } => to_vec_sr(meta),
|
||||
KclValue::Tuple { meta, .. } => to_vec_sr(meta),
|
||||
KclValue::HomArray { value, .. } => value.iter().flat_map(Into::<Vec<SourceRange>>::into).collect(),
|
||||
KclValue::Object { meta, .. } => to_vec_sr(meta),
|
||||
KclValue::Module { meta, .. } => to_vec_sr(meta),
|
||||
@ -252,7 +252,7 @@ impl KclValue {
|
||||
KclValue::Bool { value: _, meta } => meta.clone(),
|
||||
KclValue::Number { meta, .. } => meta.clone(),
|
||||
KclValue::String { value: _, meta } => meta.clone(),
|
||||
KclValue::MixedArray { value: _, meta } => meta.clone(),
|
||||
KclValue::Tuple { value: _, meta } => meta.clone(),
|
||||
KclValue::HomArray { value, .. } => value.iter().flat_map(|v| v.metadata()).collect(),
|
||||
KclValue::Object { value: _, meta } => meta.clone(),
|
||||
KclValue::TagIdentifier(x) => x.meta.clone(),
|
||||
@ -307,7 +307,7 @@ impl KclValue {
|
||||
} => "number(Angle)",
|
||||
KclValue::Number { .. } => "number",
|
||||
KclValue::String { .. } => "string (text)",
|
||||
KclValue::MixedArray { .. } => "mixed array (list)",
|
||||
KclValue::Tuple { .. } => "tuple (list)",
|
||||
KclValue::HomArray { .. } => "array (list)",
|
||||
KclValue::Object { .. } => "object",
|
||||
KclValue::Module { .. } => "module",
|
||||
@ -373,7 +373,7 @@ impl KclValue {
|
||||
|
||||
/// Put the point into a KCL value.
|
||||
pub fn from_point2d(p: [f64; 2], ty: NumericType, meta: Vec<Metadata>) -> Self {
|
||||
Self::MixedArray {
|
||||
Self::Tuple {
|
||||
value: vec![
|
||||
Self::Number {
|
||||
value: p[0],
|
||||
@ -430,7 +430,7 @@ impl KclValue {
|
||||
|
||||
pub fn as_array(&self) -> Option<&[KclValue]> {
|
||||
match self {
|
||||
KclValue::MixedArray { value, .. } | KclValue::HomArray { value, .. } => Some(value),
|
||||
KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => Some(value),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@ -602,7 +602,7 @@ impl KclValue {
|
||||
KclValue::TagDeclarator(tag) => Some(format!("${}", tag.name)),
|
||||
KclValue::TagIdentifier(tag) => Some(format!("${}", tag.value)),
|
||||
// TODO better Array and Object stringification
|
||||
KclValue::MixedArray { .. } => Some("[...]".to_owned()),
|
||||
KclValue::Tuple { .. } => Some("[...]".to_owned()),
|
||||
KclValue::HomArray { .. } => Some("[...]".to_owned()),
|
||||
KclValue::Object { .. } => Some("{ ... }".to_owned()),
|
||||
KclValue::Module { .. }
|
||||
|
@ -1932,7 +1932,7 @@ a = []
|
||||
notArray = !a";
|
||||
assert_eq!(
|
||||
parse_execute(code5).await.unwrap_err().message(),
|
||||
"Cannot apply unary operator ! to non-boolean value: mixed array (list)",
|
||||
"Cannot apply unary operator ! to non-boolean value: array (list)",
|
||||
);
|
||||
|
||||
let code6 = "
|
||||
|
@ -28,6 +28,10 @@ pub enum RuntimeType {
|
||||
}
|
||||
|
||||
impl RuntimeType {
|
||||
pub fn any() -> Self {
|
||||
RuntimeType::Primitive(PrimitiveType::Any)
|
||||
}
|
||||
|
||||
pub fn edge() -> Self {
|
||||
RuntimeType::Primitive(PrimitiveType::Edge)
|
||||
}
|
||||
@ -166,6 +170,7 @@ impl RuntimeType {
|
||||
source_range: SourceRange,
|
||||
) -> Result<Self, CompilationError> {
|
||||
Ok(match value {
|
||||
AstPrimitiveType::Any => RuntimeType::Primitive(PrimitiveType::Any),
|
||||
AstPrimitiveType::String => RuntimeType::Primitive(PrimitiveType::String),
|
||||
AstPrimitiveType::Boolean => RuntimeType::Primitive(PrimitiveType::Boolean),
|
||||
AstPrimitiveType::Number(suffix) => RuntimeType::Primitive(PrimitiveType::Number(
|
||||
@ -207,7 +212,7 @@ impl RuntimeType {
|
||||
.collect::<Vec<_>>()
|
||||
.join(" or "),
|
||||
RuntimeType::Tuple(tys) => format!(
|
||||
"an array with values of types ({})",
|
||||
"a tuple with values of types ({})",
|
||||
tys.iter().map(Self::human_friendly_type).collect::<Vec<_>>().join(", ")
|
||||
),
|
||||
RuntimeType::Object(_) => format!("an object with fields {}", self),
|
||||
@ -219,6 +224,7 @@ impl RuntimeType {
|
||||
use RuntimeType::*;
|
||||
|
||||
match (self, sup) {
|
||||
(_, Primitive(PrimitiveType::Any)) => true,
|
||||
(Primitive(t1), Primitive(t2)) => t1.subtype(t2),
|
||||
(Array(t1, l1), Array(t2, l2)) => t1.subtype(t2) && l1.subtype(*l2),
|
||||
(Tuple(t1), Tuple(t2)) => t1.len() == t2.len() && t1.iter().zip(t2).all(|(t1, t2)| t1.subtype(t2)),
|
||||
@ -269,7 +275,7 @@ impl RuntimeType {
|
||||
.map(|t| t.display_multiple())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" or "),
|
||||
RuntimeType::Tuple(_) => "arrays".to_owned(),
|
||||
RuntimeType::Tuple(_) => "tuples".to_owned(),
|
||||
RuntimeType::Object(_) => format!("objects with fields {self}"),
|
||||
}
|
||||
}
|
||||
@ -286,7 +292,7 @@ impl fmt::Display for RuntimeType {
|
||||
},
|
||||
RuntimeType::Tuple(ts) => write!(
|
||||
f,
|
||||
"[{}]",
|
||||
"({})",
|
||||
ts.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(", ")
|
||||
),
|
||||
RuntimeType::Union(ts) => write!(
|
||||
@ -337,6 +343,7 @@ impl ArrayLen {
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum PrimitiveType {
|
||||
Any,
|
||||
Number(NumericType),
|
||||
String,
|
||||
Boolean,
|
||||
@ -357,6 +364,7 @@ pub enum PrimitiveType {
|
||||
impl PrimitiveType {
|
||||
fn display_multiple(&self) -> String {
|
||||
match self {
|
||||
PrimitiveType::Any => "any values".to_owned(),
|
||||
PrimitiveType::Number(NumericType::Known(unit)) => format!("numbers({unit})"),
|
||||
PrimitiveType::Number(_) => "numbers".to_owned(),
|
||||
PrimitiveType::String => "strings".to_owned(),
|
||||
@ -377,6 +385,7 @@ impl PrimitiveType {
|
||||
|
||||
fn subtype(&self, other: &PrimitiveType) -> bool {
|
||||
match (self, other) {
|
||||
(_, PrimitiveType::Any) => true,
|
||||
(PrimitiveType::Number(n1), PrimitiveType::Number(n2)) => n1.subtype(n2),
|
||||
(PrimitiveType::TagId, PrimitiveType::Tag) => true,
|
||||
(t1, t2) => t1 == t2,
|
||||
@ -387,6 +396,7 @@ impl PrimitiveType {
|
||||
impl fmt::Display for PrimitiveType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
PrimitiveType::Any => write!(f, "any"),
|
||||
PrimitiveType::Number(NumericType::Known(unit)) => write!(f, "number({unit})"),
|
||||
PrimitiveType::Number(NumericType::Unknown) => write!(f, "number(unknown units)"),
|
||||
PrimitiveType::Number(NumericType::Default { .. }) => write!(f, "number(default units)"),
|
||||
@ -1003,9 +1013,9 @@ impl KclValue {
|
||||
self_ty.subtype(ty)
|
||||
}
|
||||
|
||||
/// Coerce `self` to a new value which has `ty` as it's closest supertype.
|
||||
/// Coerce `self` to a new value which has `ty` as its closest supertype.
|
||||
///
|
||||
/// If the result is Some, then:
|
||||
/// If the result is Ok, then:
|
||||
/// - result.principal_type().unwrap().subtype(ty)
|
||||
///
|
||||
/// If self.principal_type() == ty then result == self
|
||||
@ -1025,10 +1035,11 @@ impl KclValue {
|
||||
exec_state: &mut ExecState,
|
||||
) -> Result<KclValue, CoercionError> {
|
||||
let value = match self {
|
||||
KclValue::MixedArray { value, .. } | KclValue::HomArray { value, .. } if value.len() == 1 => &value[0],
|
||||
KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } if value.len() == 1 => &value[0],
|
||||
_ => self,
|
||||
};
|
||||
match ty {
|
||||
PrimitiveType::Any => Ok(value.clone()),
|
||||
PrimitiveType::Number(ty) => ty.coerce(value),
|
||||
PrimitiveType::String => match value {
|
||||
KclValue::String { .. } => Ok(value.clone()),
|
||||
@ -1191,41 +1202,49 @@ impl KclValue {
|
||||
exec_state: &mut ExecState,
|
||||
allow_shrink: bool,
|
||||
) -> Result<KclValue, CoercionError> {
|
||||
if len.satisfied(1, false).is_some() && self.has_type(ty) {
|
||||
return Ok(KclValue::HomArray {
|
||||
value: vec![self.clone()],
|
||||
ty: ty.clone(),
|
||||
});
|
||||
}
|
||||
match self {
|
||||
KclValue::HomArray { value, ty: aty } => {
|
||||
KclValue::HomArray { value, ty: aty, .. } => {
|
||||
let satisfied_len = len.satisfied(value.len(), allow_shrink);
|
||||
|
||||
if aty.subtype(ty) {
|
||||
len.satisfied(value.len(), allow_shrink)
|
||||
// If the element type is a subtype of the target type and
|
||||
// the length constraint is satisfied, we can just return
|
||||
// the values unchanged, only adjusting the length. The new
|
||||
// array element type should preserve its type because the
|
||||
// target type oftentimes includes an unknown type as a way
|
||||
// to say that the caller doesn't care.
|
||||
return satisfied_len
|
||||
.map(|len| KclValue::HomArray {
|
||||
value: value[..len].to_vec(),
|
||||
ty: aty.clone(),
|
||||
})
|
||||
.ok_or(self.into())
|
||||
} else {
|
||||
Err(self.into())
|
||||
.ok_or(self.into());
|
||||
}
|
||||
}
|
||||
KclValue::MixedArray { value, .. } => {
|
||||
// Check if we have a nested homogeneous array that we can flatten.
|
||||
|
||||
// Ignore the array type, and coerce the elements of the array.
|
||||
if let Some(satisfied_len) = satisfied_len {
|
||||
let value_result = value
|
||||
.iter()
|
||||
.take(satisfied_len)
|
||||
.map(|v| v.coerce(ty, exec_state))
|
||||
.collect::<Result<Vec<_>, _>>();
|
||||
|
||||
if let Ok(value) = value_result {
|
||||
// We were able to coerce all the elements.
|
||||
return Ok(KclValue::HomArray { value, ty: ty.clone() });
|
||||
}
|
||||
}
|
||||
|
||||
// As a last resort, try to flatten the array.
|
||||
let mut values = Vec::new();
|
||||
for item in value {
|
||||
if let KclValue::HomArray {
|
||||
ty: inner_ty,
|
||||
value: inner_value,
|
||||
} = item
|
||||
{
|
||||
if inner_ty.subtype(ty) {
|
||||
values.extend(inner_value.iter().cloned());
|
||||
} else {
|
||||
values.push(item.clone());
|
||||
if let KclValue::HomArray { value: inner_value, .. } = item {
|
||||
// Flatten elements.
|
||||
for item in inner_value {
|
||||
values.push(item.coerce(ty, exec_state)?);
|
||||
}
|
||||
} else {
|
||||
values.push(item.clone());
|
||||
values.push(item.coerce(ty, exec_state)?);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1233,9 +1252,22 @@ impl KclValue {
|
||||
.satisfied(values.len(), allow_shrink)
|
||||
.ok_or(CoercionError::from(self))?;
|
||||
|
||||
let value = values[..len]
|
||||
assert!(len <= values.len());
|
||||
values.truncate(len);
|
||||
|
||||
Ok(KclValue::HomArray {
|
||||
value: values,
|
||||
ty: ty.clone(),
|
||||
})
|
||||
}
|
||||
KclValue::Tuple { value, .. } => {
|
||||
let len = len
|
||||
.satisfied(value.len(), allow_shrink)
|
||||
.ok_or(CoercionError::from(self))?;
|
||||
let value = value
|
||||
.iter()
|
||||
.map(|v| v.coerce(ty, exec_state))
|
||||
.map(|item| item.coerce(ty, exec_state))
|
||||
.take(len)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(KclValue::HomArray { value, ty: ty.clone() })
|
||||
@ -1244,28 +1276,32 @@ impl KclValue {
|
||||
value: Vec::new(),
|
||||
ty: ty.clone(),
|
||||
}),
|
||||
_ if len.satisfied(1, false).is_some() => Ok(KclValue::HomArray {
|
||||
value: vec![self.coerce(ty, exec_state)?],
|
||||
ty: ty.clone(),
|
||||
}),
|
||||
_ => Err(self.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn coerce_to_tuple_type(&self, tys: &[RuntimeType], exec_state: &mut ExecState) -> Result<KclValue, CoercionError> {
|
||||
match self {
|
||||
KclValue::MixedArray { value, .. } | KclValue::HomArray { value, .. } if value.len() == tys.len() => {
|
||||
KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } if value.len() == tys.len() => {
|
||||
let mut result = Vec::new();
|
||||
for (i, t) in tys.iter().enumerate() {
|
||||
result.push(value[i].coerce(t, exec_state)?);
|
||||
}
|
||||
|
||||
Ok(KclValue::MixedArray {
|
||||
Ok(KclValue::Tuple {
|
||||
value: result,
|
||||
meta: Vec::new(),
|
||||
})
|
||||
}
|
||||
KclValue::KclNone { meta, .. } if tys.is_empty() => Ok(KclValue::MixedArray {
|
||||
KclValue::KclNone { meta, .. } if tys.is_empty() => Ok(KclValue::Tuple {
|
||||
value: Vec::new(),
|
||||
meta: meta.clone(),
|
||||
}),
|
||||
value if tys.len() == 1 && value.has_type(&tys[0]) => Ok(KclValue::MixedArray {
|
||||
value if tys.len() == 1 && value.has_type(&tys[0]) => Ok(KclValue::Tuple {
|
||||
value: vec![value.clone()],
|
||||
meta: Vec::new(),
|
||||
}),
|
||||
@ -1325,7 +1361,7 @@ impl KclValue {
|
||||
KclValue::Face { .. } => Some(RuntimeType::Primitive(PrimitiveType::Face)),
|
||||
KclValue::Helix { .. } => Some(RuntimeType::Primitive(PrimitiveType::Helix)),
|
||||
KclValue::ImportedGeometry(..) => Some(RuntimeType::Primitive(PrimitiveType::ImportedGeometry)),
|
||||
KclValue::MixedArray { value, .. } => Some(RuntimeType::Tuple(
|
||||
KclValue::Tuple { value, .. } => Some(RuntimeType::Tuple(
|
||||
value.iter().map(|v| v.principal_type()).collect::<Option<Vec<_>>>()?,
|
||||
)),
|
||||
KclValue::HomArray { ty, value, .. } => {
|
||||
@ -1361,7 +1397,7 @@ mod test {
|
||||
value: "hello".to_owned(),
|
||||
meta: Vec::new(),
|
||||
},
|
||||
KclValue::MixedArray {
|
||||
KclValue::Tuple {
|
||||
value: Vec::new(),
|
||||
meta: Vec::new(),
|
||||
},
|
||||
@ -1430,45 +1466,67 @@ mod test {
|
||||
let aty1 = RuntimeType::Array(Box::new(ty.clone()), ArrayLen::Known(1));
|
||||
let aty0 = RuntimeType::Array(Box::new(ty.clone()), ArrayLen::NonEmpty);
|
||||
|
||||
assert_coerce_results(
|
||||
v,
|
||||
&aty,
|
||||
&KclValue::HomArray {
|
||||
value: vec![v.clone()],
|
||||
ty: ty.clone(),
|
||||
},
|
||||
&mut exec_state,
|
||||
);
|
||||
assert_coerce_results(
|
||||
v,
|
||||
&aty1,
|
||||
&KclValue::HomArray {
|
||||
value: vec![v.clone()],
|
||||
ty: ty.clone(),
|
||||
},
|
||||
&mut exec_state,
|
||||
);
|
||||
assert_coerce_results(
|
||||
v,
|
||||
&aty0,
|
||||
&KclValue::HomArray {
|
||||
value: vec![v.clone()],
|
||||
ty: ty.clone(),
|
||||
},
|
||||
&mut exec_state,
|
||||
);
|
||||
match v {
|
||||
KclValue::Tuple { .. } | KclValue::HomArray { .. } => {
|
||||
// These will not get wrapped if possible.
|
||||
assert_coerce_results(
|
||||
v,
|
||||
&aty,
|
||||
&KclValue::HomArray {
|
||||
value: vec![],
|
||||
ty: ty.clone(),
|
||||
},
|
||||
&mut exec_state,
|
||||
);
|
||||
// Coercing an empty tuple or array to an array of length 1
|
||||
// should fail.
|
||||
v.coerce(&aty1, &mut exec_state).unwrap_err();
|
||||
// Coercing an empty tuple or array to an array that's
|
||||
// non-empty should fail.
|
||||
v.coerce(&aty0, &mut exec_state).unwrap_err();
|
||||
}
|
||||
_ => {
|
||||
assert_coerce_results(
|
||||
v,
|
||||
&aty,
|
||||
&KclValue::HomArray {
|
||||
value: vec![v.clone()],
|
||||
ty: ty.clone(),
|
||||
},
|
||||
&mut exec_state,
|
||||
);
|
||||
assert_coerce_results(
|
||||
v,
|
||||
&aty1,
|
||||
&KclValue::HomArray {
|
||||
value: vec![v.clone()],
|
||||
ty: ty.clone(),
|
||||
},
|
||||
&mut exec_state,
|
||||
);
|
||||
assert_coerce_results(
|
||||
v,
|
||||
&aty0,
|
||||
&KclValue::HomArray {
|
||||
value: vec![v.clone()],
|
||||
ty: ty.clone(),
|
||||
},
|
||||
&mut exec_state,
|
||||
);
|
||||
|
||||
// Tuple subtype
|
||||
let tty = RuntimeType::Tuple(vec![ty.clone()]);
|
||||
assert_coerce_results(
|
||||
v,
|
||||
&tty,
|
||||
&KclValue::MixedArray {
|
||||
value: vec![v.clone()],
|
||||
meta: Vec::new(),
|
||||
},
|
||||
&mut exec_state,
|
||||
);
|
||||
// Tuple subtype
|
||||
let tty = RuntimeType::Tuple(vec![ty.clone()]);
|
||||
assert_coerce_results(
|
||||
v,
|
||||
&tty,
|
||||
&KclValue::Tuple {
|
||||
value: vec![v.clone()],
|
||||
meta: Vec::new(),
|
||||
},
|
||||
&mut exec_state,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for v in &values[1..] {
|
||||
@ -1516,7 +1574,7 @@ mod test {
|
||||
assert_coerce_results(
|
||||
&none,
|
||||
&tty,
|
||||
&KclValue::MixedArray {
|
||||
&KclValue::Tuple {
|
||||
value: Vec::new(),
|
||||
meta: Vec::new(),
|
||||
},
|
||||
@ -1647,7 +1705,7 @@ mod test {
|
||||
],
|
||||
ty: RuntimeType::Primitive(PrimitiveType::Number(NumericType::count())),
|
||||
};
|
||||
let mixed1 = KclValue::MixedArray {
|
||||
let mixed1 = KclValue::Tuple {
|
||||
value: vec![
|
||||
KclValue::Number {
|
||||
value: 0.0,
|
||||
@ -1662,7 +1720,7 @@ mod test {
|
||||
],
|
||||
meta: Vec::new(),
|
||||
};
|
||||
let mixed2 = KclValue::MixedArray {
|
||||
let mixed2 = KclValue::Tuple {
|
||||
value: vec![
|
||||
KclValue::Number {
|
||||
value: 0.0,
|
||||
@ -1752,7 +1810,7 @@ mod test {
|
||||
],
|
||||
ty: RuntimeType::Primitive(PrimitiveType::Number(NumericType::count())),
|
||||
};
|
||||
let mixed0 = KclValue::MixedArray {
|
||||
let mixed0 = KclValue::Tuple {
|
||||
value: vec![],
|
||||
meta: Vec::new(),
|
||||
};
|
||||
@ -2169,7 +2227,7 @@ d = cos(30)
|
||||
async fn coerce_nested_array() {
|
||||
let mut exec_state = ExecState::new(&crate::ExecutorContext::new_mock().await);
|
||||
|
||||
let mixed1 = KclValue::MixedArray {
|
||||
let mixed1 = KclValue::HomArray {
|
||||
value: vec![
|
||||
KclValue::Number {
|
||||
value: 0.0,
|
||||
@ -2197,7 +2255,7 @@ d = cos(30)
|
||||
ty: RuntimeType::Primitive(PrimitiveType::Number(NumericType::count())),
|
||||
},
|
||||
],
|
||||
meta: Vec::new(),
|
||||
ty: RuntimeType::any(),
|
||||
};
|
||||
|
||||
// Principal types
|
||||
|
@ -226,6 +226,7 @@ impl PrimitiveType {
|
||||
pub fn compute_digest(&mut self) -> Digest {
|
||||
let mut hasher = Sha256::new();
|
||||
match self {
|
||||
PrimitiveType::Any => hasher.update(b"any"),
|
||||
PrimitiveType::Named(id) => hasher.update(id.compute_digest()),
|
||||
PrimitiveType::String => hasher.update(b"string"),
|
||||
PrimitiveType::Number(suffix) => hasher.update(suffix.digestable_id()),
|
||||
|
@ -3186,6 +3186,8 @@ impl PipeExpression {
|
||||
#[ts(export)]
|
||||
#[serde(tag = "p_type")]
|
||||
pub enum PrimitiveType {
|
||||
/// The super type of all other types.
|
||||
Any,
|
||||
/// A string type.
|
||||
String,
|
||||
/// A number type.
|
||||
@ -3202,6 +3204,7 @@ pub enum PrimitiveType {
|
||||
impl PrimitiveType {
|
||||
pub fn primitive_from_str(s: &str, suffix: Option<NumericSuffix>) -> Option<Self> {
|
||||
match (s, suffix) {
|
||||
("any", None) => Some(PrimitiveType::Any),
|
||||
("string", None) => Some(PrimitiveType::String),
|
||||
("bool", None) => Some(PrimitiveType::Boolean),
|
||||
("tag", None) => Some(PrimitiveType::Tag),
|
||||
@ -3215,6 +3218,7 @@ impl PrimitiveType {
|
||||
impl fmt::Display for PrimitiveType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
PrimitiveType::Any => write!(f, "any"),
|
||||
PrimitiveType::Number(suffix) => {
|
||||
write!(f, "number")?;
|
||||
if *suffix != NumericSuffix::None {
|
||||
|
@ -2757,9 +2757,9 @@ fn labeled_argument(i: &mut TokenSlice) -> PResult<LabeledArg> {
|
||||
|
||||
/// A type of a function argument.
|
||||
/// This can be:
|
||||
/// - a primitive type, e.g. 'number' or 'string' or 'bool'
|
||||
/// - an array type, e.g. 'number[]' or 'string[]' or 'bool[]'
|
||||
/// - an object type, e.g. '{x: number, y: number}' or '{name: string, age: number}'
|
||||
/// - a primitive type, e.g. `number` or `string` or `bool`
|
||||
/// - an array type, e.g. `[number]` or `[string]` or `[bool]`
|
||||
/// - an object type, e.g. `{x: number, y: number}` or `{name: string, age: number}`
|
||||
fn argument_type(i: &mut TokenSlice) -> PResult<Node<Type>> {
|
||||
let type_ = alt((
|
||||
// Object types
|
||||
|
@ -363,6 +363,27 @@ mod cube_with_error {
|
||||
super::execute(TEST_NAME, true).await
|
||||
}
|
||||
}
|
||||
mod any_type {
|
||||
const TEST_NAME: &str = "any_type";
|
||||
|
||||
/// Test parsing KCL.
|
||||
#[test]
|
||||
fn parse() {
|
||||
super::parse(TEST_NAME)
|
||||
}
|
||||
|
||||
/// Test that parsing and unparsing KCL produces the original KCL input.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn unparse() {
|
||||
super::unparse(TEST_NAME).await
|
||||
}
|
||||
|
||||
/// Test that KCL is executed correctly.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn kcl_test_execute() {
|
||||
super::execute(TEST_NAME, false).await
|
||||
}
|
||||
}
|
||||
mod artifact_graph_example_code1 {
|
||||
const TEST_NAME: &str = "artifact_graph_example_code1";
|
||||
|
||||
@ -1144,6 +1165,27 @@ mod array_elem_push_fail {
|
||||
super::execute(TEST_NAME, false).await
|
||||
}
|
||||
}
|
||||
mod array_push_item_wrong_type {
|
||||
const TEST_NAME: &str = "array_push_item_wrong_type";
|
||||
|
||||
/// Test parsing KCL.
|
||||
#[test]
|
||||
fn parse() {
|
||||
super::parse(TEST_NAME)
|
||||
}
|
||||
|
||||
/// Test that parsing and unparsing KCL produces the original KCL input.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn unparse() {
|
||||
super::unparse(TEST_NAME).await
|
||||
}
|
||||
|
||||
/// Test that KCL is executed correctly.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn kcl_test_execute() {
|
||||
super::execute(TEST_NAME, false).await
|
||||
}
|
||||
}
|
||||
mod sketch_on_face {
|
||||
const TEST_NAME: &str = "sketch_on_face";
|
||||
|
||||
|
@ -557,24 +557,23 @@ impl Args {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn make_user_val_from_point(&self, p: [TyF64; 2]) -> Result<KclValue, KclError> {
|
||||
pub(crate) fn make_kcl_val_from_point(&self, p: [f64; 2], ty: NumericType) -> Result<KclValue, KclError> {
|
||||
let meta = Metadata {
|
||||
source_range: self.source_range,
|
||||
};
|
||||
let x = KclValue::Number {
|
||||
value: p[0].n,
|
||||
value: p[0],
|
||||
meta: vec![meta],
|
||||
ty: p[0].ty.clone(),
|
||||
ty: ty.clone(),
|
||||
};
|
||||
let y = KclValue::Number {
|
||||
value: p[1].n,
|
||||
value: p[1],
|
||||
meta: vec![meta],
|
||||
ty: p[1].ty.clone(),
|
||||
ty: ty.clone(),
|
||||
};
|
||||
Ok(KclValue::MixedArray {
|
||||
value: vec![x, y],
|
||||
meta: vec![meta],
|
||||
})
|
||||
let ty = RuntimeType::Primitive(PrimitiveType::Number(ty));
|
||||
|
||||
Ok(KclValue::HomArray { value: vec![x, y], ty })
|
||||
}
|
||||
|
||||
pub(super) fn make_user_val_from_f64_with_type(&self, f: TyF64) -> KclValue {
|
||||
@ -796,7 +795,7 @@ impl<'a> FromKclValue<'a> for Vec<TagIdentifier> {
|
||||
let tags = value.iter().map(|v| v.get_tag_identifier().unwrap()).collect();
|
||||
Some(tags)
|
||||
}
|
||||
KclValue::MixedArray { value, .. } => {
|
||||
KclValue::Tuple { value, .. } => {
|
||||
let tags = value.iter().map(|v| v.get_tag_identifier().unwrap()).collect();
|
||||
Some(tags)
|
||||
}
|
||||
@ -1136,8 +1135,11 @@ impl_from_kcl_for_vec!(TyF64);
|
||||
|
||||
impl<'a> FromKclValue<'a> for SourceRange {
|
||||
fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
|
||||
let KclValue::MixedArray { value, meta: _ } = arg else {
|
||||
return None;
|
||||
let value = match arg {
|
||||
KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => value,
|
||||
_ => {
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if value.len() != 3 {
|
||||
return None;
|
||||
@ -1334,7 +1336,7 @@ impl<'a> FromKclValue<'a> for TyF64 {
|
||||
impl<'a> FromKclValue<'a> for [TyF64; 2] {
|
||||
fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
|
||||
match arg {
|
||||
KclValue::MixedArray { value, meta: _ } | KclValue::HomArray { value, .. } => {
|
||||
KclValue::Tuple { value, meta: _ } | KclValue::HomArray { value, .. } => {
|
||||
if value.len() != 2 {
|
||||
return None;
|
||||
}
|
||||
@ -1351,7 +1353,7 @@ impl<'a> FromKclValue<'a> for [TyF64; 2] {
|
||||
impl<'a> FromKclValue<'a> for [TyF64; 3] {
|
||||
fn from_kcl_val(arg: &'a KclValue) -> Option<Self> {
|
||||
match arg {
|
||||
KclValue::MixedArray { value, meta: _ } | KclValue::HomArray { value, .. } => {
|
||||
KclValue::Tuple { value, meta: _ } | KclValue::HomArray { value, .. } => {
|
||||
if value.len() != 3 {
|
||||
return None;
|
||||
}
|
||||
|
@ -9,6 +9,7 @@ use crate::{
|
||||
errors::{KclError, KclErrorDetails},
|
||||
execution::{
|
||||
kcl_value::{FunctionSource, KclValue},
|
||||
types::RuntimeType,
|
||||
ExecState,
|
||||
},
|
||||
source_range::SourceRange,
|
||||
@ -19,9 +20,11 @@ use crate::{
|
||||
pub async fn map(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
|
||||
let array: Vec<KclValue> = args.get_unlabeled_kw_arg("array")?;
|
||||
let f: &FunctionSource = args.get_kw_arg("f")?;
|
||||
let meta = vec![args.source_range.into()];
|
||||
let new_array = inner_map(array, f, exec_state, &args).await?;
|
||||
Ok(KclValue::MixedArray { value: new_array, meta })
|
||||
Ok(KclValue::HomArray {
|
||||
value: new_array,
|
||||
ty: RuntimeType::any(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Apply a function to every element of a list.
|
||||
@ -257,6 +260,31 @@ async fn call_reduce_closure(
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub async fn push(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
|
||||
let array = args.get_unlabeled_kw_arg("array")?;
|
||||
let item: KclValue = args.get_kw_arg("item")?;
|
||||
|
||||
let KclValue::HomArray { value: values, ty } = array else {
|
||||
let meta = vec![args.source_range];
|
||||
let actual_type = array.human_friendly_type();
|
||||
return Err(KclError::Semantic(KclErrorDetails {
|
||||
source_ranges: meta,
|
||||
message: format!("You can't push to a value of type {actual_type}, only an array"),
|
||||
}));
|
||||
};
|
||||
let ty = if item.has_type(&ty) {
|
||||
ty
|
||||
} else {
|
||||
// The user pushed an item with a type that differs from the array's
|
||||
// element type.
|
||||
RuntimeType::any()
|
||||
};
|
||||
|
||||
let new_array = inner_push(values, item);
|
||||
|
||||
Ok(KclValue::HomArray { value: new_array, ty })
|
||||
}
|
||||
|
||||
/// Append an element to the end of an array.
|
||||
///
|
||||
/// Returns a new array with the element appended.
|
||||
@ -276,28 +304,26 @@ async fn call_reduce_closure(
|
||||
},
|
||||
tags = ["array"]
|
||||
}]
|
||||
async fn inner_push(mut array: Vec<KclValue>, item: KclValue, args: &Args) -> Result<KclValue, KclError> {
|
||||
fn inner_push(mut array: Vec<KclValue>, item: KclValue) -> Vec<KclValue> {
|
||||
array.push(item);
|
||||
Ok(KclValue::MixedArray {
|
||||
value: array,
|
||||
meta: vec![args.source_range.into()],
|
||||
})
|
||||
|
||||
array
|
||||
}
|
||||
|
||||
pub async fn push(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
|
||||
// Extract the array and the element from the arguments
|
||||
let val: KclValue = args.get_unlabeled_kw_arg("array")?;
|
||||
let item = args.get_kw_arg("item")?;
|
||||
|
||||
let meta = vec![args.source_range];
|
||||
let KclValue::MixedArray { value: array, meta: _ } = val else {
|
||||
let actual_type = val.human_friendly_type();
|
||||
pub async fn pop(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
|
||||
let array = args.get_unlabeled_kw_arg("array")?;
|
||||
let KclValue::HomArray { value: values, ty } = array else {
|
||||
let meta = vec![args.source_range];
|
||||
let actual_type = array.human_friendly_type();
|
||||
return Err(KclError::Semantic(KclErrorDetails {
|
||||
source_ranges: meta,
|
||||
message: format!("You can't push to a value of type {actual_type}, only an array"),
|
||||
message: format!("You can't pop from a value of type {actual_type}, only an array"),
|
||||
}));
|
||||
};
|
||||
inner_push(array, item, &args).await
|
||||
|
||||
let new_array = inner_pop(values, &args)?;
|
||||
|
||||
Ok(KclValue::HomArray { value: new_array, ty })
|
||||
}
|
||||
|
||||
/// Remove the last element from an array.
|
||||
@ -320,7 +346,7 @@ pub async fn push(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, K
|
||||
},
|
||||
tags = ["array"]
|
||||
}]
|
||||
async fn inner_pop(array: Vec<KclValue>, args: &Args) -> Result<KclValue, KclError> {
|
||||
fn inner_pop(array: Vec<KclValue>, args: &Args) -> Result<Vec<KclValue>, KclError> {
|
||||
if array.is_empty() {
|
||||
return Err(KclError::Semantic(KclErrorDetails {
|
||||
message: "Cannot pop from an empty array".to_string(),
|
||||
@ -331,24 +357,5 @@ async fn inner_pop(array: Vec<KclValue>, args: &Args) -> Result<KclValue, KclErr
|
||||
// Create a new array with all elements except the last one
|
||||
let new_array = array[..array.len() - 1].to_vec();
|
||||
|
||||
Ok(KclValue::MixedArray {
|
||||
value: new_array,
|
||||
meta: vec![args.source_range.into()],
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn pop(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
|
||||
// Extract the array from the arguments
|
||||
let val = args.get_unlabeled_kw_arg("array")?;
|
||||
|
||||
let meta = vec![args.source_range];
|
||||
let KclValue::MixedArray { value: array, meta: _ } = val else {
|
||||
let actual_type = val.human_friendly_type();
|
||||
return Err(KclError::Semantic(KclErrorDetails {
|
||||
source_ranges: meta,
|
||||
message: format!("You can't pop from a value of type {actual_type}, only an array"),
|
||||
}));
|
||||
};
|
||||
|
||||
inner_pop(array, &args).await
|
||||
Ok(new_array)
|
||||
}
|
||||
|
@ -452,7 +452,7 @@ async fn make_transform<T: GeometryTrait>(
|
||||
})?;
|
||||
let transforms = match transform_fn_return {
|
||||
KclValue::Object { value, meta: _ } => vec![value],
|
||||
KclValue::MixedArray { value, meta: _ } => {
|
||||
KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
|
||||
let transforms: Vec<_> = value
|
||||
.into_iter()
|
||||
.map(|val| {
|
||||
@ -671,12 +671,44 @@ impl GeometryTrait for Solid {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::execution::types::NumericType;
|
||||
use crate::execution::types::{NumericType, PrimitiveType};
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn test_array_to_point3d() {
|
||||
let mut exec_state = ExecState::new(&ExecutorContext::new_mock().await);
|
||||
let input = KclValue::MixedArray {
|
||||
let input = KclValue::HomArray {
|
||||
value: vec![
|
||||
KclValue::Number {
|
||||
value: 1.1,
|
||||
meta: Default::default(),
|
||||
ty: NumericType::mm(),
|
||||
},
|
||||
KclValue::Number {
|
||||
value: 2.2,
|
||||
meta: Default::default(),
|
||||
ty: NumericType::mm(),
|
||||
},
|
||||
KclValue::Number {
|
||||
value: 3.3,
|
||||
meta: Default::default(),
|
||||
ty: NumericType::mm(),
|
||||
},
|
||||
],
|
||||
ty: RuntimeType::Primitive(PrimitiveType::Number(NumericType::mm())),
|
||||
};
|
||||
let expected = [
|
||||
TyF64::new(1.1, NumericType::mm()),
|
||||
TyF64::new(2.2, NumericType::mm()),
|
||||
TyF64::new(3.3, NumericType::mm()),
|
||||
];
|
||||
let actual = array_to_point3d(&input, Vec::new(), &mut exec_state);
|
||||
assert_eq!(actual.unwrap(), expected);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn test_tuple_to_point3d() {
|
||||
let mut exec_state = ExecState::new(&ExecutorContext::new_mock().await);
|
||||
let input = KclValue::Tuple {
|
||||
value: vec![
|
||||
KclValue::Number {
|
||||
value: 1.1,
|
||||
|
@ -17,9 +17,9 @@ use crate::{
|
||||
/// Returns the point at the end of the given segment.
|
||||
pub async fn segment_end(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
|
||||
let tag: TagIdentifier = args.get_unlabeled_kw_arg("tag")?;
|
||||
let result = inner_segment_end(&tag, exec_state, args.clone())?;
|
||||
let pt = inner_segment_end(&tag, exec_state, args.clone())?;
|
||||
|
||||
args.make_user_val_from_point(result)
|
||||
args.make_kcl_val_from_point([pt[0].n, pt[1].n], pt[0].ty.clone())
|
||||
}
|
||||
|
||||
/// Compute the ending point of the provided line segment.
|
||||
@ -64,8 +64,11 @@ fn inner_segment_end(tag: &TagIdentifier, exec_state: &mut ExecState, args: Args
|
||||
source_ranges: vec![args.source_range],
|
||||
})
|
||||
})?;
|
||||
let (p, ty) = path.end_point_components();
|
||||
// Docs generation isn't smart enough to handle ([f64; 2], NumericType).
|
||||
let point = [TyF64::new(p[0], ty.clone()), TyF64::new(p[1], ty)];
|
||||
|
||||
Ok(path.get_to().clone())
|
||||
Ok(point)
|
||||
}
|
||||
|
||||
/// Returns the segment end of x.
|
||||
@ -156,9 +159,9 @@ fn inner_segment_end_y(tag: &TagIdentifier, exec_state: &mut ExecState, args: Ar
|
||||
/// Returns the point at the start of the given segment.
|
||||
pub async fn segment_start(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
|
||||
let tag: TagIdentifier = args.get_unlabeled_kw_arg("tag")?;
|
||||
let result = inner_segment_start(&tag, exec_state, args.clone())?;
|
||||
let pt = inner_segment_start(&tag, exec_state, args.clone())?;
|
||||
|
||||
args.make_user_val_from_point(result)
|
||||
args.make_kcl_val_from_point([pt[0].n, pt[1].n], pt[0].ty.clone())
|
||||
}
|
||||
|
||||
/// Compute the starting point of the provided line segment.
|
||||
@ -203,8 +206,11 @@ fn inner_segment_start(tag: &TagIdentifier, exec_state: &mut ExecState, args: Ar
|
||||
source_ranges: vec![args.source_range],
|
||||
})
|
||||
})?;
|
||||
let (p, ty) = path.start_point_components();
|
||||
// Docs generation isn't smart enough to handle ([f64; 2], NumericType).
|
||||
let point = [TyF64::new(p[0], ty.clone()), TyF64::new(p[1], ty)];
|
||||
|
||||
Ok(path.get_from().to_owned())
|
||||
Ok(point)
|
||||
}
|
||||
|
||||
/// Returns the segment start of x.
|
||||
|
Reference in New Issue
Block a user