### Install and Start Example Server Source: https://github.com/rust-diplomat/diplomat/blob/main/example/demo_gen/README.md Installs project dependencies and starts a local development server to view the `demo_gen` example. ```bash npm install npm run start ``` -------------------------------- ### Install and start demo web server Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/demo_gen/quickstart.md Installs Node.js dependencies and starts a local HTTP server to view the web demo. ```sh npm -C adder_bindings/demo install npm -C adder_bindings/demo run start ``` -------------------------------- ### Install Extension Module Source: https://github.com/rust-diplomat/diplomat/blob/main/feature_tests/nanobind/CMakeLists.txt Specifies the installation rule for the 'somelib' target, installing it as a library into the 'somelib' directory. ```cmake install(TARGETS somelib LIBRARY DESTINATION somelib) ``` -------------------------------- ### Project Setup and Compiler Check Source: https://github.com/rust-diplomat/diplomat/blob/main/feature_tests/nanobind/CMakeLists.txt Defines the project name and ensures a working C++ compiler is available. This is a standard CMake setup step. ```cmake project(my_ext LANGUAGES CXX) ``` -------------------------------- ### TOML Configuration File Example Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/config.md This TOML file demonstrates how to set shared configuration options and backend-specific overrides for Kotlin and other backends. ```toml # Top level table specifies Shared Config settings that apply to all backends: lib-name = "MyLibrary" [kotlin] # Individual tables can override Shared Config settings: lib-name = "LibraryNameOverride" # Along with backend specific settings: domain = "org.myOrganization" [demo_gen] explicit-generation = true [other-library-name] some-value = 100 ``` -------------------------------- ### CLI Configuration Example Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/config.md This command shows how to set configuration options directly via the `diplomat-tool` CLI, overriding TOML settings. ```bash ./diplomat-tool kotlin ./kotlin-folder --config lib_name="MyLibrary" --config kotlin.domain = "org.myOrganization" ``` -------------------------------- ### Install Diplomat CLI Tool Source: https://github.com/rust-diplomat/diplomat/blob/main/README.md Install the Diplomat command-line interface tool for generating bindings. This command is run from your terminal. ```bash $ cargo install diplomat-tool ``` -------------------------------- ### Install diplomat-tool Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/npm_packaging.md If `diplomat-tool` is not installed, use `cargo install` to add it to your system. This tool is required for generating JavaScript bindings and TypeScript headers. ```sh cargo install diplomat-tool ``` -------------------------------- ### Demo Attribute Example Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/demo_gen.md An example of the `#[diplomat::demo]` attribute used for special configuration in Rust code. ```rust #[diplomat::demo(default_constructor)] pub fn try_new( locale: &Locale, provider: &DataProvider, options: FixedDecimalFormatterOptions, ) -> Result, ()> { /* ... */ } ``` -------------------------------- ### Rust Attribute Configuration Example Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/config.md These Rust attributes demonstrate setting configuration directly within `lib.rs` for structs, modules, and impl blocks. These have the highest priority. ```rust #[diplomat::config(lib_name="MyLibrary")] struct SomeConfig; #[diplomat::config(kotlin.domain="org.myOrganization")] mod kotlin_specific_mod; #[diplomat::config(...)] impl SomeConfig { } ``` -------------------------------- ### Backend-Specific Documentation with Diplomat Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/docs.md Shows how to use `#[diplomat::docs]` to control which documentation comments are included in specific backends. Includes examples for C++ and excluding JavaScript. ```rust #[diplomat::bridge] mod ffi { /// This comment will be shown everywhere. /// This comment will also be shown everywhere. #[diplomat::docs(cpp)] /// This comment will only be shown in C++. /// ```cpp /// void sampleCodeHere(); /// ``` #[diplomat::docs(not(js))] /// This comment will be shown everywhere BUT JS. /// ```js /// sampleCodeHere(); /// ``` #[diplomat::docs(*)] /// This comment will be shown everywhere, again. pub struct MyZST; } ``` -------------------------------- ### Add wasm32-unknown-unknown target Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/demo_gen/quickstart.md Installs the necessary WebAssembly target for Rust compilation. ```sh rustup target add wasm32-unknown-unknown ``` -------------------------------- ### DiplomatWrite Buffer Create and Management Functions Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/backends/c.md Functions for creating, retrieving data from, getting the length of, and destroying a DiplomatWrite buffer. ```c DiplomatWrite* diplomat_buffer_write_create(size_t cap); char* diplomat_buffer_write_get_bytes(DiplomatWrite* t); size_t diplomat_buffer_write_len(DiplomatWrite* t); void diplomat_buffer_write_destroy(DiplomatWrite* t); ``` -------------------------------- ### Rust Option Example Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/option.md Demonstrates `Option` usage for creating and manipulating optional values. `maybe_create` returns an optional boxed `Thingy`, and `increment_option` increments an optional `u8`. ```Rust #[diplomat::bridge] mod ffi { // just exists so we can get methods #[diplomat::opaque] pub struct Thingy; impl Thingy { pub fn maybe_create() -> Option> { Some(Box::new(Thingy)) } pub fn increment_option(x: Option) -> Option { x.map(|inner| inner + 1) } } } ``` -------------------------------- ### Generated Java API Example Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/design_doc.md Illustrates a potential Java API generated by a Diplomat plugin for a PluralRules class. It shows constructor, select method, and a destroy method for resource management. ```java public class PluralRules { public PluralRules(...) throws PluralError { // call PluralRules_new(), convert any types } public void select(...) { // call PluralRules_select(), convert any types } // could also generate a finalizer, AutoCloseable, or something else public void destroy(..) { // call PluralRules_destroy() } } ``` -------------------------------- ### JavaScript Example for Indirect Struct Passing Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/wasm_abi_quirks.md Demonstrates how to call a Wasm function expecting a struct via indirect passing using JavaScript. ```javascript // Allocate space for the struct with the right size/alignment let structAlloc = wasm.diplomat_alloc(8, 4); ptrWrite(structAlloc, a, 1); ptrWrite(structAlloc + 4, b, 4); wasm.takes_struct(structAlloc); // Clean up wasm.diplomat_free(structAlloc); ``` -------------------------------- ### Allowed Opaque Slice Input Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/attrs/slices.md Shows an example of an allowed opaque slice input in Diplomat. Opaque slices are currently restricted to input only. ```Rust // Allowed: pub fn takes_opaque_slice<'a>(&'a self, sl: &'a [MyOpaque]); ``` -------------------------------- ### Rust Code with Diplomat Documentation Annotations Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/docs.md Demonstrates the use of `#[diplomat::bridge]`, `#[diplomat::rust_link]`, `#[diplomat::opaque]`, and `#[diplomat::enum_convert]` for generating documentation and bindings. Includes examples of linking to Rust types, structs, enums, and functions. ```rust #[diplomat::bridge] mod ffi { use my_thingy::MyThingy; /// A Thingy #[diplomat::rust_link(my_thingy::MyThingy, Struct)] #[diplomat::opaque] pub struct Thingy(MyThingy); #[diplomat::enum_convert(my_thingy::SpeedSetting)] #[diplomat::rust_link(my_thingy::SpeedSetting, Enum)] pub enum SpeedSetting { Fast, Medium, Slow } #[diplomat::enum_convert(my_thingy::ThingyStatus)] #[diplomat::rust_link(my_thingy::ThingyStatus, Enum)] pub enum ThingyStatus { Good, Bad } impl Thingy { /// Make a [`MyThingy`]! #[diplomat::rust_link(my_thingy::MyThingy::new, FnInStruct)] pub fn create(speed: SpeedSetting) -> Box { Box::new(Thingy(Thingy::new(speed.into()))) } /// Get the status #[diplomat::rust_link(my_thingy::MyThingy::get_status, FnInStruct)] pub fn get_status(&self) -> ThingyStatus { self.0.get_status().into() } } } ``` -------------------------------- ### LLVM IR for Indirect Struct Passing in Wasm Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/wasm_abi_quirks.md Presents LLVM IR examples for indirect struct passing, showing variations for different compilers/flags. ```llvm ; produced by webassembly-clang: %struct.MyStruct = type { i8, i32 } define dso_local void @takes_struct(ptr noundef byval(%struct.MyStruct) align 4 %0) #0 { ... } ``` ```llvm ; produced by rustc with -Zwasm-c-abi=spec define dso_local void @takes_struct(ptr byval([8 x i8]) align 4 %x) unnamed_addr #0 { ... } ``` -------------------------------- ### Rust Struct Definition for Padded Direct Passing Example Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/wasm_abi_quirks.md Illustrates a Rust struct designed to demonstrate 'padded direct' passing, including padding bytes. ```rust ; Edited from IR produced by rustc with (default) -Zwasm-c-abi=legacy %MyStruct = type { i8, [3 x i8], i32 } define dso_local void @takes_struct(%MyStruct %0) unnamed_addr #0 { ... } ``` -------------------------------- ### Rust Diplomat Bridge Block Example Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/design_doc.md Demonstrates a Rust bridge block using the `diplomat` attribute to define extra methods and apply attributes like `diplomat_java::protected` for custom code generation. ```rust #[diplomat::bridge] mod ffi { // snip #[diplomat_java::extra_methods(./PluralRulesExtra.java)] impl PluralRules { #[diplomat_java::protected] fn select(...) -> PluralCategory { // snip } } } ``` -------------------------------- ### Rust Function for Wasm Option Handling Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/wasm_abi_quirks.md An example Rust function that accepts a `DiplomatOption` and logs its content. This demonstrates how optional structs are passed and accessed. ```rust #[repr(C)] #[derive(Debug)] pub struct Inner { x: u8, y: u16, z: u32, } #[no_mangle] pub extern "C" fn opt(x: DiplomatOption) { let val = unsafe { x.value.ok }; log(&format!("{val:#x?}")); } ``` -------------------------------- ### Rust DiplomatOption Example Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/option.md Illustrates `DiplomatOption` for FFI-safe optional fields within structs, particularly for non-reference types like primitives and enums. It also shows a standard `Option<&'a MyOpaque>`. ```Rust #[diplomat::bridge] mod ffi { use diplomat_runtime::DiplomatOption; #[diplomat::opaque] pub struct MyOpaque(u8); pub enum MyEnum { Foo, Bar } pub struct MyStruct<'a> { a: DiplomatOption, b: DiplomatOption, c: Option<&'a MyOpaque> } } ``` -------------------------------- ### Set Minimum CMake Version and Policies Source: https://github.com/rust-diplomat/diplomat/blob/main/feature_tests/nanobind/CMakeLists.txt Specifies the minimum required CMake version and the range of versions for which policies are set. This ensures compatibility with a range of CMake installations. ```cmake cmake_minimum_required(VERSION 3.15...3.27) ``` -------------------------------- ### Custom Javascript Function for Demo Generation Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/demo_gen/custom_functions.md Define a custom Javascript function to demonstrate library capabilities. This example shows how to call two different Rust functions and combine their results. ```javascript // adder_bindings/src/adder_custom.mjs import { lib } from "./index.mjs"; export default { "AddThreeVariables": { func: (a, b, c) => { return lib.AddResult.getAddStr(a, b) + " and " + lib.AddResult.getAddStr(b, c); }, funcName: "Add a + b, b + c", parameters: [ { name: "a", type: "number" }, { name: "b", type: "number" }, { name: "c", type: "number" } ] } } ``` -------------------------------- ### Expected native symbol output Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/developer.md This is an example of the expected content in a snapshot file after generating native symbols. It shows the native symbol name for the 'add_two' method of 'OpaqueStruct'. ```yaml --- source: tool/src/backend/mod.rs assertion_line: 67 expression: generated --- OpaqueStruct_add_two ``` -------------------------------- ### Define Rust API with diplomat::bridge Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/basics.md Use the `diplomat::bridge` macro to define Rust modules and structs that will be exposed over FFI. This example shows a simple struct with public fields and associated methods. ```rust #[diplomat::bridge] mod ffi { pub struct MyFFIStruct { pub a: i32, pub b: bool, } impl MyFFIStruct { pub fn create() -> MyFFIStruct { MyFFIStruct { a: 42, b: true } } pub fn do_a_thing(self) { println!("doing thing {:?}", self.b); } } } ``` -------------------------------- ### Generated C++ Opaque Type Example Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/opaque.md This C++ code snippet illustrates the generated interface for an opaque type. It shows a `Person` class with static factory method `create` and member functions `get_age` and `dump`, but the internal representation is hidden. ```cpp class Person { public: static std::unique_ptr create(const std::string_view s, int8_t age); int8_t get_age(); void dump(); // snip private: }; ``` -------------------------------- ### Warning for Direct CMake Invocation Source: https://github.com/rust-diplomat/diplomat/blob/main/feature_tests/nanobind/CMakeLists.txt Displays a warning message if CMake is invoked directly, guiding users to use 'scikit-build-core' for proper installation and development workflows. ```cmake if (NOT SKBUILD) message(WARNING "\ This CMake file is meant to be executed using 'scikit-build-core'. Running it directly will almost certainly not produce the desired result. If you are a user trying to install this package, use the command below, which will install all necessary build dependencies, compile the package in an isolated environment, and then install it. ===================================================================== $ pip install . ===================================================================== If you are a software developer, and this is your own package, then it is usually much more efficient to install the build dependencies in your environment once and use the following command that avoids a costly creation of a new virtual environment at every compilation: ===================================================================== $ pip install nanobind scikit-build-core[pyproject] $ pip install --no-build-isolation -ve . ===================================================================== You may optionally add -Ceditable.rebuild=true to auto-rebuild when the package is imported. Otherwise, you need to rerun the above after editing C++ files.") endif() ``` -------------------------------- ### Initialize NPM package in the lib directory Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/npm_packaging.md Navigate to the `lib` directory and use `npm init` to generate an initial `package.json` file. This command will prompt you for package details. ```sh # my-bindings/lib/ npm init ``` -------------------------------- ### Set up directory structure for NPM package Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/npm_packaging.md Create the necessary directories (`lib`, `lib/api`, `lib/docs`, `lib/tests`) within your bindings crate to organize the files for the NPM package. ```sh # my-bindings/ mkdir lib lib/api lib/docs lib/tests ``` -------------------------------- ### Run Diplomat tool to generate demo_gen bindings Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/demo_gen/quickstart.md Executes the diplomat-tool to generate JavaScript bindings and demo files for the adder_bindings library. ```sh diplomat-tool demo_gen adder_bindings/demo/demo_gen --entry adder_bindings/src/lib.rs ``` -------------------------------- ### Create Diplomat configuration file Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/npm_packaging.md Create a `diplomat.config.js` file to specify the `wasm_path` for the compiled WebAssembly binary and an optional `init` function for initialization tasks. ```js // my-bindings/lib/diplomat.config.js export default { wasm_path: new URL('./api/my_bindings.wasm', import.meta.url), }; ``` -------------------------------- ### Generate Backend Feature Tests Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/developer.md This command generates feature tests for a specific backend, such as Dart. Ensure you have cargo-make installed and configured in your Makefile.toml. ```sh cargo make gen-dart-feature ``` -------------------------------- ### Configure Include Directories for Extension Source: https://github.com/rust-diplomat/diplomat/blob/main/feature_tests/nanobind/CMakeLists.txt Adds public include directories for the 'somelib' target, including the project's 'src/include' and nanobind's robin_map headers. ```cmake target_include_directories(somelib PUBLIC "src/include" "${nanobind_ROOT}/ext/robin_map/include") ``` -------------------------------- ### Rust Struct Definition for Direct Passing Example Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/wasm_abi_quirks.md Defines a Rust struct with explicit memory layout for demonstrating direct ABI passing. ```rust #[repr(C)] struct MyStruct { a: u8, // 3 bytes padding b: u32 } #[no_mangle] extern "C" fn takes_struct(s: MyStruct) {...} ``` -------------------------------- ### Generate Kotlin Backend Library Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/backends/kotlin.md Command to generate the Kotlin backend library using the diplomat-tool. Requires specifying the path to the Rust library, a configuration file, and optional configuration overrides. ```sh diplomat-tool -e {PATH_TO_LIB.RS} -c {CONFIG_FILE} --config {CONFIG_OVERRIDE_1} --config {CONFIG_OVERRIDE_2} kotlin {OUTPUT_PATH} ``` -------------------------------- ### Duckscript Function for Generation Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/developer.md This is an example of a Duckscript function used within cargo-make tasks for code generation. Duckscript is a simple scripting language. ```duckscript #!/usr/bin/env duckscript # This file is part of Diplomat. # https://github.com/rust-diplomat/diplomat # This is a simple example of a duckscript function. # It is not intended to be run directly. fn main() { # Example of a function call within duckscript # This is a placeholder and does not represent actual functionality. print("Hello, Diplomat!") } main() ``` -------------------------------- ### Define Function Accepting Callback (Rust) Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/callbacks.md Example of defining a Rust function within a Diplomat bridge that accepts a callback with a non-mutating closure. ```rust #[diplomat::bridge] impl MyType{ pub fn acceptsCallback(&self, impl Fn()) } ``` -------------------------------- ### Define Function Accepting Mutating Callback (Rust) Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/callbacks.md Example of defining a Rust function within a Diplomat bridge that accepts a callback with a mutating closure. ```rust impl MyType{ pub fn acceptsCallback(&self, impl FnMut()) } ``` -------------------------------- ### Generate Opaque Definition Stub Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/developer.md A placeholder function for generating code for an opaque struct. This is a starting point for your backend's code generation logic. ```rust use diplomat_core::hir::{OpaqueDef, TypeContext, TypeId}; fn gen_opaque_def(ctx: &TypeContext, type_id: TypeId, opaque_path: &OpaqueDef) -> String { "We'll get to it".into() } ``` -------------------------------- ### Create a new Rust library project Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/developer.md Use cargo to create a new Rust library project. This command initializes a new project with the specified name and sets it up as a library. ```sh cargo new --lib mybackendtest ``` -------------------------------- ### Generate JavaScript bindings and TypeScript headers Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/npm_packaging.md Run `diplomat-tool` to generate the JavaScript bindings and TypeScript headers. Specify the output directory for API files (`lib/api`) and documentation (`lib/docs`). ```sh # my-bindings/ diplomat-tool js lib/api --docs lib/docs ``` -------------------------------- ### Configure package.json for NPM distribution Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/npm_packaging.md Edit the `package.json` file to specify the main entry point (`./api/index.js`), set the module type to `"module"`, and define the `directories` for documentation. ```js // my-bindings/lib/package.json { // other config options... "main": "./api/index.js", // diplomat-tool is going to only write in `api/` later "type": "module", "directories": { // other directories... "doc": "docs" } } ``` -------------------------------- ### WebAssembly WAT for Function Signature Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/wasm_abi_quirks.md Shows the WebAssembly Text format (WAT) for the 'opt' function signature. This details the parameters expected by the Wasm module, reflecting the C ABI. ```wat (type $t0 (func (param i32 i32 i32 i32 i32 i32))) (func $opt (export "opt") (type $t0) (param $p0 i32) (param $p1 i32) (param $p2 i32) (param $p3 i32) (param $p4 i32) (param $p5 i32) ...) ``` -------------------------------- ### TOML Configuration for demo_gen Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/demo_gen/markup.md Configure demo_gen's behavior for explicit generation, hiding renderers, and setting module or relative import paths. This TOML file demonstrates various settings with comments explaining their purpose and default values. ```toml [demo-gen] # If false, demo_gen will automatically search all methods for functions it can generate demonstration JS for. # If true, demo_gen will look for any methods explicitly flagged with #[diplomat::demo(generate)] to perform generation. explicit-generation=true # default = false (bool) # This removes the rendering/ folder. hide-default-renderer=true # default = false (bool) # Adjusts all imports that demo_gen creates to a specific module. Setting this will not generate the js/ folder. # # So for instance, this setting will adjust imports to: `import { type } from "icu4x"; module-name="icu4x" # (string) # Adjusts all imports that demo_gen creates to a relative path where Diplomat JS output should be. Setting this will not generate the js/ folder. # # Setting this will adjust imports to: `import {type} from "../js/folder/here/index.mjs"; # # Intended to be a mutually exclusive setting with module_name, although you can set both simultaneously to import modules from a relative path. relative-js-path="../js/folder/here" # (string) ``` -------------------------------- ### Create a new Rust library crate for bindings Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/npm_packaging.md Use `cargo new --lib` to create a new Rust library crate that will house your Diplomat bindings. This separates bindings from your main library code. ```sh cargo new --lib my-bindings ``` -------------------------------- ### Configure Cargo.toml for WebAssembly compilation Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/npm_packaging.md Modify the `Cargo.toml` file to enable compilation to WebAssembly (`cdylib`) and set optimization for small code size (`opt-level = "s"`). Include necessary dependencies like `diplomat` and `diplomat-runtime`. ```toml # my-bindings/Cargo.toml [package] name = "my-bindings" version = "0.1.0" edition = "2021" [lib] # Enable compilation to WebAssembly crate-type = ["cdylib", "rlib"] [dependencies] diplomat = "*" diplomat-runtime = "*" # your crate here [profile.release] # Optimize for small code size opt-level = "s" ``` -------------------------------- ### Build adder_bindings with WASM target Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/demo_gen/quickstart.md Compiles the Diplomat bindings for the adder library, targeting WebAssembly. ```sh cargo build -p adder_bindings --target wasm32-unknown-unknown ``` -------------------------------- ### Use 'auto' for Attribute Configuration Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/attrs.md The `auto` configuration specification is equivalent to `supports = whichever attribute this is attempting to apply`, simplifying attribute application when backend support varies. ```rust #[diplomat::attr(auto, iterator)] ``` -------------------------------- ### Rust Person Struct Definition Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/opaque.md Defines a `Person` struct in Rust with name and age fields, along with methods to create a new person, get their age, and print their details. ```rust struct Person { name: String, age: u8, } impl Person { pub fn new(name: String, age: u8) -> Self { Self { name, age } } pub fn get_age(&self) -> u8 { self.age } pub fn dump(&self) { println!("Person {} of age {}", self.name, self.age); } } ``` -------------------------------- ### Rust struct definition for Wasm return Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/wasm_abi_quirks.md Example of a Rust struct definition that will be returned from a Wasm function. Note the comments indicating size and alignment, which are crucial for Wasm memory management. ```rust pub struct Big { a: u8, // size 1, offset 0 b: u16, // size 2, offset 2 c: u64, // size 8, offset 8 } #[no_mangle] pub extern "C" fn returns_big(arg1: u8, arg2: u8) -> Big { ... } ``` -------------------------------- ### LLVM IR for Wasm ABI Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/wasm_abi_quirks.md Illustrates the Low-Level Virtual Machine (LLVM) Intermediate Representation generated by rustc for the Wasm C ABI. It shows the type layout for structs and unions. ```llvm ; produced by rustc with (default) -Zwasm-c-abi=legacy %Inner = type { i8, [1 x i8], i16, i32 } %"DiplomatResult" = type { %"DiplomatResultValue", i8, [3 x i8] } %"DiplomatResultValue" = type { [2 x i32] } define dso_local void @opt(% ``` -------------------------------- ### Configure Cargo.toml for a dynamic library Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/developer.md This Cargo.toml configuration specifies the package details, sets the library type to 'cdylib' for dynamic linking, and defines path dependencies for Diplomat. ```toml [package] name = "mybackendtest" version = "0.1.0" edition = "2021" [lib] crate_type = ["cdylib"] name = "mybackendtest" [dependencies] diplomat = {path = "../diplomat/macro"} diplomat-runtime = {path = "../diplomat/runtime"} ``` -------------------------------- ### Generated C Header Code Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/design_doc.md Example of C header code generated from a Rust bridge block. This defines the C-level API for interacting with Rust types, intended for use by plugins. ```c struct PluralRulesRust; struct PluralRules { PluralRulesRust* inner; } enum PluralCategory {..}; struct PluralRulesResult { // ... }; PluralRulesResult PluralRules_new(...); PluralCategory PluralRules_select(PluralRules* pr); void PluralRules_destroy(...); ``` -------------------------------- ### Rust FFI with DiplomatWrite Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/write.md Demonstrates how to use `DiplomatWrite` to write debug output and string representations of a struct to the FFI boundary. This avoids intermediate Rust string allocations. ```rust #[diplomat::bridge] mod ffi { use diplomat_runtime::DiplomatWrite; use std::fmt::Write; #[diplomat::opaque] #[derive(Debug)] pub struct Thingy(u8); impl Thingy { pub fn debug_output(&self, write: &mut DiplomatWrite) { write!(write, "{:?}", self); } pub fn maybe_get_string(&self, write: &mut DiplomatWrite) -> Result<(), ()> { write!(write, "integer is {}", self.0).map_err(|_| ()) } } } ``` -------------------------------- ### Equivalent Disable Struct with not() Attribute Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/attrs/disable.md Provides the equivalent of the `cfg` example, explicitly using `#[diplomat::attr(not(supports = namespaces), disable)]` to disable a struct when the `supports = namespaces` condition is not met. ```rust #[diplomat::bridge] mod ffi { #[diplomat::opaque] #[diplomat::attr(not(supports = namespaces), disable)] struct Foo; } ``` -------------------------------- ### Rust Function with u8 Parameter and Return Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/wasm_abi_quirks.md Demonstrates how a Rust function accepting a single u8 parameter and returning a u8 is represented as i32 in Wasm/WAT due to ABI limitations. ```rust #[no_mangle] pub extern "C" fn inout(x: u8) -> u8 { 1 } ``` -------------------------------- ### Compile Rust bindings to WebAssembly Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/npm_packaging.md Compile your Rust bindings crate to WebAssembly using `cargo build --target wasm32-unknown-unknown`. This produces a `.wasm` binary. ```sh # my-bindings/ cargo build --target wasm32-unknown-unknown ``` -------------------------------- ### Custom External Parameter Evaluation for DataProvider Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/demo_gen/renderer.md An example of a custom 'evaluateExternal' function that specifically handles the 'DataProvider' parameter type by providing compiled data. It logs an error for any other unrecognized parameter types. ```javascript let dataProvider = DataProvider.compiled(); let evaluateExternal = (param, updateParamEvent) => { if (parameter.type === "DataProvider") { updateParamEvent(dataProvider); } else { console.error(`Unrecognized parameter type ${param}`); } }; ``` -------------------------------- ### Build the Rust dynamic library Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/developer.md This command compiles the Rust project, creating a debug artifact for the dynamically linked library in the target directory. ```sh cargo build ``` -------------------------------- ### Wasm/WAT Representation of Rust Function Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/wasm_abi_quirks.md Illustrates the WebAssembly Binary Instruction Format (WAT) representation of the Rust function, showing the i32 type mapping for parameters and results. ```wat (type $t0 (func (param i32) (result i32))) (func $inout (export "inout") (type $t0) (param $p0 i32) (result i32) ...) ``` -------------------------------- ### Structs Containing Output-Only Types with `diplomat::out` Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/structs.md This example demonstrates how to define a struct that contains output-only types, such as `Box`, by using the `#[diplomat::out]` attribute. This attribute also marks the struct itself as output-only. ```rust mod ffi { use my_thingy::MyThingy; #[diplomat::opaque] pub struct Thingy(=MyThingy); #[diplomat::out] pub struct ThingyAndExtraStuff { pub thingy: Box, pub stuff: u32 } impl Thingy { pub fn create() -> ThingyAndExtraStuff { let thingy = Box::new(Thingy(MyThingy::new())); let stuff = 42; ThingyAndExtraStuff { thingy, stuff } } } } ``` -------------------------------- ### Implement Indexing for a Rust Struct Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/attrs/indexing.md This snippet shows how to define an `indexer` method on a Rust struct (`Foo`) that wraps a `Vec`. The `get` method is marked with `#[diplomat::attr(auto, indexer)]` to enable indexing. ```rust #[diplomat::bridge] mod ffi { #[diplomat::opaque] struct Foo(Vec); impl Foo { #[diplomat::attr(auto, indexer)] pub fn get(&self, idx: usize) -> Option { self.0.get(idx).copied() } } } ``` -------------------------------- ### Set Features via CLI Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/attrs/features.md Specify a comma-separated list of features to be enabled for all backends using the `diplomat_tool` CLI command. Backend-specific configurations can override this setting. ```bash diplomat_tool cpp . --features-enabled=some,comma,separated,list ``` -------------------------------- ### Link Libraries for Extension Module Source: https://github.com/rust-diplomat/diplomat/blob/main/feature_tests/nanobind/CMakeLists.txt Links the 'diplomat_feature_tests' Rust library and the Python ABI library to the 'somelib' extension module. ```cmake target_link_libraries(somelib PUBLIC diplomat_feature_tests ${Python3_SABI_LIBRARY}) ``` -------------------------------- ### DiplomatWrite Simple Write Function Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/backends/c.md Provides a simple implementation of DiplomatWrite for a pre-allocated buffer. ```c DiplomatWrite diplomat_simple_write(char* buf, size_t buf_size); ``` -------------------------------- ### Build WASM bindings and run generator Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/demo_gen/quickstart.md Compiles the Rust library into WASM and runs the Diplomat generator to create bindings. ```sh cargo build -p adder_bindings --target wasm32-unknown-unknown cargo run -p generator cp target/wasm32-unknown-unknown/debug/adder_bindings.wasm adder_bindings/demo ``` -------------------------------- ### Replace npm command with npm.cmd on Windows Source: https://github.com/rust-diplomat/diplomat/blob/main/ContributingOnWindows.md If a script directly calls 'npm' and fails on Windows, try replacing it with 'npm.cmd' to use the Windows command script. ```shell npm.cmd ``` -------------------------------- ### Python Usage of Slice with Nanobind Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/backends/nanobind.md Demonstrates how to create and pass a `FooSlice` object to a Python function that expects a slice of `Foo` objects. This showcases the automatic conversion and copying handled by Nanobind. ```python f = somelib.FooSlice([somelib.Foo(x=10, y=10)]) somelib.Foo.takes_slice(f) ``` -------------------------------- ### Handling Failing Functions with Nanobind Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/backends/nanobind.md Demonstrates how to catch exceptions from Rust functions that return a Result type in Python. The exception's arguments will contain the converted error type. ```python try: somelib.FailingFunction() except Exception as e: error_type = e.args[0] ``` -------------------------------- ### JavaScript RenderInfo for FixedDecimalFormatter.formatWrite Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/demo_gen.md This JavaScript object `RenderInfo` defines the metadata for rendering the `FixedDecimalFormatter.formatWrite` function. It includes the function reference, its name, and a detailed list of parameters with their names and types, aiding in the generation of UI elements or documentation. ```javascript export const RenderInfo = { termini: { "FixedDecimalFormatter.formatWrite": { func: FixedDecimalFormatterDemo.formatWrite, // For avoiding webpacking minifying issues: funcName: "FixedDecimalFormatter.formatWrite", parameters: [ { name: "Locale Name", type: "string" }, { name: "ICU4X Fixed Decimal Grouping Strategy", type: "FixedDecimalGroupingStrategy" }, { name: "Useless Config (Ignore)", type: "boolean" }, { name: "ICU4XFixedDecimal Value", type: "number" } ] }, } }; ``` -------------------------------- ### Define and Use Structs and Enums with Diplomat Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/structs.md This snippet demonstrates defining opaque structs, settings structs with various field types (including enums), and enums themselves, along with methods to create and interact with these types. It shows conversion between FFI types and internal library types. ```rust #[diplomat::bridge] mod ffi { use my_thingy::MyThingy; // just exists so we can get methods #[diplomat::opaque] pub struct Thingy(MyThingy); pub struct ThingySettings { pub a: bool, pub b: u8, pub speed: SpeedSetting, } #[diplomat::enum_convert(my_thingy::SpeedSetting)] pub enum SpeedSetting { Fast, Medium, Slow } #[diplomat::enum_convert(my_thingy::ThingyStatus)] pub enum ThingyStatus { Good, Bad } impl Thingy { pub fn create(settings: ThingySettings) -> Box { // Convert our FFI type to whatever internal settings type was needed let settings = my_thingy::ThingySettings { a: settings.a, b: settings.b, speed: settings.speed.into() }; Box::new(Thingy::new(settings)) } pub fn get_status(&self) -> ThingyStatus { self.0.get_status().into() } } } ``` -------------------------------- ### Struct FromFields Call Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/demo_gen.md This Javascript code demonstrates how structs are constructed using the `FromFields` function, which is available for non-out structs. It assumes the existence of parameters `a`, `b`, `c`, and `d`. ```javascript Struct.FromFields(a, b, c, d); ``` -------------------------------- ### Test Opaque Struct Generation Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/developer.md This test case demonstrates how to parse a Diplomat AST, create a TypeContext, and extract opaque definitions to test code generation. It uses `syn` for parsing and `insta` for snapshot testing. ```rust use diplomat_core::{ ast::{self}, hir::{self, TypeDef}, }; use quote::quote; #[test] fn test_opaque_gen() { let tokens = quote! { #[diplomat::bridge] mod ffi { #[diplomat::opaque] struct OpaqueStruct; } }; let item = syn::parse2::(tokens).expect("failed to parse item "); let diplomat_file = ast::File::from(&item); let env = diplomat_file.all_types(); let attr_validator = hir::BasicAttributeValidator::new("my_backend_test"); let context = match hir::TypeContext::from_ast(&env, attr_validator) { Ok(context) => context, Err(e) => { for (_cx, err) in e { eprintln!("Lowering error: {}", err); } panic!("Failed to create context") } }; let (type_id, opaque_def) = match context .all_types() .next() .expect("Failed to generate first opaque def") { (type_id, TypeDef::Opaque(opaque_def)) => (type_id, opaque_def), _ => panic!("Failed to find opaque type from AST"), }; let generated = super::gen_opaque_def(&context, type_id, opaque_def); insta::assert_snapshot!(generated) } ``` -------------------------------- ### Implement Full Comparison Operators Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/attrs/comparators.md Use the `comparison` attribute on a method that takes another `Self` parameter to expose full comparison operators (`<`, `>`, `=`, etc.). This allows for direct comparison in target languages. ```rust #[diplomat::bridge] mod ffi { #[diplomat::opaque] #[derive(Ord, PartialOrd, Eq, PartialEq)] struct Foo(u8); impl Foo { #[diplomat::attr(auto, comparison)] pub fn compare(&self, other: &Foo) -> std::cmp::Ordering { self.cmp(other) } } } ``` -------------------------------- ### Rust Constructor for FixedDecimalFormatter Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/demo_gen.md This Rust function `try_new` serves as a default constructor for `FixedDecimalFormatter`. It requires a `Locale`, a `DataProvider`, and `FixedDecimalFormatterOptions` as input and returns a `Result` containing a boxed `FixedDecimalFormatter` or an error. ```rust #[diplomat::demo(default_constructor)] pub fn try_new( locale: &Locale, provider: &DataProvider, opions: FixedDecimalFormatterOptions, ) -> Result, ()> { /* ... */ } ``` -------------------------------- ### Enable Features via Config Source: https://github.com/rust-diplomat/diplomat/blob/main/book/src/attrs/features.md Configure which features are enabled globally for all backends using the `diplomat::config` attribute. This determines which tagged items will be generated. ```rust #[diplomat::config(features_enabled=["this_feature", "some_feature"])] struct Config; ``` -------------------------------- ### Define Custom Target for Rust Library Build Source: https://github.com/rust-diplomat/diplomat/blob/main/feature_tests/nanobind/CMakeLists.txt Sets up a custom command to build the Rust library using 'cargo build' and creates a custom target that depends on the output library file. This ensures the Rust code is compiled before the C++ extension. ```cmake set(FEATURE_TEST_LIB_FILE ${DIPLOMAT_ROOT}/target/debug/${CMAKE_STATIC_LIBRARY_PREFIX}diplomat_feature_tests${CMAKE_STATIC_LIBRARY_SUFFIX}) add_custom_command(OUTPUT ${FEATURE_TEST_LIB_FILE} COMMAND cargo build ) add_custom_target(diplomat_feature_tests_target DEPENDS ${FEATURE_TEST_LIB_FILE}) ``` -------------------------------- ### Wasm/WAT for outparam return Source: https://github.com/rust-diplomat/diplomat/blob/main/docs/wasm_abi_quirks.md The WebAssembly Binary Instruction Format (WAT) representation of the function signature. It highlights the absence of a direct return value and the presence of an additional outparam. ```wat (type $t0 (func (param i32 i32 i32))) (func $returns_big (export "returns_big") (type $t0) (param $p0 i32) (param $p1 i32) (param $p2 i32) ...) ```