Skip to content

Non-Python host bindings (JS/PHP/Go, native Rust API) #27

Open

Description

@JuroOravec

Real host bindings for JS/TS, PHP, and Go, plus a native Rust API, beyond the current stubs.

Current state: the four non-Python LangImpls are regex-based structural stubs (crates/citry_template_parser/src/lang/{js,php,go,rust}.rs); only Python is fully implemented (via python_safe_eval). packages/ contains only py.

Scope (per language): real expression parsing + variable tracking, code generation, and a host runtime consuming the compiler output.

Binding mechanisms (harvested from old TODO/v2_cross_lang.md)

  • JS/TS: wasm-bindgen + wasm-pack, with js-sys / web-sys for JS and Web-API types. Build per target: wasm-pack build --target web (browser) versus --target nodejs.
  • PHP and Go (C ABI): compile with crate-type = ["cdylib", "rlib"] and generate the C header with cbindgen; load via PHP's ext-ffi or Go's cgo.
  • Python: the existing PyO3 path.

Out of scope for now: becomes relevant once the Python version is established and users ask for other languages.

Activity

  1. added
    enhancement
    on Jul 1, 2026
  2. JuroOravec commented on Jul 1, 2026

    @JuroOravec
    MemberAuthor

    Calling Rust from Other Languages: PyO3, wasm-bindgen, and FFI

    Overview

    Yes, you can call Rust compiled binaries from other languages (JavaScript, PHP, Go), similar to how PyO3/maturin works for Python. The approaches vary by language, but they all ultimately use FFI (Foreign Function Interface) mechanisms.

    JavaScript/TypeScript: WebAssembly (WASM)

    Use WebAssembly with wasm-bindgen and wasm-pack (similar to PyO3 for Python).

    Tools:

    • wasm-bindgen - Generates bindings between Rust and JavaScript
    • wasm-pack - Builds and packages Rust-generated WebAssembly
    • js-sys / web-sys - Bindings for JavaScript standard objects and Web APIs

    Example:

    use wasm_bindgen::prelude::*;
    
    #[wasm_bindgen]
    pub fn parse_template(input: &str) -> String {
        // Your parsing logic
        format!("Parsed: {}", input)
    }

    Build:

    wasm-pack build --target web      # For browsers
    wasm-pack build --target nodejs   # For Node.js

    Use in JavaScript:

    import init, { parse_template } from "./pkg/your_project.js";
    await init();
    const result = parse_template("{{ user.name }}");

    PHP: FFI Extension

    Use PHP's FFI extension to call C-compatible Rust libraries.

    Approach:

    1. Compile Rust to a shared library (.so/.dll/.dylib) with C-compatible interface
    2. Use PHP's ext-ffi to load and call the library

    Rust code:

    #[no_mangle]
    pub extern "C" fn parse_template(input: *const c_char) -> *mut c_char {
        // Your parsing logic
        // Return C string
    }

    PHP code:

    $ffi = FFI::cdef("
        char* parse_template(const char* input);
    ", "./target/release/libyour_lib.so");
    
    $result = $ffi->parse_template("{{ user.name }}");

    Go: cgo

    Use Go's cgo to call C-compatible Rust libraries.

    Rust code:

    #[no_mangle]
    pub extern "C" fn parse_template(input: *const c_char) -> *mut c_char {
        // Your parsing logic
    }

    Go code:

    /*
    #cgo LDFLAGS: -L./target/release -lyour_lib
    #include <stdlib.h>
    extern char* parse_template(const char* input);
    */
    import "C"
    import "unsafe"
    
    func ParseTemplate(input string) string {
        cInput := C.CString(input)
        defer C.free(unsafe.Pointer(cInput))
    
        cResult := C.parse_template(cInput)
        defer C.free(unsafe.Pointer(cResult))
    
        return C.GoString(cResult)
    }

    Comparison with PyO3

    Language Approach Similarity to PyO3
    Python PyO3/maturin ✅ Native integration
    JavaScript/TS wasm-bindgen/wasm-pack ✅ High-level bindings
    PHP FFI extension ⚠️ Lower-level (C ABI)
    Go cgo ⚠️ Lower-level (C ABI)

    General Pattern: C ABI

    For languages without high-level bindings (PHP, Go, etc.), compile Rust to a C-compatible shared library:

    1. Use extern "C" and #[no_mangle] in Rust
    2. Compile as cdylib (shared library)
    3. Create C header file (or use cbindgen to generate it)
    4. Load from the target language using its FFI mechanism

    Cargo.toml:

    [lib]
    crate-type = ["cdylib", "rlib"]

    Build:

    cargo build --release
    # Produces: libyour_lib.so (Linux), libyour_lib.dylib (macOS), your_lib.dll (Windows)

    How PyO3 and wasm-bindgen Differ from Manual FFI

    PyO3: High-Level Wrapper Around Python's C API

    What PyO3 does:

    1. Uses Python's C API (C-based FFI)
    2. Generates Python extension modules (.so/.pyd) via procedural macros
    3. Automatically converts types (Rust String ↔ Python str, Rust Vec ↔ Python list, etc.)
    4. Manages memory (reference counting, GIL)
    5. Generates boilerplate (module initialization, function wrappers)

    Manual FFI equivalent:

    // You'd have to write this manually:
    static PyObject* parse_template(PyObject* self, PyObject* args) {
        char* input;
        if (!PyArg_ParseTuple(args, "s", &input)) {
            return NULL;
        }
        // Call Rust function, convert result, manage refs...
    }

    PyO3 version:

    #[pyfunction]
    pub fn parse_template(input: &str) -> String {
        // PyO3 handles all the C API calls automatically
    }

    wasm-bindgen: High-Level Wrapper Around WebAssembly Interface

    What wasm-bindgen does:

    1. Uses WebAssembly's interface (not C FFI, but WASM's own ABI)
    2. Generates JavaScript glue code that calls WASM functions
    3. Converts types (Rust String ↔ JavaScript string, Rust Vec ↔ JavaScript Array, etc.)
    4. Manages WASM linear memory
    5. Handles complex types (objects, arrays, closures)

    Manual WASM equivalent:

    // You'd have to write this manually:
    const wasmModule = await WebAssembly.instantiateStreaming(fetch("module.wasm"));
    const memory = wasmModule.instance.exports.memory;
    const parse_template = wasmModule.instance.exports.parse_template;
    
    // Manually allocate strings in WASM memory, call function,
    // read result from memory, free memory...

    wasm-bindgen version:

    #[wasm_bindgen]
    pub fn parse_template(input: &str) -> String {
        // wasm-bindgen handles all the WASM/JS interop automatically
    }

    Comparison Table

    Aspect Manual FFI (C ABI) PyO3 wasm-bindgen
    FFI Layer C ABI (shared library) Python C API (C ABI) WebAssembly ABI
    Type Conversion Manual Automatic Automatic
    Memory Management Manual Automatic (ref counting) Automatic (WASM memory)
    Code Generation None Procedural macros Build-time codegen
    Safety Unsafe (manual) Safe Rust API Safe Rust API
    Boilerplate Lots Minimal Minimal

    The Key Insight

    Yes—PyO3 and wasm-bindgen are essentially:

    1. Code generators that create language-specific bindings
    2. Type conversion layers (Rust types ↔ target language types)
    3. Memory management wrappers (handling ref counting, GIL, WASM memory)
    4. Safety abstractions (exposing safe Rust APIs instead of unsafe FFI)

    PyO3 flow:

    Your Rust Code
        ↓
    PyO3 procedural macros (code generation)
        ↓
    Rust code that calls Python C API (FFI)
        ↓
    Python extension module (.so/.pyd)
        ↓
    Python imports and uses it
    

    wasm-bindgen flow:

    Your Rust Code
        ↓
    wasm-bindgen (code generation)
        ↓
    WASM module + JavaScript glue code
        ↓
    JavaScript imports and uses it
    

    Manual FFI flow:

    Your Rust Code
        ↓
    You manually write C-compatible functions
        ↓
    Compile to shared library (.so/.dylib/.dll)
        ↓
    Target language loads library via FFI
        ↓
    You manually write bindings in target language
    

    Why Use PyO3/wasm-bindgen Instead of Manual FFI?

    • Automatic type conversions (no manual CString, PyObject*, etc.)
    • Memory safety (reference counting, GIL, WASM memory management)
    • Less boilerplate (macros generate the FFI code)
    • Type safety (compile-time checks)
    • Easier maintenance (updates when APIs change)

    In short: they are high-level interfaces that generate FFI bindings and handle the low-level details, making it much easier to call Rust from other languages.

  3. added
    next-sprint
    on Oct 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementnext-sprint

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions