Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add the runtime value of arguments to operations #5206

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
173 changes: 169 additions & 4 deletions src/wasm-lib/kcl/src/execution/cad_op.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ use indexmap::IndexMap;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use super::{kcl_value::NumericType, ArtifactId, KclValue};
use crate::{docs::StdLibFn, std::get_stdlib_fn, SourceRange};

/// A CAD modeling operation for display in the feature tree, AKA operations
/// timeline.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, ts_rs::TS, JsonSchema)]
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
#[serde(tag = "type")]
pub enum Operation {
Expand Down Expand Up @@ -54,18 +55,21 @@ impl Operation {
}

/// An argument to a CAD modeling operation.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, ts_rs::TS, JsonSchema)]
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
#[serde(rename_all = "camelCase")]
pub struct OpArg {
/// The runtime value of the argument. Instead of using [`KclValue`], we
/// refer to scene objects using their [`ArtifactId`]s.
value: OpKclValue,
/// The KCL code expression for the argument. This is used in the UI so
/// that the user can edit the expression.
source_range: SourceRange,
}

impl OpArg {
pub(crate) fn new(source_range: SourceRange) -> Self {
Self { source_range }
pub(crate) fn new(value: OpKclValue, source_range: SourceRange) -> Self {
Self { value, source_range }
}
}

Expand Down Expand Up @@ -132,3 +136,164 @@ where
fn is_false(b: &bool) -> bool {
!*b
}

/// A KCL value used in Operations. `ArtifactId`s are used to refer to the
/// actual scene objects. Any data not needed in the UI may be omitted.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
#[serde(tag = "type")]
pub enum OpKclValue {
Uuid {
value: ::uuid::Uuid,
},
Bool {
value: bool,
},
Number {
value: f64,
ty: NumericType,
},
String {
value: String,
},
Array {
value: Vec<OpKclValue>,
},
Object {
value: OpKclObjectFields,
},
TagIdentifier {
/// The name of the tag identifier.
value: String,
/// The artifact ID of the object it refers to.
artifact_id: Option<ArtifactId>,
},
TagDeclarator {
name: String,
},
Plane {
artifact_id: ArtifactId,
},
Face {
artifact_id: ArtifactId,
},
Sketch {
value: Box<OpSketch>,
},
Sketches {
value: Vec<OpSketch>,
},
Solid {
value: Box<OpSolid>,
},
Solids {
value: Vec<OpSolid>,
},
Helix {
value: Box<OpHelix>,
},
ImportedGeometry {
artifact_id: ArtifactId,
},
Function {},
Module {},
KclNone {},
}

pub type OpKclObjectFields = IndexMap<String, OpKclValue>;

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
#[serde(rename_all = "camelCase")]
pub struct OpSketch {
artifact_id: ArtifactId,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
#[serde(rename_all = "camelCase")]
pub struct OpSolid {
artifact_id: ArtifactId,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
#[serde(rename_all = "camelCase")]
pub struct OpHelix {
artifact_id: ArtifactId,
}

impl From<&KclValue> for OpKclValue {
fn from(value: &KclValue) -> Self {
match value {
KclValue::Uuid { value, .. } => Self::Uuid { value: *value },
KclValue::Bool { value, .. } => Self::Bool { value: *value },
KclValue::Number { value, ty, .. } => Self::Number {
value: *value,
ty: ty.clone(),
},
KclValue::String { value, .. } => Self::String { value: value.clone() },
KclValue::Array { value, .. } => {
let value = value.iter().map(Self::from).collect();
Self::Array { value }
}
KclValue::Object { value, .. } => {
let value = value.iter().map(|(k, v)| (k.clone(), Self::from(v))).collect();
Self::Object { value }
}
KclValue::TagIdentifier(tag_identifier) => Self::TagIdentifier {
value: tag_identifier.value.clone(),
artifact_id: tag_identifier.info.as_ref().map(|info| ArtifactId::new(info.id)),
},
KclValue::TagDeclarator(node) => Self::TagDeclarator {
name: node.name.clone(),
},
KclValue::Plane { value } => Self::Plane {
artifact_id: value.artifact_id,
},
KclValue::Face { value } => Self::Face {
artifact_id: value.artifact_id,
},
KclValue::Sketch { value } => Self::Sketch {
value: Box::new(OpSketch {
artifact_id: value.artifact_id,
}),
},
KclValue::Sketches { value } => {
let value = value
.iter()
.map(|sketch| OpSketch {
artifact_id: sketch.artifact_id,
})
.collect();
Self::Sketches { value }
}
KclValue::Solid { value } => Self::Solid {
value: Box::new(OpSolid {
artifact_id: value.artifact_id,
}),
},
KclValue::Solids { value } => {
let value = value
.iter()
.map(|solid| OpSolid {
artifact_id: solid.artifact_id,
})
.collect();
Self::Solids { value }
}
KclValue::Helix { value } => Self::Helix {
value: Box::new(OpHelix {
artifact_id: value.artifact_id,
}),
},
KclValue::ImportedGeometry(imported_geometry) => Self::ImportedGeometry {
artifact_id: ArtifactId::new(imported_geometry.id),
},
KclValue::Function { .. } => Self::Function {},
KclValue::Module { .. } => Self::Module {},
KclValue::KclNone { .. } => Self::KclNone {},
KclValue::Tombstone { .. } => unreachable!("Tombstone OpKclValue"),
}
}
}
23 changes: 17 additions & 6 deletions src/wasm-lib/kcl/src/execution/exec_ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::{
errors::{KclError, KclErrorDetails},
execution::{
annotations,
cad_op::{OpArg, Operation},
cad_op::{OpArg, OpKclValue, Operation},
kcl_value::NumericType,
memory,
state::ModuleState,
Expand Down Expand Up @@ -925,11 +925,13 @@ impl Node<CallExpressionKw> {
.kw_args
.labeled
.iter()
.map(|(k, v)| (k.clone(), OpArg::new(v.source_range)))
.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.kw_args.unlabeled.as_ref().map(|arg| OpArg::new(arg.source_range)),
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,
Expand Down Expand Up @@ -970,15 +972,19 @@ impl Node<CallExpressionKw> {
.kw_args
.labeled
.iter()
.map(|(k, v)| (k.clone(), OpArg::new(v.source_range)))
.map(|(k, arg)| (k.clone(), OpArg::new(OpKclValue::from(&arg.value), arg.source_range)))
.collect();
exec_state
.mod_local
.operations
.push(Operation::UserDefinedFunctionCall {
name: Some(fn_name.clone()),
function_source_range: func.function_def_source_range().unwrap_or_default(),
unlabeled_arg: args.kw_args.unlabeled.as_ref().map(|arg| OpArg::new(arg.source_range)),
unlabeled_arg: args
.kw_args
.unlabeled
.as_ref()
.map(|arg| OpArg::new(OpKclValue::from(&arg.value), arg.source_range)),
labeled_args: op_labeled_args,
source_range: callsite,
});
Expand Down Expand Up @@ -1043,7 +1049,12 @@ impl Node<CallExpression> {
.args(false)
.iter()
.zip(&fn_args)
.map(|(k, v)| (k.name.clone(), OpArg::new(v.source_range)))
.map(|(k, arg)| {
(
k.name.clone(),
OpArg::new(OpKclValue::from(&arg.value), arg.source_range),
)
})
.collect();
Some(Operation::StdLibCall {
std_lib_fn: (&func).into(),
Expand Down
3 changes: 1 addition & 2 deletions src/wasm-lib/kcl/src/execution/kcl_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use anyhow::Result;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use super::{memory::EnvironmentRef, MetaSettings};
use crate::{
errors::KclErrorDetails,
exec::Sketch,
Expand All @@ -21,8 +22,6 @@ use crate::{
ExecutorContext, KclError, ModuleId, SourceRange,
};

use super::{memory::EnvironmentRef, MetaSettings};

pub type KclObjectFields = HashMap<String, KclValue>;

/// Any KCL value.
Expand Down
7 changes: 6 additions & 1 deletion src/wasm-lib/kcl/src/simulation_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,12 @@ fn assert_common_snapshots(
artifact_graph: ArtifactGraph,
) {
assert_snapshot(test_name, "Operations executed", || {
insta::assert_json_snapshot!("ops", operations);
insta::assert_json_snapshot!("ops", operations, {
"[].unlabeledArg.*.value.**[].from[]" => rounded_redaction(4),
"[].unlabeledArg.*.value.**[].to[]" => rounded_redaction(4),
"[].labeledArgs.*.value.**[].from[]" => rounded_redaction(4),
"[].labeledArgs.*.value.**[].to[]" => rounded_redaction(4),
});
});
assert_snapshot(test_name, "Artifact commands", || {
insta::assert_json_snapshot!("artifact_commands", artifact_commands, {
Expand Down
18 changes: 12 additions & 6 deletions src/wasm-lib/kcl/src/std/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,17 +130,23 @@ impl Args {
})
}

/// Get the unlabeled keyword argument. If not set, returns Err.
/// 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()
.or(self.args.first())
.or(self.pipe_value.as_ref())
}

/// Get the unlabeled keyword argument. If not set, returns Err. If it
/// can't be converted to the given type, returns Err.
pub(crate) fn get_unlabeled_kw_arg<'a, T>(&'a self, label: &str) -> Result<T, KclError>
where
T: FromKclValue<'a>,
{
let arg = self
.kw_args
.unlabeled
.as_ref()
.or(self.args.first())
.or(self.pipe_value.as_ref())
.unlabeled_kw_arg_unconverted()
.ok_or(KclError::Semantic(KclErrorDetails {
source_ranges: vec![self.source_range],
message: format!("This function requires a value for the special unlabeled first parameter, '{label}'"),
Expand Down
32 changes: 30 additions & 2 deletions src/wasm-lib/kcl/tests/angled_line/ops.snap
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
---
source: kcl/src/simulation_tests.rs
description: Operations executed angled_line.kcl
snapshot_kind: text
---
[
{
"labeledArgs": {
"data": {
"value": {
"type": "String",
"value": "XY"
},
"sourceRange": [
24,
28,
Expand All @@ -26,6 +29,19 @@ snapshot_kind: text
{
"labeledArgs": {
"length": {
"value": {
"type": "Number",
"value": 4.0,
"ty": {
"type": "Default",
"len": {
"type": "Mm"
},
"angle": {
"type": "Degrees"
}
}
},
"sourceRange": [
287,
288,
Expand All @@ -40,6 +56,18 @@ snapshot_kind: text
0
],
"type": "StdLibCall",
"unlabeledArg": null
"unlabeledArg": {
"value": {
"type": "Sketch",
"value": {
"artifactId": "[uuid]"
}
},
"sourceRange": [
0,
0,
0
]
}
}
]
Loading
Loading