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

KCL stdlib and circle function #1029

Merged
merged 6 commits into from
Nov 9, 2023
Merged
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
8 changes: 6 additions & 2 deletions src/wasm-lib/.config/nextest.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@
serial-integration = { max-threads = 4 }

[profile.default]
slow-timeout = { period = "60s", terminate-after = 1 }
slow-timeout = { period = "10s", terminate-after = 1 }

[profile.ci]
slow-timeout = { period = "120s", terminate-after = 10 }
slow-timeout = { period = "30s", terminate-after = 5 }

[[profile.default.overrides]]
filter = "test(serial_test_)"
Expand All @@ -20,3 +20,7 @@ threads-required = 4
filter = "test(serial_test_)"
test-group = "serial-integration"
threads-required = 4

[[profile.default.overrides]]
filter = "test(parser::parser_impl::snapshot_tests)"
slow-timeout = { period = "1s", terminate-after = 5 }
62 changes: 54 additions & 8 deletions src/wasm-lib/kcl/src/ast/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ use tower_lsp::lsp_types::{CompletionItem, CompletionItemKind, DocumentSymbol, R

pub use self::literal_value::LiteralValue;
use crate::{
docs::StdLibFn,
errors::{KclError, KclErrorDetails},
executor::{ExecutorContext, MemoryItem, Metadata, PipeInfo, ProgramMemory, SourceRange, UserVal},
executor::{BodyType, ExecutorContext, MemoryItem, Metadata, PipeInfo, ProgramMemory, SourceRange, UserVal},
parser::PIPE_OPERATOR,
std::{kcl_stdlib::KclStdLibFn, FunctionKind},
};

mod literal_value;
Expand Down Expand Up @@ -960,8 +962,8 @@ impl CallExpression {
fn_args.push(result);
}

match ctx.stdlib.get(&self.callee.name) {
Some(func) => {
match ctx.stdlib.get_either(&self.callee.name) {
FunctionKind::Core(func) => {
// Attempt to call the function.
let args = crate::std::Args::new(fn_args, self.into(), ctx.clone());
let result = func.std_lib_fn()(args).await?;
Expand All @@ -973,15 +975,54 @@ impl CallExpression {
Ok(result)
}
}
// Must be user-defined then
None => {
FunctionKind::Std(func) => {
let function_expression = func.function();
if fn_args.len() != function_expression.params.len() {
return Err(KclError::Semantic(KclErrorDetails {
message: format!(
"Expected {} arguments, got {}",
function_expression.params.len(),
fn_args.len(),
),
source_ranges: vec![(function_expression).into()],
}));
}

// Add the arguments to the memory.
let mut fn_memory = memory.clone();
for (index, param) in function_expression.params.iter().enumerate() {
fn_memory.add(&param.name, fn_args.get(index).unwrap().clone(), param.into())?;
}

// Call the stdlib function
let p = func.function().clone().body;
let results = crate::executor::execute(p, &mut fn_memory, BodyType::Block, ctx).await?;
let out = results.return_;
let result = out.ok_or_else(|| {
KclError::UndefinedValue(KclErrorDetails {
message: format!("Result of stdlib function {} is undefined", fn_name),
source_ranges: vec![self.into()],
})
})?;
let result = result.get_value()?;

if pipe_info.is_in_pipe {
pipe_info.index += 1;
pipe_info.previous_results.push(result);

execute_pipe_body(memory, &pipe_info.body.clone(), pipe_info, self.into(), ctx).await
} else {
Ok(result)
}
}
FunctionKind::UserDefined => {
let func = memory.get(&fn_name, self.into())?;
let result = func
.call_fn(fn_args, memory.clone(), ctx.clone())
.await?
.ok_or_else(|| {
KclError::UndefinedValue(KclErrorDetails {
message: format!("Result of function {} is undefined", fn_name),
message: format!("Result of user-defined function {} is undefined", fn_name),
source_ranges: vec![self.into()],
})
})?;
Expand Down Expand Up @@ -1056,10 +1097,15 @@ impl CallExpression {
#[ts(export)]
#[serde(tag = "type")]
pub enum Function {
/// A stdlib function.
/// A stdlib function written in Rust (aka core lib).
StdLib {
/// The function.
func: Box<dyn crate::docs::StdLibFn>,
func: Box<dyn StdLibFn>,
},
/// A stdlib function written in KCL.
StdLibKcl {
/// The function.
func: Box<dyn KclStdLibFn>,
},
/// A function that is defined in memory.
#[default]
Expand Down
46 changes: 29 additions & 17 deletions src/wasm-lib/kcl/src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use std::{collections::HashMap, sync::Arc};

use anyhow::Result;
use async_recursion::async_recursion;
use kittycad::types::{Color, ModelingCmd, Point3D};
use parse_display::{Display, FromStr};
use schemars::JsonSchema;
Expand All @@ -13,7 +14,7 @@ use crate::{
ast::types::{BodyItem, FunctionExpression, Value},
engine::{EngineConnection, EngineManager},
errors::{KclError, KclErrorDetails},
std::StdLib,
std::{FunctionKind, StdLib},
};

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
Expand Down Expand Up @@ -781,6 +782,7 @@ pub struct ExecutorContext {
}

/// Execute a AST's program.
#[async_recursion(?Send)]
pub async fn execute(
program: crate::ast::types::Program,
memory: &mut ProgramMemory,
Expand Down Expand Up @@ -828,27 +830,37 @@ pub async fn execute(
}
}
let _show_fn = Box::new(crate::std::Show);
if let Some(func) = ctx.stdlib.get(&call_expr.callee.name) {
use crate::docs::StdLibFn;
if func.name() == _show_fn.name() {
if options != BodyType::Root {
match ctx.stdlib.get_either(&call_expr.callee.name) {
FunctionKind::Core(func) => {
use crate::docs::StdLibFn;
if func.name() == _show_fn.name() {
if options != BodyType::Root {
return Err(KclError::Semantic(KclErrorDetails {
message: "Cannot call show outside of a root".to_string(),
source_ranges: vec![call_expr.into()],
}));
}

memory.return_ = Some(ProgramReturn::Arguments(call_expr.arguments.clone()));
}
}
FunctionKind::Std(func) => {
let mut newmem = memory.clone();
let result = execute(func.program().to_owned(), &mut newmem, BodyType::Block, ctx).await?;
memory.return_ = result.return_;
}
FunctionKind::UserDefined => {
if let Some(func) = memory.clone().root.get(&fn_name) {
let result = func.call_fn(args.clone(), memory.clone(), ctx.clone()).await?;

memory.return_ = result;
} else {
return Err(KclError::Semantic(KclErrorDetails {
message: "Cannot call show outside of a root".to_string(),
message: format!("No such name {} defined", fn_name),
source_ranges: vec![call_expr.into()],
}));
}

memory.return_ = Some(ProgramReturn::Arguments(call_expr.arguments.clone()));
}
} else if let Some(func) = memory.clone().root.get(&fn_name) {
let result = func.call_fn(args.clone(), memory.clone(), ctx.clone()).await?;

memory.return_ = result;
} else {
return Err(KclError::Semantic(KclErrorDetails {
message: format!("No such name {} defined", fn_name),
source_ranges: vec![call_expr.into()],
}));
}
}
}
Expand Down
5 changes: 2 additions & 3 deletions src/wasm-lib/kcl/src/parser/parser_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1388,7 +1388,7 @@ const mySk1 = startSketchAt([0, 0])"#;
let Value::PipeExpression(pipe) = val else {
panic!("expected pipe");
};
let mut noncode = dbg!(pipe.non_code_meta);
let mut noncode = pipe.non_code_meta;
assert_eq!(noncode.non_code_nodes.len(), 1);
let comment = noncode.non_code_nodes.remove(&0).unwrap().pop().unwrap();
assert_eq!(
Expand Down Expand Up @@ -2575,8 +2575,7 @@ thing(false)
let tokens = crate::token::lexer(test_program);
let parser = crate::parser::Parser::new(tokens);
let result = parser.ast();
let e = result.unwrap_err();
eprintln!("{e:?}")
let _e = result.unwrap_err();
}

#[test]
Expand Down
Loading
Loading