RFC-021: Library-Driven FFI Extension and Cross-Language Call Support
⚠️ Deprecated: This document is deprecated; its content has been merged into RFC-026: FFI Core Mechanism.
References:
Summary
This document proposes a library-driven FFI (Foreign Function Interface) extension scheme. The sole entry point for FFI is the native("symbol") declaration plus the FfiRegistry runtime registry, with no second mechanism introduced into the core. On top of this, capabilities such as dynamic library loading and cross-language call bindings are provided through the standard library. Bindings for specific languages (such as C, Python, JavaScript) are automatically generated by the official toolchain or written on demand by individual projects.
Motivation
Shortcomings of the Current Implementation
The current FFI implementation already has the following capabilities:
native("symbol")syntax to declare external functionsFfiRegistryfunction registry
But its functionality is relatively limited:
- Lacks dynamic library loading support
- No infrastructure for cross-language calls
- No automated binding generation tool
Design Philosophy
YaoXiang follows the principle of "a simple core, with complexity sunk into libraries":
Good Taste: The language's job is to provide atomic capabilities, not an all-encompassing feature set. Complexity should be solved through libraries, not piled up in the compiler.
Therefore, this plan:
- ✅ Zero syntax changes — Fully backward compatible; the only FFI entry point is
native("symbol") - ✅ Libraries as language — Features are extended through the standard library
- ✅ Toolchain automation — Bindings are auto-generated by
yx-bindgen, not hand-maintained - ✅ Progressive enhancement — Developers introduce features as needed
Proposal
1. Core FFI Library Enhancement
Extend the std.ffi module. Note: all calls to external functions still go through the native("symbol") declaration; std.ffi only provides auxiliary capabilities.
1.1 Dynamic Library Loading
import ffi
# Load dynamic library (.so/.dll/.dylib)
lib = ffi.load_library("./libmyext.so")
# Get function symbols from the library, returning a symbol name usable as native
ffi.register_library_symbols(lib, [
"my_function",
"another_func",
])load_library returns a DynamicLibrary handle, and register_library_symbols registers the symbol names into the FfiRegistry's known table. Afterwards, the user still uses them through the native declaration:
my_func: (a: Int, b: Int) -> Int = native("my_function")No second calling syntax, no try_call wrapper.
1.2 Library Management
# List loaded libraries
loaded = ffi.loaded_libraries()
# Unload a library
ffi.unload_library(lib)
# Library version check
ffi.check_version(lib, "1.0.0")1.3 Symbol Resolution
# Look up a symbol by name (returns a Symbol struct)
sin_sym = ffi.dlsym("libm.so", "sin")Cross-language calling conventions and type conversions are not handled through a generic wrapper at runtime; they are generated at compile time by yx-bindgen.
2. Dynamic Library Loading Implementation
2.1 Core Data Structures
pub struct DynamicLibrary {
handle: *mut std::ffi::c_void,
path: String,
}
impl DynamicLibrary {
pub fn load(path: &str) -> Result<Self, FfiError>;
pub fn get_symbol(&self, name: &str) -> Result<*mut std::ffi::c_void, FfiError>;
pub fn unload(self) -> Result<(), FfiError>;
}2.2 Error Type
pub enum FfiError {
LibraryNotFound { name: String, os_error: Option<OsError> },
SymbolNotFound { name: String, os_error: Option<OsError> },
CallFailed { message: String, os_error: Option<OsError> },
Timeout,
}
pub struct OsError {
pub code: i32,
pub message: String,
}OsError carries the platform-native error code (Linux's dlerror(), Windows's GetLastError()), ensuring debuggability.
3. Multi-Language Binding: The Toolchain Approach
Abandon the fantasy of "each language's community maintainer writing binding libraries". Switch to automatic generation by the official toolchain instead.
3.1 Architecture Design
┌───────────────────────────────────────────────┐
│ YaoXiang code │
│ │
│ // The user only writes native declarations │
│ my_func: (a: Int) -> Int = native("my_func") │
└───────────────────────────────────────────────┘
↑ ↑
| Compile time | Runtime
┌──────────────────┐ ┌────────────────────────┐
│ yx-bindgen │ │ std.ffi + FfiRegistry │
│ (C header → .yx) │ │ - dlopen/dlsym │
│ │ │ - LoadLibrary/GetProc │
└──────────────────┘ └────────────────────────┘3.2 Binding Generator (yx-bindgen)
yx-bindgen is a standalone CLI tool that generates YaoXiang FFI binding code from C header files:
yx-bindgen --header /usr/include/sqlite3.h --output sqlite3.yxExample generated output:
# Auto-generated, do not edit manually
# Source: /usr/include/sqlite3.h
sqlite3_open: (filename: *const u8, ppDb: *mut *mut opaque) -> Int
= native("sqlite3_open")
sqlite3_close: (db: *mut opaque) -> Int
= native("sqlite3_close")
sqlite3_exec: (
db: *mut opaque,
sql: *const u8,
callback: *mut opaque,
arg: *mut opaque,
errmsg: *mut *mut u8,
) -> Int
= native("sqlite3_exec")yx-bindgen is maintained officially, ensuring:
- Complete type mapping (
int→Int,char*→*const u8,void*→*mut opaque) - Struct layout alignment (automatic
#[repr(C)]equivalent) - Callback signature conversion
3.3 Officially Maintained Binding Packages
The YaoXiang core team does not commit to maintaining generic binding libraries for all languages, but provides an official libc binding package (POSIX + Windows API subset) as a best-practice FFI example and foundational capability.
Bindings for other languages and libraries:
- Use
yx-bindgento generate them yourself - Can be published as YaoXiang packages (e.g.,
libsqlite3,libcurl,libsdl2) - The core team is not responsible for maintenance, but provides package publishing and version management mechanisms
4. Type Conversion Layer
4.1 Compile-Time Type Mapping
Type conversions are not handled through runtime wrappers; they are decided statically during yx-bindgen generation:
| C type | YaoXiang type | Conversion method |
|---|---|---|
int | Int | Pass by value |
char* | *const u8 | Pointer passing |
void* | *mut opaque | Opaque pointer |
struct T | extern struct T | Memory layout match |
int* | *mut Int | Pointer passing (mut) |
const int* | *const Int | Pointer passing (read) |
4.2 Manual Conversion (Standard Library Helper)
# Explicit conversion
raw_ptr = ffi.to_pointer(my_bytes)
c_string = ffi.to_c_string(my_string)5. Memory Ownership Model
5.1 Basic Principles
Every memory allocation crossing the FFI boundary must explicitly answer two questions:
- Who allocates? (C-side
malloc/ YaoXiang-side runtime) - Who frees? (C-side
free/ YaoXiang-side runtime)
yx-bindgen adds annotations to common patterns during generation:
# C-allocated, caller frees
sqlite3_exec: (...) -> Int
= native("sqlite3_exec")
# memory: C-allocated, caller must free errmsg via sqlite3_free
# Caller-allocated pointer
read: (fd: Int, buf: *mut u8, count: Int) -> Int
= native("read")
# memory: caller-allocated bufThe runtime does not perform automatic memory management on pointer references crossing the FFI boundary — ownership is clearly placed on the caller.
5.2 String Handling
A char* returned by a C function is copied immediately when converted to a YaoXiang String. The ownership of the original pointer is determined by the C function (declared via annotations) and is not released automatically.
6. Safety Considerations
6.1 Concurrency Safety
FFI function calls do not participate in DAG scheduling by default and are treated as blocking operations. C functions confirmed to be reentrant can be marked as @concurrent:
# Pure function, no global state, safe for concurrent use
sin_safe: (x: Float) -> Float = native("sin")
# reentrant: true
# Has global state, not safe for concurrent use
strtok: (s: *const u8, delim: *const u8) -> *const u8 = native("strtok")
# reentrant: falseyx-bindgen annotates reentrancy information for standard C library functions as much as possible (e.g., the _r variants of strtok).
Requirement for async callers: Before calling an FFI function, the caller must ensure that the target function is reentrant. The runtime does not perform automatic detection — this is a problem that cannot be solved statically.
6.2 Error Isolation
- FFI call errors are propagated through the
Resulttype (if the function declares a Result return type) - Timeout mechanisms prevent external function deadlocks
# Call with timeout (implemented at the FfiRegistry layer)
result = ffi.call_with_timeout("blocking_func", 5000) # 5-second timeout6.3 Pointer Safety
- Pointer parameters require the
unsafemarker on the YaoXiang side - The lifetime of pointers crossing the FFI boundary is guaranteed by the caller
7. Compiler Changes
Zero syntax changes — only the native("symbol") declaration is required, already implemented in the current compiler.
Additions to the interpreter/runtime:
- Dynamic library loading instructions (FFI binding for
DynamicLibrary) - Timeout mechanism
8. Features Not Accepted
The following features are explicitly excluded after review and are no longer incorporated into the RFC:
ffi.try_call: Redundant,native+Resultreturn type already existsffi.verify_signature: Doing the compiler's job at runtime is the wrong abstraction layerffi.async_call: Wait until the reentrancy contract model is clarified- Community-maintained binding table: Not enforceable; switched to the
yx-bindgentoolchain approach
Trade-offs
Advantages
- ✅ Zero syntax changes — The only FFI entry point is
native("symbol"), fully backward compatible - ✅ Libraries as language — Features are introduced progressively through the standard library
- ✅ Toolchain-driven —
yx-bindgenautomatically handles binding generation - ✅ Memory safety — Clear ownership model, no use-after-free caused by automatic reclamation
- ✅ Debuggable — Errors carry OS-native error codes
Disadvantages
- ⚠️ Type safety is limited by the expressiveness of C header files (
void*cannot be statically distinguished) - ⚠️
yx-bindgenrequires ongoing maintenance to keep up with C standard evolution - ⚠️ Bindings for non-C languages (Python/JS/Java) need to be handled by individual projects; no unified solution
Implementation Strategy
Phase 1: Core Library (v0.7)
- [ ] Extend the
std.ffimodule - [ ] Implement the
DynamicLibrarystruct - [ ] Support Linux/macOS (
dlopen/dlsym) - [ ] Support Windows (
LoadLibrary/GetProcAddress) - [ ] Add timeout mechanism to the runtime
- [ ] Unit tests
Phase 2: yx-bindgen (v0.8)
- [ ] Implement C header file parser (based on existing Clang binding or hand-written parser)
- [ ] Type mapping system
- [ ] Generate
native("symbol")declarations - [ ] Generate struct layouts
- [ ] Integration tests: generate bindings for real C libraries such as SQLite3, libcurl
Phase 3: Ecosystem Foundation (v0.9)
- [ ] Publish official
libcbinding package (POSIX + Windows API subset) - [ ] Establish binding package publishing specification
- [ ] Documentation: FFI best practices, memory ownership, concurrency safety contracts
Relationship to Other RFCs
- RFC-001: FFI calls, as external functions, default to
@block(do not participate in DAG scheduling) - RFC-008: Scheduler decoupling design; FFI calls as independent tasks
- RFC-020: Detailed scheduling-level design for FFI nodes' scheduling semantics, Phi nodes, loop unrolling, etc. in the DAG
Open Questions
- [ ] Does
yx-bindgenneed to be integrated into the build system (yaoxiang build)? - [ ] How to design FFI support for the WASM platform? (WASM's import mechanism is completely different from dlopen)
- [ ] Is it necessary to provide
cxx-bindgento handle C++ name mangling (optional, consider after v1.0)?
Appendix A: Design Decision Records
| Decision | Decision | Reason | Date | Recorder |
|---|---|---|---|---|
| Unification of FFI entry point | Only keep native("symbol") | Avoid API fragmentation | 2026-05-29 | 晨煦 |
Exclude try_call | Not implemented | Redundant, Result type already exists | 2026-05-29 | 晨煦 |
Exclude verify_signature | Not implemented | Doing the compiler's job at runtime | 2026-05-29 | 晨煦 |
| Community binding → toolchain | yx-bindgen auto-generation | An unenforceable fantasy | 2026-05-29 | 晨煦 |
| OS error code | FfiError must carry os_error | An undebuggable API is useless | 2026-05-29 | 晨煦 |
| Zero syntax changes | Implemented via library | Core simplicity principle | 2026-03-14 | 晨煦 |
| Dynamic library loading | Use dlopen/dlsym | Standard OS interface | 2026-03-14 | 晨煦 |
| Error handling | Use Result type | Consistency | 2026-03-14 | 晨煦 |
Appendix B: Example Code
Complete Example: Using a C Library
# Load the C math library
libm = ffi.load_library("libm.so")
# Register C symbols into the runtime table (yx-bindgen does this at compile time)
ffi.register_library_symbols(libm, ["sin", "cos", "sqrt"])
# Use them via native declarations
sin_f: (x: Float) -> Float = native("sin")
cos_f: (x: Float) -> Float = native("cos")
# Direct call
result = sin_f(3.14159 / 2)
# Use Result when calling a C function that may fail
file_open: (path: *const u8, mode: *const u8) -> Result(*mut opaque, Int)
= native("fopen")Using yx-bindgen
# Auto-generate all declarations, no manual writing needed
yx-bindgen --header /usr/include/math.h --output math_bindings.yx
# Import in YaoXiang
import "math_bindings.yx"
# sin_f / cos_f etc. are already auto-declared as native("sin") / native("cos")