From c7a7201cfd8bd0b14d59ef737cf24b5b925d7b21 Mon Sep 17 00:00:00 2001 From: despiegk Date: Fri, 4 Apr 2025 14:58:51 +0200 Subject: [PATCH] .. --- herodb/aiprompts/rhaiwrapping.md | 998 +++++++++++++++++- herodb/aiprompts/rhaiwrapping_advanced.md | 134 +++ .../aiprompts/rhaiwrapping_best_practices.md | 187 ++++ 3 files changed, 1310 insertions(+), 9 deletions(-) create mode 100644 herodb/aiprompts/rhaiwrapping_advanced.md create mode 100644 herodb/aiprompts/rhaiwrapping_best_practices.md diff --git a/herodb/aiprompts/rhaiwrapping.md b/herodb/aiprompts/rhaiwrapping.md index e855499..09a12d2 100644 --- a/herodb/aiprompts/rhaiwrapping.md +++ b/herodb/aiprompts/rhaiwrapping.md @@ -1,14 +1,994 @@ -in @src/zaz/rhai -make wrappers for the src/zaz/models and see how to use them from src/zaz/cmd/examples.rs +# Best Practices for Wrapping Rust Functions with Rhai -how to do this you can find in rhaibook/rust +This document provides comprehensive guidance on how to effectively wrap Rust functions with different standard arguments, pass structs, and handle various return types including errors when using the Rhai scripting language. -the wrappers need to be simple and return the result and if an error return a proper error into the rhai environment so the rhai script using the wrappers will get appropriate error +## Table of Contents -all wrapped functions need to be registered into the rhai engine +1. [Introduction](#introduction) +2. [Basic Function Registration](#basic-function-registration) +3. [Working with Different Argument Types](#working-with-different-argument-types) +4. [Passing and Working with Structs](#passing-and-working-with-structs) +5. [Error Handling](#error-handling) +6. [Returning Different Types](#returning-different-types) +7. [Native Function Handling](#native-function-handling) +8. [Advanced Patterns](#advanced-patterns) +9. [Complete Examples](#complete-examples) -keep all code as small as possible +## Introduction -the creation of the db should not be done in the rhai script, -this shouldd be done before we call the rhai script -a db is context outside of the script execution \ No newline at end of file +Rhai is an embedded scripting language for Rust that allows you to expose Rust functions to scripts and vice versa. This document focuses on the best practices for wrapping Rust functions so they can be called from Rhai scripts, with special attention to handling different argument types, structs, and error conditions. + +## Basic Function Registration + +### Simple Function Registration + +The most basic way to register a Rust function with Rhai is using the `register_fn` method: + +```rust +fn add(x: i64, y: i64) -> i64 { + x + y +} + +fn main() -> Result<(), Box> { + let mut engine = Engine::new(); + + // Register the function with Rhai + engine.register_fn("add", add); + + // Now the function can be called from Rhai scripts + let result = engine.eval::("add(40, 2)")?; + + println!("Result: {}", result); // prints 42 + + Ok(()) +} +``` + +### Function Naming Conventions + +When registering functions, follow these naming conventions: + +1. Use snake_case for function names to maintain consistency with Rhai's style +2. Choose descriptive names that clearly indicate the function's purpose +3. For functions that operate on specific types, consider prefixing with the type name (e.g., `string_length`) + +## Working with Different Argument Types + +### Primitive Types + +Rhai supports the following primitive types that can be directly used as function arguments: + +- `i64` (integer) +- `f64` (float) +- `bool` (boolean) +- `String` or `&str` (string) +- `char` (character) +- `()` (unit type) + +Example: + +```rust +fn calculate(num: i64, factor: f64, enabled: bool) -> f64 { + if enabled { + num as f64 * factor + } else { + 0.0 + } +} + +engine.register_fn("calculate", calculate); +``` + +### Arrays and Collections + +For array arguments: + +```rust +fn sum_array(arr: Array) -> i64 { + arr.iter() + .filter_map(|v| v.as_int().ok()) + .sum() +} + +engine.register_fn("sum_array", sum_array); +``` + +### Optional Arguments and Function Overloading + +Rhai supports function overloading, which allows you to register multiple functions with the same name but different parameter types or counts: + +```rust +fn greet(name: &str) -> String { + format!("Hello, {}!", name) +} + +fn greet_with_title(title: &str, name: &str) -> String { + format!("Hello, {} {}!", title, name) +} + +engine.register_fn("greet", greet); +engine.register_fn("greet", greet_with_title); + +// In Rhai: +// greet("World") -> "Hello, World!" +// greet("Mr.", "Smith") -> "Hello, Mr. Smith!" +``` + +## Passing and Working with Structs + +### Registering Custom Types + +To use Rust structs in Rhai, you need to register them: + +#### Method 1: Using the CustomType Trait (Recommended) + +```rust +#[derive(Debug, Clone, CustomType)] +#[rhai_type(extra = Self::build_extra)] +struct TestStruct { + x: i64, +} + +impl TestStruct { + pub fn new() -> Self { + Self { x: 1 } + } + + pub fn update(&mut self) { + self.x += 1000; + } + + pub fn calculate(&mut self, data: i64) -> i64 { + self.x * data + } + + fn build_extra(builder: &mut TypeBuilder) { + builder + .with_name("TestStruct") + .with_fn("new_ts", Self::new) + .with_fn("update", Self::update) + .with_fn("calc", Self::calculate); + } +} + +// In your main function: +let mut engine = Engine::new(); +engine.build_type::(); +``` + +#### Method 2: Manual Registration + +```rust +#[derive(Debug, Clone)] +struct TestStruct { + x: i64, +} + +impl TestStruct { + pub fn new() -> Self { + Self { x: 1 } + } + + pub fn update(&mut self) { + self.x += 1000; + } +} + +let mut engine = Engine::new(); + +engine + .register_type_with_name::("TestStruct") + .register_fn("new_ts", TestStruct::new) + .register_fn("update", TestStruct::update); +``` + +### Accessing Struct Fields + +By default, Rhai can access public fields of registered structs: + +```rust +// In Rhai script: +let x = new_ts(); +x.x = 42; // Direct field access +``` + +### Passing Structs as Arguments + +When passing structs as arguments to functions, ensure they implement the `Clone` trait: + +```rust +fn process_struct(test: TestStruct) -> i64 { + test.x * 2 +} + +engine.register_fn("process_struct", process_struct); +``` + +### Returning Structs from Functions + +You can return custom structs from functions: + +```rust +fn create_struct(value: i64) -> TestStruct { + TestStruct { x: value } +} + +engine.register_fn("create_struct", create_struct); +``` + +## Error Handling + +Error handling is a critical aspect of integrating Rust functions with Rhai. Proper error handling ensures that script execution fails gracefully with meaningful error messages. + +### Basic Error Handling + +The most basic way to handle errors is to return a `Result` type: + +```rust +fn divide(a: i64, b: i64) -> Result> { + if b == 0 { + // Return an error if division by zero + Err("Division by zero".into()) + } else { + Ok(a / b) + } +} + +engine.register_fn("divide", divide); +``` + +### EvalAltResult Types + +Rhai provides several error types through the `EvalAltResult` enum: + +```rust +use rhai::EvalAltResult; +use rhai::Position; + +fn my_function() -> Result> { + // Different error types + + // Runtime error - general purpose error + return Err(Box::new(EvalAltResult::ErrorRuntime( + "Something went wrong".into(), + Position::NONE + ))); + + // Type error - when a type mismatch occurs + return Err(Box::new(EvalAltResult::ErrorMismatchOutputType( + "expected i64, got string".into(), + Position::NONE, + "i64".into() + ))); + + // Function not found error + return Err(Box::new(EvalAltResult::ErrorFunctionNotFound( + "function_name".into(), + Position::NONE + ))); +} +``` + +### Custom Error Types + +For more structured error handling, you can create custom error types: + +```rust +use thiserror::Error; +use rhai::{EvalAltResult, Position}; + +#[derive(Error, Debug)] +enum MyError { + #[error("Invalid input: {0}")] + InvalidInput(String), + + #[error("Calculation error: {0}")] + CalculationError(String), + + #[error("Database error: {0}")] + DatabaseError(String), +} + +// Convert your custom error to EvalAltResult +fn process_data(input: i64) -> Result> { + // Your logic here that might return a custom error + let result = validate_input(input) + .map_err(|e| Box::new(EvalAltResult::ErrorRuntime( + format!("Validation failed: {}", e), + Position::NONE + )))?; + + let processed = calculate(result) + .map_err(|e| Box::new(EvalAltResult::ErrorRuntime( + format!("Calculation failed: {}", e), + Position::NONE + )))?; + + if processed < 0 { + return Err(Box::new(EvalAltResult::ErrorRuntime( + "Negative result not allowed".into(), + Position::NONE + ))); + } + + Ok(processed) +} + +// Helper functions that return our custom error type +fn validate_input(input: i64) -> Result { + if input <= 0 { + return Err(MyError::InvalidInput("Input must be positive".into())); + } + Ok(input) +} + +fn calculate(value: i64) -> Result { + if value > 1000 { + return Err(MyError::CalculationError("Value too large".into())); + } + Ok(value * 2) +} +``` + +### Error Propagation + +When calling Rhai functions from Rust, errors are propagated through the `?` operator: + +```rust +let result = engine.eval::("divide(10, 0)")?; // This will propagate the error +``` + +### Error Context and Position Information + +For better debugging, include position information in your errors: + +```rust +fn parse_config(config: &str) -> Result> { + // Get the call position from the context + let pos = Position::NONE; // In a real function, you'd get this from NativeCallContext + + match serde_json::from_str::(config) { + Ok(json) => { + // Convert JSON to Rhai Map + let mut map = Map::new(); + // ... conversion logic ... + Ok(map) + }, + Err(e) => { + Err(Box::new(EvalAltResult::ErrorRuntime( + format!("Failed to parse config: {}", e), + pos + ))) + } + } +} +``` + +### Best Practices for Error Handling + +1. **Be Specific**: Provide clear, specific error messages that help script writers understand what went wrong +2. **Include Context**: When possible, include relevant context in error messages (e.g., variable values, expected types) +3. **Consistent Error Types**: Use consistent error types for similar issues +4. **Validate Early**: Validate inputs at the beginning of functions to fail fast +5. **Document Error Conditions**: Document possible error conditions for functions exposed to Rhai + + +## Returning Different Types + +Properly handling return types is crucial for creating a seamless integration between Rust and Rhai. This section covers various approaches to returning different types of data from Rust functions to Rhai scripts. + +### Simple Return Types + +For simple return types, specify the type when registering the function: + +```rust +fn get_number() -> i64 { 42 } +fn get_string() -> String { "hello".to_string() } +fn get_boolean() -> bool { true } +fn get_float() -> f64 { 3.14159 } +fn get_char() -> char { 'A' } +fn get_unit() -> () { () } + +engine.register_fn("get_number", get_number); +engine.register_fn("get_string", get_string); +engine.register_fn("get_boolean", get_boolean); +engine.register_fn("get_float", get_float); +engine.register_fn("get_char", get_char); +engine.register_fn("get_unit", get_unit); +``` + +### Dynamic Return Types + +WE SHOULD TRY NOT TO DO THIS + +For functions that may return different types based on conditions, use the `Dynamic` type: + +```rust +fn get_value(which: i64) -> Dynamic { + match which { + 0 => Dynamic::from(42), + 1 => Dynamic::from("hello"), + 2 => Dynamic::from(true), + 3 => Dynamic::from(3.14159), + 4 => { + let mut array = Array::new(); + array.push(Dynamic::from(1)); + array.push(Dynamic::from(2)); + Dynamic::from_array(array) + }, + 5 => { + let mut map = Map::new(); + map.insert("key".into(), "value".into()); + Dynamic::from_map(map) + }, + _ => Dynamic::UNIT, + } +} + +engine.register_fn("get_value", get_value); +``` + +### Returning Collections + +Rhai supports various collection types: + +```rust +// Returning an array +fn get_array() -> Array { + let mut array = Array::new(); + array.push(Dynamic::from(1)); + array.push(Dynamic::from("hello")); + array.push(Dynamic::from(true)); + array +} + +// Returning a map +fn get_map() -> Map { + let mut map = Map::new(); + map.insert("number".into(), 42.into()); + map.insert("string".into(), "hello".into()); + map.insert("boolean".into(), true.into()); + map +} + +// Returning a typed Vec (will be converted to Rhai Array) +fn get_numbers() -> Vec { + vec![1, 2, 3, 4, 5] +} + +// Returning a HashMap (will be converted to Rhai Map) +fn get_config() -> HashMap { + let mut map = HashMap::new(); + map.insert("host".to_string(), "localhost".to_string()); + map.insert("port".to_string(), "8080".to_string()); + map +} + +engine.register_fn("get_array", get_array); +engine.register_fn("get_map", get_map); +engine.register_fn("get_numbers", get_numbers); +engine.register_fn("get_config", get_config); +``` + +### Returning Custom Structs + +For returning custom structs, ensure they implement the `Clone` trait: + +```rust +#[derive(Debug, Clone)] +struct TestStruct { + x: i64, + name: String, + active: bool, +} + +fn create_struct(value: i64, name: &str, active: bool) -> TestStruct { + TestStruct { + x: value, + name: name.to_string(), + active + } +} + +fn get_struct_array() -> Vec { + vec![ + TestStruct { x: 1, name: "one".to_string(), active: true }, + TestStruct { x: 2, name: "two".to_string(), active: false }, + ] +} + +engine.register_type_with_name::("TestStruct") + .register_fn("create_struct", create_struct) + .register_fn("get_struct_array", get_struct_array); +``` + +### Returning Results and Options + +For functions that might fail or return optional values: + +```rust +// Returning a Result +fn divide(a: i64, b: i64) -> Result> { + if b == 0 { + Err("Division by zero".into()) + } else { + Ok(a / b) + } +} + +// Returning an Option (converted to Dynamic) +fn find_item(id: i64) -> Dynamic { + let item = lookup_item(id); + + match item { + Some(value) => value.into(), + None => Dynamic::UNIT, // Rhai has no null, so use () for None + } +} + +// Helper function returning Option +fn lookup_item(id: i64) -> Option { + match id { + 1 => Some(TestStruct { x: 1, name: "one".to_string(), active: true }), + 2 => Some(TestStruct { x: 2, name: "two".to_string(), active: false }), + _ => None, + } +} + +engine.register_fn("divide", divide); +engine.register_fn("find_item", find_item); +``` + +### Serialization and Deserialization + +When working with JSON or other serialized formats: + +```rust +use serde_json::{Value as JsonValue, json}; + +// Return JSON data as a Rhai Map +fn get_json_data() -> Result> { + // Simulate fetching JSON data + let json_data = json!({ + "name": "John Doe", + "age": 30, + "address": { + "street": "123 Main St", + "city": "Anytown" + }, + "phones": ["+1-555-1234", "+1-555-5678"] + }); + + // Convert JSON to Rhai Map + json_to_rhai_value(json_data) + .and_then(|v| v.try_cast::().map_err(|_| "Expected a map".into())) +} + +// Helper function to convert JSON Value to Rhai Dynamic +fn json_to_rhai_value(json: JsonValue) -> Result> { + match json { + JsonValue::Null => Ok(Dynamic::UNIT), + JsonValue::Bool(b) => Ok(b.into()), + JsonValue::Number(n) => { + if n.is_i64() { + Ok(n.as_i64().unwrap().into()) + } else { + Ok(n.as_f64().unwrap().into()) + } + }, + JsonValue::String(s) => Ok(s.into()), + JsonValue::Array(arr) => { + let mut rhai_array = Array::new(); + for item in arr { + rhai_array.push(json_to_rhai_value(item)?); + } + Ok(Dynamic::from_array(rhai_array)) + }, + JsonValue::Object(obj) => { + let mut rhai_map = Map::new(); + for (k, v) in obj { + rhai_map.insert(k.into(), json_to_rhai_value(v)?); + } + Ok(Dynamic::from_map(rhai_map)) + } + } +} + +engine.register_fn("get_json_data", get_json_data); +``` + +### Working with Dynamic Type System + +Understanding how to work with Rhai's Dynamic type system is essential: + +```rust +// Function that examines a Dynamic value and returns information about it +fn inspect_value(value: Dynamic) -> Map { + let mut info = Map::new(); + + // Store the type name + info.insert("type".into(), value.type_name().into()); + + // Store specific type information + if value.is_int() { + info.insert("category".into(), "number".into()); + info.insert("value".into(), value.clone()); + } else if value.is_float() { + info.insert("category".into(), "number".into()); + info.insert("value".into(), value.clone()); + } else if value.is_string() { + info.insert("category".into(), "string".into()); + info.insert("length".into(), value.clone_cast::().len().into()); + info.insert("value".into(), value.clone()); + } else if value.is_array() { + info.insert("category".into(), "array".into()); + info.insert("length".into(), value.clone_cast::().len().into()); + } else if value.is_map() { + info.insert("category".into(), "map".into()); + info.insert("keys".into(), value.clone_cast::().keys().len().into()); + } else if value.is_bool() { + info.insert("category".into(), "boolean".into()); + info.insert("value".into(), value.clone()); + } else { + info.insert("category".into(), "other".into()); + } + + info +} + +engine.register_fn("inspect", inspect_value); +``` + +## Native Function Handling + +When working with native Rust functions in Rhai, there are several important considerations for handling different argument types, especially when dealing with complex data structures and error cases. + +### Native Function Signature + +Native Rust functions registered with Rhai can have one of two signatures: + +1. **Standard Function Signature**: Functions with typed parameters + ```rust + fn my_function(param1: Type1, param2: Type2, ...) -> ReturnType { ... } + ``` + +2. **Dynamic Function Signature**: Functions that handle raw Dynamic values + ```rust + fn my_dynamic_function(context: NativeCallContext, args: &mut [&mut Dynamic]) -> Result> { ... } + ``` + +### Working with Raw Dynamic Arguments + +The dynamic function signature gives you more control but requires manual type checking and conversion: + +```rust +fn process_dynamic_args(context: NativeCallContext, args: &mut [&mut Dynamic]) -> Result> { + // Check number of arguments + if args.len() != 2 { + return Err("Expected exactly 2 arguments".into()); + } + + // Extract and convert the first argument to an integer + let arg1 = args[0].as_int().map_err(|_| "First argument must be an integer".into())?; + + // Extract and convert the second argument to a string + let arg2 = args[1].as_str().map_err(|_| "Second argument must be a string".into())?; + + // Process the arguments + let result = format!("{}: {}", arg2, arg1); + + // Return the result as a Dynamic value + Ok(result.into()) +} + +// Register the function +engine.register_fn("process", process_dynamic_args); +``` + +### Handling Complex Struct Arguments + +When working with complex struct arguments, you have several options: + +#### Option 1: Use typed parameters (recommended for simple cases) + +```rust +#[derive(Clone)] +struct ComplexData { + id: i64, + values: Vec, +} + +fn process_complex(data: &mut ComplexData, factor: f64) -> f64 { + let sum: f64 = data.values.iter().sum(); + data.values.push(sum * factor); + sum * factor +} + +engine.register_fn("process_complex", process_complex); +``` + +#### Option 2: Use Dynamic parameters for more flexibility + +```rust +fn process_complex_dynamic(context: NativeCallContext, args: &mut [&mut Dynamic]) -> Result> { + // Check arguments + if args.len() != 2 { + return Err("Expected exactly 2 arguments".into()); + } + + // Get mutable reference to the complex data + let data = args[0].write_lock::() + .ok_or_else(|| "First argument must be ComplexData".into())?; + + // Get the factor + let factor = args[1].as_float().map_err(|_| "Second argument must be a number".into())?; + + // Process the data + let sum: f64 = data.values.iter().sum(); + data.values.push(sum * factor); + + Ok((sum * factor).into()) +} +``` + +### Handling Variable Arguments + +For functions that accept a variable number of arguments: + +```rust +fn sum_all(context: NativeCallContext, args: &mut [&mut Dynamic]) -> Result> { + let mut total: i64 = 0; + + for arg in args.iter() { + total += arg.as_int().map_err(|_| "All arguments must be integers".into())?; + } + + Ok(total.into()) +} + +engine.register_fn("sum_all", sum_all); + +// In Rhai: +// sum_all(1, 2, 3, 4, 5) -> 15 +// sum_all(10, 20) -> 30 +``` + +### Handling Optional Arguments + +For functions with optional arguments, use function overloading: + +```rust +fn create_person(name: &str) -> Person { + Person { name: name.to_string(), age: 30 } // Default age +} + +fn create_person_with_age(name: &str, age: i64) -> Person { + Person { name: name.to_string(), age } +} + +engine.register_fn("create_person", create_person); +engine.register_fn("create_person", create_person_with_age); + +// In Rhai: +// create_person("John") -> Person with name "John" and age 30 +// create_person("John", 25) -> Person with name "John" and age 25 +``` + +### Handling Default Arguments + +Rhai doesn't directly support default arguments, but you can simulate them: + +```rust +fn configure(options: &mut Map) -> Result<(), Box> { + // Check if certain options exist, if not, set defaults + if !options.contains_key("timeout") { + options.insert("timeout".into(), 30_i64.into()); + } + + if !options.contains_key("retry") { + options.insert("retry".into(), true.into()); + } + + Ok(()) +} + +engine.register_fn("configure", configure); + +// In Rhai: +// let options = #{}; +// configure(options); +// print(options.timeout); // Prints 30 +``` + +### Handling Mutable and Immutable References + +Rhai supports both mutable and immutable references: + +```rust +// Function taking an immutable reference +fn get_name(person: &Person) -> String { + person.name.clone() +} + +// Function taking a mutable reference +fn increment_age(person: &mut Person) { + person.age += 1; +} + +engine.register_fn("get_name", get_name); +engine.register_fn("increment_age", increment_age); +``` + +### Converting Between Rust and Rhai Types + +When you need to convert between Rust and Rhai types: + +```rust +// Convert a Rust HashMap to a Rhai Map +fn create_config() -> Map { + let mut rust_map = HashMap::new(); + rust_map.insert("server".to_string(), "localhost".to_string()); + rust_map.insert("port".to_string(), "8080".to_string()); + + // Convert to Rhai Map + let mut rhai_map = Map::new(); + for (k, v) in rust_map { + rhai_map.insert(k.into(), v.into()); + } + + rhai_map +} + +// Convert a Rhai Array to a Rust Vec +fn process_array(arr: Array) -> Result> { + // Convert to Rust Vec + let rust_vec: Result, _> = arr.iter() + .map(|v| v.as_int().map_err(|_| "Array must contain only integers".into())) + .collect(); + + let numbers = rust_vec?; + Ok(numbers.iter().sum()) +} +``` + +## Complete Examples + +### Example 1: Basic Function Registration and Struct Handling + +```rust +use rhai::{Engine, EvalAltResult, RegisterFn}; + +#[derive(Debug, Clone)] +struct Person { + name: String, + age: i64, +} + +impl Person { + fn new(name: &str, age: i64) -> Self { + Self { + name: name.to_string(), + age, + } + } + + fn greet(&self) -> String { + format!("Hello, my name is {} and I am {} years old.", self.name, self.age) + } + + fn have_birthday(&mut self) { + self.age += 1; + } +} + +fn is_adult(person: &Person) -> bool { + person.age >= 18 +} + +fn main() -> Result<(), Box> { + let mut engine = Engine::new(); + + // Register the Person type + engine + .register_type_with_name::("Person") + .register_fn("new_person", Person::new) + .register_fn("greet", Person::greet) + .register_fn("have_birthday", Person::have_birthday) + .register_fn("is_adult", is_adult); + + // Run a script that uses the Person type + let result = engine.eval::(r#" + let p = new_person("John", 17); + let greeting = p.greet(); + + if !is_adult(p) { + p.have_birthday(); + } + + greeting + " Now I am " + p.age.to_string() + " years old." + "#)?; + + println!("{}", result); + + Ok(()) +} +``` + +### Example 2: Error Handling and Complex Return Types + +```rust +use rhai::{Engine, EvalAltResult, Map, Dynamic}; +use std::collections::HashMap; + +#[derive(Debug, Clone)] +struct Product { + id: i64, + name: String, + price: f64, +} + +fn get_product(id: i64) -> Result> { + match id { + 1 => Ok(Product { id: 1, name: "Laptop".to_string(), price: 999.99 }), + 2 => Ok(Product { id: 2, name: "Phone".to_string(), price: 499.99 }), + _ => Err("Product not found".into()) + } +} + +fn calculate_total(products: Array) -> Result> { + let mut total = 0.0; + + for product_dynamic in products.iter() { + let product = product_dynamic.clone().try_cast::() + .map_err(|_| "Invalid product in array".into())?; + + total += product.price; + } + + Ok(total) +} + +fn get_product_map() -> Map { + let mut map = Map::new(); + + map.insert("laptop".into(), + Dynamic::from(Product { id: 1, name: "Laptop".to_string(), price: 999.99 })); + map.insert("phone".into(), + Dynamic::from(Product { id: 2, name: "Phone".to_string(), price: 499.99 })); + + map +} + +fn main() -> Result<(), Box> { + let mut engine = Engine::new(); + + engine + .register_type_with_name::("Product") + .register_fn("get_product", get_product) + .register_fn("calculate_total", calculate_total) + .register_fn("get_product_map", get_product_map); + + let result = engine.eval::(r#" + let products = []; + + // Try to get products + try { + products.push(get_product(1)); + products.push(get_product(2)); + products.push(get_product(3)); // This will throw an error + } catch(err) { + print(`Error: ${err}`); + } + + // Get products from map + let product_map = get_product_map(); + products.push(product_map.laptop); + + calculate_total(products) + "#)?; + + println!("Total: ${:.2}", result); + + Ok(()) +} +``` diff --git a/herodb/aiprompts/rhaiwrapping_advanced.md b/herodb/aiprompts/rhaiwrapping_advanced.md new file mode 100644 index 0000000..666710a --- /dev/null +++ b/herodb/aiprompts/rhaiwrapping_advanced.md @@ -0,0 +1,134 @@ + +### Error Handling in Dynamic Functions + +When working with the dynamic function signature, error handling is slightly different: + +```rust +fn dynamic_function(ctx: NativeCallContext, args: &mut [&mut Dynamic]) -> Result> { + // Get the position information from the context + let pos = ctx.position(); + + // Validate arguments + if args.len() < 2 { + return Err(Box::new(EvalAltResult::ErrorRuntime( + format!("Expected at least 2 arguments, got {}", args.len()), + pos + ))); + } + + // Try to convert arguments with proper error handling + let arg1 = match args[0].as_int() { + Ok(val) => val, + Err(_) => return Err(Box::new(EvalAltResult::ErrorMismatchOutputType( + "Expected first argument to be an integer".into(), + pos, + "i64".into() + ))) + }; + + // Process with error handling + if arg1 <= 0 { + return Err(Box::new(EvalAltResult::ErrorRuntime( + "First argument must be positive".into(), + pos + ))); + } + + // Return success + Ok(Dynamic::from(arg1 * 2)) +} +``` + + +## Advanced Patterns + +### Working with Function Pointers + +You can create function pointers that bind to Rust functions: + +```rust +fn my_awesome_fn(ctx: NativeCallContext, args: &mut[&mut Dynamic]) -> Result> { + // Check number of arguments + if args.len() != 2 { + return Err("one argument is required, plus the object".into()); + } + + // Get call arguments + let x = args[1].try_cast::().map_err(|_| "argument must be an integer".into())?; + + // Get mutable reference to the object map, which is passed as the first argument + let map = &mut *args[0].as_map_mut().map_err(|_| "object must be a map".into())?; + + // Do something awesome here ... + let result = x * 2; + + Ok(result.into()) +} + +// Register a function to create a pre-defined object +engine.register_fn("create_awesome_object", || { + // Use an object map as base + let mut map = Map::new(); + + // Create a function pointer that binds to 'my_awesome_fn' + let fp = FnPtr::from_fn("awesome", my_awesome_fn)?; + // ^ name of method + // ^ native function + + // Store the function pointer in the object map + map.insert("awesome".into(), fp.into()); + + Ok(Dynamic::from_map(map)) +}); +``` + +### Creating Rust Closures from Rhai Functions + +You can encapsulate a Rhai script as a Rust closure: + +```rust +use rhai::{Engine, Func}; + +let engine = Engine::new(); + +let script = "fn calc(x, y) { x + y.len < 42 }"; + +// Create a Rust closure from a Rhai function +let func = Func::<(i64, &str), bool>::create_from_script( + engine, // the 'Engine' is consumed into the closure + script, // the script + "calc" // the entry-point function name +)?; + +// Call the closure +let result = func(123, "hello")?; + +// Pass it as a callback to another function +schedule_callback(func); +``` + +### Calling Rhai Functions from Rust + +You can call Rhai functions from Rust: + +```rust +// Compile the script to AST +let ast = engine.compile(script)?; + +// Create a custom 'Scope' +let mut scope = Scope::new(); + +// Add variables to the scope +scope.push("my_var", 42_i64); +scope.push("my_string", "hello, world!"); +scope.push_constant("MY_CONST", true); + +// Call a function defined in the script +let result = engine.call_fn::(&mut scope, &ast, "hello", ("abc", 123_i64))?; + +// For a function with one parameter, use a tuple with a trailing comma +let result = engine.call_fn::(&mut scope, &ast, "hello", (123_i64,))?; + +// For a function with no parameters +let result = engine.call_fn::(&mut scope, &ast, "hello", ())?; +``` diff --git a/herodb/aiprompts/rhaiwrapping_best_practices.md b/herodb/aiprompts/rhaiwrapping_best_practices.md new file mode 100644 index 0000000..17d0a92 --- /dev/null +++ b/herodb/aiprompts/rhaiwrapping_best_practices.md @@ -0,0 +1,187 @@ +## Best Practices and Optimization + +When wrapping Rust functions for use with Rhai, following these best practices will help you create efficient, maintainable, and robust code. + +### Performance Considerations + +1. **Minimize Cloning**: Rhai often requires cloning data, but you can minimize this overhead: + ```rust + // Prefer immutable references when possible + fn process_data(data: &MyStruct) -> i64 { + // Work with data without cloning + data.value * 2 + } + + // Use mutable references for in-place modifications + fn update_data(data: &mut MyStruct) { + data.value += 1; + } + ``` + +2. **Avoid Excessive Type Conversions**: Converting between Rhai's Dynamic type and Rust types has overhead: + ```rust + // Inefficient - multiple conversions + fn process_inefficient(ctx: NativeCallContext, args: &mut [&mut Dynamic]) -> Result> { + let value = args[0].as_int()?; + let result = value * 2; + Ok(Dynamic::from(result)) + } + + // More efficient - use typed parameters when possible + fn process_efficient(value: i64) -> i64 { + value * 2 + } + ``` + +3. **Batch Operations**: For operations on collections, batch processing is more efficient: + ```rust + // Process an entire array at once rather than element by element + fn sum_array(arr: Array) -> Result> { + arr.iter() + .map(|v| v.as_int()) + .collect::, _>>() + .map(|nums| nums.iter().sum()) + .map_err(|_| "Array must contain only integers".into()) + } + ``` + +4. **Compile Scripts Once**: Reuse compiled ASTs for scripts that are executed multiple times: + ```rust + // Compile once + let ast = engine.compile(script)?; + + // Execute multiple times with different parameters + for i in 0..10 { + let result = engine.eval_ast::(&ast)?; + println!("Result {}: {}", i, result); + } + ``` + +### Thread Safety + +1. **Use Sync Mode When Needed**: If you need thread safety, use the `sync` feature: + ```rust + // In Cargo.toml + // rhai = { version = "1.x", features = ["sync"] } + + // This creates a thread-safe engine + let engine = Engine::new(); + + // Now you can safely share the engine between threads + std::thread::spawn(move || { + let result = engine.eval::("40 + 2")?; + println!("Result: {}", result); + }); + ``` + +2. **Clone the Engine for Multiple Threads**: When not using `sync`, clone the engine for each thread: + ```rust + let engine = Engine::new(); + + let handles: Vec<_> = (0..5).map(|i| { + let engine_clone = engine.clone(); + std::thread::spawn(move || { + let result = engine_clone.eval::(&format!("{} + 2", i * 10))?; + println!("Thread {}: {}", i, result); + }) + }).collect(); + + for handle in handles { + handle.join().unwrap(); + } + ``` + +### Memory Management + +1. **Control Scope Size**: Be mindful of the size of your scopes: + ```rust + // Create a new scope for each operation to avoid memory buildup + for item in items { + let mut scope = Scope::new(); + scope.push("item", item); + engine.eval_with_scope::<()>(&mut scope, "process(item)")?; + } + ``` + +2. **Limit Script Complexity**: Use engine options to limit script complexity: + ```rust + let mut engine = Engine::new(); + + // Set limits to prevent scripts from consuming too many resources + engine.set_max_expr_depths(64, 64) // Max expression/statement depth + .set_max_function_expr_depth(64) // Max function depth + .set_max_array_size(10000) // Max array size + .set_max_map_size(10000) // Max map size + .set_max_string_size(10000) // Max string size + .set_max_call_levels(64); // Max call stack depth + ``` + +3. **Use Shared Values Carefully**: Shared values (via closures) have reference-counting overhead: + ```rust + // Avoid unnecessary capturing in closures when possible + engine.register_fn("process", |x: i64| x * 2); + + // Instead of capturing large data structures + let large_data = vec![1, 2, 3, /* ... thousands of items ... */]; + engine.register_fn("process_data", move |idx: i64| { + if idx >= 0 && (idx as usize) < large_data.len() { + large_data[idx as usize] + } else { + 0 + } + }); + + // Consider registering a lookup function instead + let large_data = std::sync::Arc::new(vec![1, 2, 3, /* ... thousands of items ... */]); + let data_ref = large_data.clone(); + engine.register_fn("lookup", move |idx: i64| { + if idx >= 0 && (idx as usize) < data_ref.len() { + data_ref[idx as usize] + } else { + 0 + } + }); + ``` + +### API Design + +1. **Consistent Naming**: Use consistent naming conventions: + ```rust + // Good: Consistent naming pattern + engine.register_fn("create_user", create_user) + .register_fn("update_user", update_user) + .register_fn("delete_user", delete_user); + + // Bad: Inconsistent naming + engine.register_fn("create_user", create_user) + .register_fn("user_update", update_user) + .register_fn("remove", delete_user); + ``` + +2. **Logical Function Grouping**: Group related functions together: + ```rust + // Register all string-related functions together + engine.register_fn("str_length", |s: &str| s.len() as i64) + .register_fn("str_uppercase", |s: &str| s.to_uppercase()) + .register_fn("str_lowercase", |s: &str| s.to_lowercase()); + + // Register all math-related functions together + engine.register_fn("math_sin", |x: f64| x.sin()) + .register_fn("math_cos", |x: f64| x.cos()) + .register_fn("math_tan", |x: f64| x.tan()); + ``` + +3. **Comprehensive Documentation**: Document your API thoroughly: + ```rust + // Add documentation for script writers + let mut engine = Engine::new(); + + #[cfg(feature = "metadata")] + { + // Add function documentation + engine.register_fn("calculate_tax", calculate_tax) + .register_fn_metadata("calculate_tax", |metadata| { + metadata.set_doc_comment("Calculates tax based on income and rate.\n\nParameters:\n- income: Annual income\n- rate: Tax rate (0.0-1.0)\n\nReturns: Calculated tax amount"); + }); + } + ```