diff --git a/Cargo.toml b/Cargo.toml index 98e07f52..d83873be 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,3 +12,7 @@ license = "Apache-2.0" [dependencies] anyhow = "1" kclvm-api = { git = "https://github.com/kcl-lang/kcl", version = "0.10.0-rc.1" } +kclvm-evaluator = { git = "https://github.com/kcl-lang/kcl", version = "0.10.0-rc.1" } +kclvm-loader = { git = "https://github.com/kcl-lang/kcl", version = "0.10.0-rc.1" } +kclvm-parser = { git = "https://github.com/kcl-lang/kcl", version = "0.10.0-rc.1" } +kclvm-runtime = { git = "https://github.com/kcl-lang/kcl", version = "0.10.0-rc.1" } diff --git a/src/lib.rs b/src/lib.rs index 3cb3d82c..1bb5a35d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -33,6 +33,9 @@ use anyhow::Result; pub type API = KclvmServiceImpl; +#[cfg(test)] +mod tests; + /// Call KCL API with the API name and argument protobuf bytes. #[inline] pub fn call<'a>(name: &'a [u8], args: &'a [u8]) -> Result> { diff --git a/src/tests.rs b/src/tests.rs new file mode 100644 index 00000000..85f672d0 --- /dev/null +++ b/src/tests.rs @@ -0,0 +1,48 @@ +use anyhow::{anyhow, Result}; +use kclvm_evaluator::Evaluator; +use kclvm_loader::{load_packages, LoadPackageOptions}; +use kclvm_parser::LoadProgramOptions; +use kclvm_runtime::{Context, IndexMap, PluginFunction, ValueRef}; +use std::{cell::RefCell, rc::Rc, sync::Arc}; + +fn my_plugin_sum(_: &Context, args: &ValueRef, _: &ValueRef) -> Result { + let a = args + .arg_i_int(0, Some(0)) + .ok_or(anyhow!("expect int value for the first param"))?; + let b = args + .arg_i_int(1, Some(0)) + .ok_or(anyhow!("expect int value for the second param"))?; + Ok((a + b).into()) +} + +fn context_with_plugin() -> Rc> { + let mut plugin_functions: IndexMap = Default::default(); + let func = Arc::new(my_plugin_sum); + plugin_functions.insert("my_plugin.add".to_string(), func); + let mut ctx = Context::new(); + ctx.plugin_functions = plugin_functions; + Rc::new(RefCell::new(ctx)) +} + +#[test] +fn test_exec_with_plugin() -> Result<()> { + let src = r#" +import kcl_plugin.my_plugin + +sum = my_plugin.add(1, 1) +"#; + let p = load_packages(&LoadPackageOptions { + paths: vec!["test.k".to_string()], + load_opts: Some(LoadProgramOptions { + load_plugins: true, + k_code_list: vec![src.to_string()], + ..Default::default() + }), + load_builtin: false, + ..Default::default() + })?; + let evaluator = Evaluator::new_with_runtime_ctx(&p.program, context_with_plugin()); + let result = evaluator.run()?; + println!("yaml result {}", result.1); + Ok(()) +}