1
0
Fork 0
forked from fun/fun

Rust doc fixes. No code changes. (0.38.5)

This commit is contained in:
Johannes Findeisen 2026-01-29 15:13:01 +01:00
commit 5fdd02f3a6

View file

@ -1,104 +1,197 @@
#endif # Writing Rust-backed opcodes for Fun VM
case OP_RADD: { This guide explains how to implement VM opcodes in Rust, wire them into the C VM, and use them from Fun scripts.
#ifdef FUN_WITH_RUST
(void)fun_op_radd(vm); It assumes you are comfortable with basic Rust and C and have a working Fun checkout.
#else
vm_raise_error(vm, "RADD requires FUN_WITH_RUST=ON at build time"); ## Overview
push_value(vm, make_nil()); // or follow your opcodes error convention
#endif Funs VM is written in C, but you can implement opcode handlers in Rust and call them via FFI. The typical flow is:
break;
} 1) Write a Rust function with a stable C ABI (extern "C", #[no_mangle]) that takes a pointer to the VM and returns an int status code.
2) Use VM stack helpers (exposed to Rust via FFI) to pop arguments and push results.
Notes: 3) Expose that Rust function to the C VM by calling it from the opcode dispatch (a case in the VMs opcode switch or a small shim under src/vm/rust/).
- Follow the existing opcode conventions for your module (core, math, strings, etc.). 4) Add or reuse a Fun builtin that maps to your opcode, then call it from Fun code.
- If your build puts the Rust symbol into a static library, make sure the VM target links it when FUN_WITH_RUST is ON (the top-level CMake already does this for the examples provided).
## Project layout (relevant parts)
## Using Rust-backed opcodes from Fun
- src/rust/src/lib.rs — Rust library with exported opcode functions and FFI helpers.
Once wired, expose the opcode via a builtin function or directly in bytecode. The repository includes a demo builtin rust_hello() that returns a Rust-generated string. - src/vm/rust/ — C-side wiring examples and small opcode cases calling into Rust.
- examples/rust_hello.fun — Example Fun script using a Rust-backed opcode.
Run the example: - docs/opcodes.md — General overview of many built-in opcodes (mostly C-based).
1) Build with Rust enabled (Debug): ## Enabling Rust in the build
cmake -S . -B build_debug -DFUN_WITH_RUST=ON
cmake --build build_debug --target fun Rust integration is optional and gated by a CMake flag. Default builds usually have it OFF.
2) Execute the script: Enable it for a configured profile (Debug or Release):
build_debug/fun examples/rust_hello.fun
- Debug example:
Expected output: cmake -S . -B build_debug -DFUN_WITH_RUST=ON
Hello from Rust ops! cmake --build build_debug --target fun
If you build without Rust, calling rust_hello() raises a runtime error indicating that Rust integration is disabled. - Release example:
cmake -S . -B build_release -DFUN_WITH_RUST=ON
## Stack discipline and error handling cmake --build build_release --target fun
- Always pop exactly the arguments you expect and push exactly the results your opcode promises. Mismatch leads to stack corruption and hard-to-debug failures. Useful targets in this repository include:
- Return an int status to the VM (0 for success). If your project uses a different convention for some opcodes, match it consistently. - fun — the main executable
- Validate types where appropriate (e.g., ensure values are integers before arithmetic). If a check fails, use the VMs error mechanism (e.g., vm_raise_error) and follow the modules convention on what to push after errors. - rust_ops_build — helps build/link Rust ops when enabled
- test_opcodes — test executable (if you want to extend tests)
## Data types and FFI surface
Note: In CLion, prefer building with one of the provided CMake profiles (Debug/Release) and avoid creating custom build directories.
The minimal helpers shown cover 64-bit integers and simple strings. Extending the Rust<->C bridge usually involves:
- Declaring additional extern "C" functions in Rust that the C VM implements (to read/write values on the stack, construct arrays/maps/strings, etc.). ## Writing an opcode in Rust
- Ensuring all pointers and lifetimes are well-defined: strings pushed to the VM should be copied or allocated using VM facilities so they remain valid after the call.
- Keeping Rust no_std unless you add an allocator and link setup to support std. The Rust side is a no_std static library exposing C ABI functions that the VM can call. See src/rust/src/lib.rs for examples already in the tree.
## Troubleshooting Key points:
- Use extern "C" and #[no_mangle] to fix the symbol name.
- Link errors: Make sure FUN_WITH_RUST=ON for your build directory and that the Rust library is compiled before linking the VM. Use the rust_ops_build target if provided by your profile. - Take a raw pointer to the VM as *mut Vm; return i32 status (0 for success).
- Missing symbol at runtime: Confirm #[no_mangle] and extern "C" on the Rust function and that C sees the correct prototype. - Interact with the VM stack via helper FFI functions declared as externs.
- Wrong or garbled values: Double-check stack order (Fun uses a stack VM; many ops pop in reverse order: first b, then a). - Provide a minimal panic handler (no_std) as shown in lib.rs.
- No output from rust_hello(): Ensure you run a binary built with FUN_WITH_RUST=ON; otherwise the VM deliberately raises an error and returns Nil for that call.
Example: integer addition opcode implemented in Rust.
## Small end-to-end checklist
In src/rust/src/lib.rs:
1) Write the Rust function in src/rust/src/lib.rs with extern "C", #[no_mangle].
2) Use FFI helpers to pop arguments and push results. #![no_std]
3) Add a C-side case under src/vm/... (or src/vm/rust/...) that calls your Rust function when the opcode executes.
4) Ensure the build links Rust code when FUN_WITH_RUST=ON. #[repr(C)]
5) Add or reuse a builtin in the parser/runtime to surface your opcode to Fun code. pub struct Vm;
6) Build and run a small .fun example to validate behavior.
extern "C" {
## References in this repo fn vm_pop_i64(vm: *mut Vm) -> i64;
fn vm_push_i64(vm: *mut Vm, v: i64);
- Rust lib with examples: src/rust/src/lib.rs }
- C-side hello wiring: src/vm/rust/hello.c
- Demo script: examples/rust_hello.fun #[no_mangle]
- General opcode reference: docs/opcodes.md pub extern "C" fn fun_op_radd(vm: *mut Vm) -> i32 {
unsafe {
## Links let b = vm_pop_i64(vm);
let a = vm_pop_i64(vm);
Authoritative and practical resources on exposing Rust to C (FFI) and maintaining a C-compatible API: vm_push_i64(vm, a + b);
}
- Rustonomicon: FFI overview and best practices 0
https://doc.rust-lang.org/nomicon/ffi.html }
- Rustonomicon: Calling Rust code from C
https://doc.rust-lang.org/nomicon/ffi.html#calling-rust-code-from-c #[panic_handler]
- The Rust Book: Unsafe and FFI (extern, #[no_mangle], calling Rust from other languages) fn panic(_info: &core::panic::PanicInfo) -> ! { loop {} }
https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html#calling-rust-functions-from-other-languages
- Rust Reference: extern blocks, ABIs, and linkage What this does:
https://doc.rust-lang.org/reference/items/external-blocks.html - Pops two 64-bit integers from the VM stack.
- Rust FFI Omnibus (examples for many patterns, including Rust ↔ C) - Pushes back their sum.
https://github.com/shepmaster/rust-ffi-omnibus - Returns 0 to indicate success to the VM.
- cbindgen (generate C headers from Rust libraries)
https://cbindgen.github.io/cbindgen/ You can add more extern helpers (e.g., for strings, arrays, maps) once they are exposed by the C VM. The repository already includes a simple string example returning a const char* from Rust, see fun_rust_get_string() usage below.
- bindgen (generate Rust bindings to existing C headers; useful when mixing C and Rust)
https://github.com/rust-lang/rust-bindgen ## Wiring the opcode in C
## Return-only Rust string helper To make the VM call your Rust opcode, add a small C-side case that invokes the exported Rust symbol. A minimal pattern lives under src/vm/rust/.
Two variants are available for passing a string to Rust and getting output: String demo wiring (already present): src/vm/rust/hello.c
- rust_hello_args(msg) case OP_RUST_HELLO: {
- Rust side prints the message to stdout; Fun receives Nil. Use when you only want side-effect printing. #ifdef FUN_WITH_RUST
- rust_hello_args_return(msg) const char *s = fun_rust_get_string();
- Rust side does not print; it returns the provided string to Fun (useful for assignment or chaining). if (!s) s = "";
push_value(vm, make_string(s));
Example: #else
vm_raise_error(vm, "RUST_HELLO requires FUN_WITH_RUST=ON at build time");
msg = rust_hello_args_return("Hello back from Rust (no print)!") push_value(vm, make_nil());
print(msg) #endif
break;
See examples/rust_hello_args_return.fun for a complete script. }
For a stack-based math opcode (like fun_op_radd), you would declare and call the Rust function similarly:
#ifdef FUN_WITH_RUST
extern int fun_op_radd(void* vm); // or use the proper VM type if available
#endif
case OP_RADD: {
#ifdef FUN_WITH_RUST
(void)fun_op_radd(vm);
#else
vm_raise_error(vm, "RADD requires FUN_WITH_RUST=ON at build time");
push_value(vm, make_nil()); // or follow your opcodes error convention
#endif
break;
}
Notes:
- Follow the existing opcode conventions for your module (core, math, strings, etc.).
- If your build puts the Rust symbol into a static library, make sure the VM target links it when FUN_WITH_RUST is ON (the top-level CMake already does this for the examples provided).
## Using Rust-backed opcodes from Fun
Once wired, expose the opcode via a builtin function or directly in bytecode. The repository includes a demo builtin rust_hello() that returns a Rust-generated string.
Run the example:
1) Build with Rust enabled (Debug):
cmake -S . -B build_debug -DFUN_WITH_RUST=ON
cmake --build build_debug --target fun
2) Execute the script:
build_debug/fun examples/rust_hello.fun
Expected output:
Hello from Rust ops!
If you build without Rust, calling rust_hello() raises a runtime error indicating that Rust integration is disabled.
## Stack discipline and error handling
- Always pop exactly the arguments you expect and push exactly the results your opcode promises. Mismatch leads to stack corruption and hard-to-debug failures.
- Return an int status to the VM (0 for success). If your project uses a different convention for some opcodes, match it consistently.
- Validate types where appropriate (e.g., ensure values are integers before arithmetic). If a check fails, use the VMs error mechanism (e.g., vm_raise_error) and follow the modules convention on what to push after errors.
## Data types and FFI surface
The minimal helpers shown cover 64-bit integers and simple strings. Extending the Rust<->C bridge usually involves:
- Declaring additional extern "C" functions in Rust that the C VM implements (to read/write values on the stack, construct arrays/maps/strings, etc.).
- Ensuring all pointers and lifetimes are well-defined: strings pushed to the VM should be copied or allocated using VM facilities so they remain valid after the call.
- Keeping Rust no_std unless you add an allocator and link setup to support std.
## Troubleshooting
- Link errors: Make sure FUN_WITH_RUST=ON for your build directory and that the Rust library is compiled before linking the VM. Use the rust_ops_build target if provided by your profile.
- Missing symbol at runtime: Confirm #[no_mangle] and extern "C" on the Rust function and that C sees the correct prototype.
- Wrong or garbled values: Double-check stack order (Fun uses a stack VM; many ops pop in reverse order: first b, then a).
- No output from rust_hello(): Ensure you run a binary built with FUN_WITH_RUST=ON; otherwise the VM deliberately raises an error and returns Nil for that call.
## Small end-to-end checklist
1) Write the Rust function in src/rust/src/lib.rs with extern "C", #[no_mangle].
2) Use FFI helpers to pop arguments and push results.
3) Add a C-side case under src/vm/... (or src/vm/rust/...) that calls your Rust function when the opcode executes.
4) Ensure the build links Rust code when FUN_WITH_RUST=ON.
5) Add or reuse a builtin in the parser/runtime to surface your opcode to Fun code.
6) Build and run a small .fun example to validate behavior.
## References in this repo
- Rust lib with examples: src/rust/src/lib.rs
- C-side hello wiring: src/vm/rust/hello.c
- Demo script: examples/rust_hello.fun
- General opcode reference: docs/opcodes.md
## Links
Authoritative and practical resources on exposing Rust to C (FFI) and maintaining a C-compatible API:
- Rustonomicon: FFI overview and best practices
https://doc.rust-lang.org/nomicon/ffi.html
- Rustonomicon: Calling Rust code from C
https://doc.rust-lang.org/nomicon/ffi.html#calling-rust-code-from-c
- The Rust Book: Unsafe and FFI (extern, #[no_mangle], calling Rust from other languages)
https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html#calling-rust-functions-from-other-languages
- Rust Reference: extern blocks, ABIs, and linkage
https://doc.rust-lang.org/reference/items/external-blocks.html
- Rust FFI Omnibus (examples for many patterns, including Rust ↔ C)
https://github.com/shepmaster/rust-ffi-omnibus
- cbindgen (generate C headers from Rust libraries)
https://cbindgen.github.io/cbindgen/
- bindgen (generate Rust bindings to existing C headers; useful when mixing C and Rust)
https://github.com/rust-lang/rust-bindgen