|
| 1 | +use anyhow::{anyhow, Result}; |
| 2 | +use kclvm_evaluator::Evaluator; |
| 3 | +use kclvm_loader::{load_packages, LoadPackageOptions}; |
| 4 | +use kclvm_parser::LoadProgramOptions; |
| 5 | +use kclvm_runtime::{Context, IndexMap, PluginFunction, ValueRef}; |
| 6 | +use std::{cell::RefCell, rc::Rc, sync::Arc}; |
| 7 | + |
| 8 | +fn my_plugin_sum(_: &Context, args: &ValueRef, _: &ValueRef) -> Result<ValueRef> { |
| 9 | + let a = args |
| 10 | + .arg_i_int(0, Some(0)) |
| 11 | + .ok_or(anyhow!("expect int value for the first param"))?; |
| 12 | + let b = args |
| 13 | + .arg_i_int(1, Some(0)) |
| 14 | + .ok_or(anyhow!("expect int value for the second param"))?; |
| 15 | + Ok((a + b).into()) |
| 16 | +} |
| 17 | + |
| 18 | +fn context_with_plugin() -> Rc<RefCell<Context>> { |
| 19 | + let mut plugin_functions: IndexMap<String, PluginFunction> = Default::default(); |
| 20 | + let func = Arc::new(my_plugin_sum); |
| 21 | + plugin_functions.insert("my_plugin.add".to_string(), func); |
| 22 | + let mut ctx = Context::new(); |
| 23 | + ctx.plugin_functions = plugin_functions; |
| 24 | + Rc::new(RefCell::new(ctx)) |
| 25 | +} |
| 26 | + |
| 27 | +#[test] |
| 28 | +fn test_exec_with_plugin() -> Result<()> { |
| 29 | + let src = r#" |
| 30 | +import kcl_plugin.my_plugin |
| 31 | +
|
| 32 | +sum = my_plugin.add(1, 1) |
| 33 | +"#; |
| 34 | + let p = load_packages(&LoadPackageOptions { |
| 35 | + paths: vec!["test.k".to_string()], |
| 36 | + load_opts: Some(LoadProgramOptions { |
| 37 | + load_plugins: true, |
| 38 | + k_code_list: vec![src.to_string()], |
| 39 | + ..Default::default() |
| 40 | + }), |
| 41 | + load_builtin: false, |
| 42 | + ..Default::default() |
| 43 | + })?; |
| 44 | + let evaluator = Evaluator::new_with_runtime_ctx(&p.program, context_with_plugin()); |
| 45 | + let result = evaluator.run()?; |
| 46 | + println!("yaml result {}", result.1); |
| 47 | + Ok(()) |
| 48 | +} |
0 commit comments