Skip to main content

CbindgenBuilder

Struct CbindgenBuilder 

Source
pub struct CbindgenBuilder { /* private fields */ }

Implementations§

Source§

impl CbindgenBuilder

Source

pub fn new() -> Self

Create an adapter with no declarations (emits an empty library).

Source

pub fn source_module(self, p: Path) -> Self

Set the module path the original #[prebindgen] items live under (e.g. syn::parse_quote!(zenoh_flat)). Root-level modifier: resets the current declaration, so it can’t be followed by .base_name()/.error()/etc.

Source

pub fn free_memory_function(self, name: impl Into<String>) -> Self

Set the name of the universal memory-freeing function (a type-agnostic C free) the generated layer exports for releasing char* data it hands to C — string returns and String fields of data structs. Root-level modifier: resets the current declaration. Required whenever the adapter produces such string memory; otherwise that’s a build error.

Source

pub fn mangle_rust_type(self, f: impl Fn(&str) -> String + 'static) -> Self

Set the base Rust-type mangler: maps a type’s Rust short name (e.g. ZKeyExpr) to a canonical token (e.g. keyexpr). Its output feeds Self::mangle_type_name, Self::mangle_destructor and Self::mangle_callback, so a one-off spelling fix (e.g. KeyExprkeyexpr) lives in a single place instead of a per-declaration .base_name() exception. Root-level modifier (resets the current declaration). The adapter ships no default — unset, the base defaults to the snake_case of the Rust short name.

Source

pub fn mangle_type_name(self, f: impl Fn(&str) -> String + 'static) -> Self

Set the type-name mangler: base (see Self::mangle_rust_type) → the C type name emitted for a opaque_ptr / data_struct / enum_type (e.g. keyexprz_keyexpr_t). The base can be overridden per declaration by .base_name(). Root-level modifier.

Source

pub fn mangle_destructor(self, f: impl Fn(&str) -> String + 'static) -> Self

Set the destructor mangler: base → an opaque handle’s _drop symbol (e.g. keyexprz_keyexpr_drop). Root-level modifier.

Source

pub fn mangle_take(self, f: impl Fn(&str) -> String + 'static) -> Self

Set the “take” mangler: base → the public move symbol of a value_opaque type used as a Self::takeable_param (e.g. samplez_sample_take). When unset, the take symbol defaults to <destructor-base>_take. Root-level modifier.

Source

pub fn mangle_callback(self, f: impl Fn(&[String]) -> String + 'static) -> Self

Set the callback-struct mangler: the bases of a callback’s argument types → the closure struct’s C name (e.g. ["sample"]z_closure_sample_t, []z_closure_drop_t). A per-declaration .base_name() replaces the args’ bases with a single explicit base. Root-level modifier.

Source

pub fn mangle_function(self, f: impl Fn(&str) -> String + 'static) -> Self

Set the function mangler: a #[prebindgen] function’s Rust ident → its exported #[no_mangle] symbol (e.g. prefix z_). Functions are not types, so this does not go through the base mangler; the ident can be overridden per declaration by .base_name(). Root-level modifier.

Source

pub fn source<P: AsRef<Path>>(self, dir: P) -> Self

Declare a #[prebindgen] function to convert into the C layer. Every #[prebindgen] item captured in dir — see JniGenBuilder::source.

Source

pub fn source_named<P: AsRef<Path>>( self, dir: P, crate_name: impl Into<String>, ) -> Self

The same, for a dependency this crate renames in Cargo.toml.

Source

pub fn items<I>(self, items: I) -> Self
where I: IntoIterator<Item = (Item, SourceLocation)>,

Add a captured item stream. Accumulates, so it mixes with Self::source.

Source

pub fn function(self, ident: Ident) -> Self

Source

pub fn convert(self, decl: ConvertDecl) -> Self

Declare a canonical scalar conversion shared with JniGenBuilder. A domain on the ConvertDecl is validated in both directions; invalid scalar values become by-value niches for Option/Result, with public C constants derived from the conversion’s naming base.

Source

pub fn ignore_function(self, ident: Ident) -> Self

Mark a #[prebindgen] function as intentionally ignored by this adapter. Root-level modifier: suppresses the registry’s “skipping undeclared” warning for that function without scanning or emitting it.

Source

pub fn panic(self) -> Self

Allow the most recently declared Self::function to panic! on an internal error message. Required when a non-Result function has a fallible input (otherwise that’s a build error) — a null borrow, an invalid String, or an out-of-range discriminant for a declared Self::enum_type.

Source

pub fn opaque_ptr(self, ty: Type) -> Self

Declare a pointer-struct (opaque-handle) type — a Box-owned Rust value the C side holds as #[repr(C)] struct T { _0: *mut c_void }. Its C struct + <name>_drop destructor are generated. (Mirrors JniExt’s ptr_class.)

Source

pub fn data_struct(self, ty: Type) -> Self

Declare a by-value #[repr(C)] data struct (e.g. Error).

Source

pub fn opaque_data_struct(self, rust_ty: Type, opaque_ty: Type) -> Self

Declare an inline-opaque by-value, plain-data type: the Rust value rust_ty is passed across the C ABI by value (no Box) by transmuting it to/from opaque_ty, an opaque #[repr(C, align(_))] counterpart of identical size+align (typically produced by a size/align probe generator and defined elsewhere). Use this for types that hold no external resource (typically Copy — e.g. a timestamp): consuming one simply moves it out, leaving the source’s bitwise duplicate harmlessly droppable, so no gravestone write-back and no prebindgen_c_runtime::Gravestone impl are needed — only the autogenerated prebindgen_c_runtime::Transmute glue (emitted here) plus a fail-closed const _ size+align equality assert. Contrast Self::opaque_owned_struct for types owning external data.

Source

pub fn opaque_owned_struct(self, rust_ty: Type, opaque_ty: Type) -> Self

Declare an inline-opaque by-value, owns-external-data type: like Self::opaque_data_struct, but for a Rust value that owns external resources (refcounts / heap — e.g. a byte buffer, a sample). Passed by value (no Box) via the opaque_ty transmute counterpart; the converters move values via prebindgen_c_runtime::Transmute and write a gravestone back on consume (safe drop-after-move), exposing an Option<rust_ty> null niche. The consumer must implement prebindgen_c_runtime::Gravestone for opaque_ty — only its logic (rust_gravestone).

Source

pub fn repr_c_struct(self, ty: Type) -> Self

Declare a #[repr(C)], FFI-safe value struct crossed by direct reinterpret (zero-copy) — the C struct’s memory is the Rust struct’s memory. Unlike Self::data_struct (which copies each field, lowering a String to char*), this passes the whole struct by value via prebindgen_c_runtime::Transmute and a &T borrow / impl Fn(&T) callback as a zero-copy *const pointer cast — the value-opaque machinery, but with an auto-generated visible-field #[repr(C)] C mirror (so C reads the fields directly) instead of an opaque blob.

Every field must be FFI-safe: a primitive, a declared Self::enum_type, or an opaque pointer Option<Box<T>> / Box<T> where T is a declared Self::opaque_ptr (rendered *mut t_t; this is how a heap String rides along — Option<Box<String>>string_t *). The source type must be #[repr(C)]; a fail-closed size_of/align_of assert against the generated mirror proves the reinterpret sound at compile time. Call after the manglers are configured (the mirror name is resolved through them). A <base>_drop is generated.

Owned-ness is inferred from the fields: a struct with an opaque-pointer field owns external resources, so a by-value consume cleans the moved-from slot (nulls the owned pointers) to keep the caller’s later _drop a no-op — no .owned() modifier and no double-free footgun. A struct with only scalar/enum fields is plain data (a by-value crossing is a bitwise copy with no write-back). The source type needs Default only if it has a bare Box<T> field (whose gravestone can’t be a NULL pointer); Option<Box<T>> fields are nulled in place.

§Why the spelling is load-bearing here

This is the one position that is exempt from the rule stated on prebindgen_registry::Prebindgensame kind ⇒ same destination-language type — and the exemption is structural rather than a concession. A mirror is not converted; it is reinterpreted from the source struct’s bytes, so its field types are a layout fact. Box<T> is a pointer and T is inline: to C they really are different types, and the size/align assert above would reject a mirror that pretended otherwise. So this path reads the wrapper the model erases — kind rather than unwrapped — on purpose. It is the one place the usual “classify off kind, spell off the syntax” split inverts, and it inverts because the contract is layout rather than surface.

That is also why a wrapper the model erases must not be refused here (prebindgen#230). Option<Box<String>> is how a source crate says “this field is a nullable pointer” — a layout statement a zero-copy mirror is entitled to read, not the source naming a C type. There is no competing spelling to prefer: Option<String> is a 24-byte niche-optimised value with no C representation at all, and declaring one is a hard error naming the field. Rejecting the Box would leave a nullable-pointer field inexpressible.

Source

pub fn assume_c_field_validity(self) -> Self

Accept a Self::repr_c_struct whose mirror has restricted-validity fields, taking responsibility for their bytes.

A repr_c_struct crosses IN by one whole-struct reinterpret, so there is no per-field hook where a C-supplied byte could be normalised or checked before the source struct exists. A field whose Rust type accepts only some bit patterns — bool (0/1) or a declared Self::enum_type (the declared discriminants) — is therefore undefined behaviour the moment C writes anything else into the mirror and hands it back. The generator rejects such a declaration by default (#170 instance 3, #158 instance 3); the real fix is a raw-wire lowering, which does not exist yet.

This modifier is the acknowledgement, not a fix: it says the C side of this binding is trusted to write only in-domain bytes into those fields. It exists so that the audit rejects silently unsound new declarations without removing bindings that already ship. Chain it directly after the Self::repr_c_struct it applies to; the panic message names every field it would cover.

Prefer, in order: move the field into a Self::data_struct (per-field wires, so bool normalises), pass it as a separate scalar parameter, or widen it to an integer the whole domain of which is valid.

Source

pub fn ignore_type(self, ty: Type) -> Self

Mark a #[prebindgen] type as intentionally ignored by this adapter. Root-level modifier: suppresses the registry’s “skipping undeclared” warning for that type without scanning or emitting it.

Source

pub fn base_name(self, base: impl Into<String>) -> Self

Set the base name token of the current declaration (universal modifier): the per-declaration base fed to the name manglers, replacing the auto-derived one. For a type it replaces the mangle_rust_type base (so mangle_type_name/mangle_destructor/mangle_take all see it); for a function it replaces the ident fed to mangle_function; for a callback it is the sole base fed to mangle_callback (replacing the args’ bases — useful to disambiguate e.g. &T from T closures). E.g. .callback(...).base_name("sample_ref") with a |bases| "z_closure_{…}_t" mangler → z_closure_sample_ref_t. Panics if not chained directly after a declaration.

Source

pub fn error(self) -> Self

Mark the current declaration (which must be a Self::data_struct) as an error type: it may appear as the E of a Result<_, E> return. The type must implement From<String>. Panics if the current declaration is not a data struct.

Source

pub fn opaque_error(self, error_ty: Type, message_fn: Ident) -> Self

Declare an opaque error type — one that appears as the E of a Result<_, E> but is not a by-value Self::data_struct (e.g. ZError = Box<dyn Error + Send + Sync>). Such an error is marshalled to C as a char* message obtained by calling message_fn(&err) -> String (e.g. z_error_message); the generated wrapper’s error out-param becomes char **e. The type must implement From<String> (so a fallible input’s internal message can be lifted into it). Root-level modifier (resets the current declaration).

Source

pub fn enum_type(self, ty: Type) -> Self

Declare a C-like (fieldless) enum type to convert. (Mirrors JniExt’s enum_class.)

Crossing into Rust, the caller’s discriminant is validated before any Rust enum is built — an out-of-range one is a fallible-input error, so a non-Result function taking this enum by value needs Self::panic. See the module docs for why the wire is MaybeUninit<mirror>.

Source

pub fn tagged_union(self, ty: Type) -> Self

Declare a data-carrying enum: it crosses by value as a #[repr(C)] enum with payload variants, which cbindgen renders as the idiomatic C tagged union (a tag enum plus a union of the variant bodies). The counterpart of Self::enum_type, which is for the unit-variant-only case a plain C enum can hold. (Mirrors JniExt’s sealed_class.)

Each payload field crosses as its own wire, chosen by the same policy a Self::repr_c_struct field uses, extended with Stringchar *: a scalar passes through, a declared Self::enum_type becomes its C enum, a String becomes a malloc’d char *, and an opaque pointer Option<Box<T>> / Box<T> (with T a declared Self::opaque_ptr) becomes *mut t_t. Anything else is a generation error.

Ownership. The union crosses by value, so when any variant’s payload wire owns memory (char *, an opaque pointer) a typed <base>_drop(t_t *) is generated that frees the active arm — consistent with the existing typed per-pointer drops. A union whose payloads are all plain data needs no drop and gets none.

Validity. Crossing into Rust, the tag a C caller supplied is range-checked before any Rust enum is built — so, exactly like Self::enum_type, a union taken by value is a fallible input, and a function taking one without a Result return needs Self::panic. A data struct carrying a union field inherits that fallibility. See the module docs for the wire this uses and why.

Source

pub fn callback(self, ty: Type) -> Self

Declare a callback signature so its impl Fn(...) parameters resolve and a #[repr(C)] closure struct ({ void *context; call; drop }) is emitted for it. ty must be impl Fn(Args...) + Send + Sync + 'static. Identical signatures share one struct. Sets the declaration cursor, so a following .base_name("...") sets the base fed to mangle_callback (else the args’ bases drive the generated name).

Source

pub fn takeable_param(self, idx: usize) -> Self

Mark argument idx of the current callback declaration as a takeable owned pointer: the C call receives *mut z_x_t (not by value); the callee may take the value (z_x_take moves it out, leaving a gravestone) or just read it; the trampoline drops it after the call (no-op if taken). The arg type must be an inline-opaque type (Self::opaque_owned_struct / Self::opaque_data_struct). Chain after .callback(...) (and any .base_name(...)).

Source§

impl CbindgenBuilder

Source

pub fn build(self) -> Result<Cbindgen, WriteRustError>

State this binding into registry, then resolve it — see JniGenBuilder::build. Read the source, resolve every crossing, and hand back the binding — see JniGenBuilder::build.

Source

pub fn declare_into( &self, registry: RegistryBuilder<()>, ) -> Result<RegistryBuilder<()>, ScanError>

Trait Implementations§

Source§

impl Default for CbindgenBuilder

Source§

fn default() -> CbindgenBuilder

Returns the “default value” for a type. Read more
Source§

impl Prebindgen for CbindgenBuilder

Source§

fn validate(&self, binding: &Building<'_, Self::Metadata>) -> Result<(), String>

Report what this binding left unclaimed. Here because it is the earliest generator-owned hook that sees the model, and it runs exactly where the registry used to print these itself. Moves into CbindgenBuilder::generate once that exists (prebindgen#251 phase E).

consts: None — cbindgen has no const declaration mechanism, so every captured const is re-emitted verbatim and none is ever a skip.

Source§

type Metadata = ()

Adapter-specific extras every resolved converter carries. The resolver copies this from each ConverterImpl it accepts into the matching TypeEntry, so emitter code reads metadata off the registry rather than through a parallel side channel.
Source§

fn source_module(&self) -> Option<&Path>

Absolute path under which the source crate’s items are reachable from the generated file (e.g. zenoh_flat), for adapters that qualify emitted references against one. Drives the default Self::on_const: with a source module available, a named const re-emits as a path-alias to the source item instead of copying its initializer tokens. Default: None.
Source§

fn prerequisites(&self, registry: &Registry<()>, emit: &Emit) -> Vec<Item>

Rust items the adapter’s emitted converters depend on (helper structs, type aliases, runtime-support code). Emitted at the top of the destination file, before all auto-generated converters. Read more
Source§

fn on_function( &self, f: &Function, registry: &Registry<()>, emit: &Emit, ) -> TokenStream

Wrap a #[prebindgen] fn into the destination-language wrapper (e.g. JNI extern "C" fn).
Source§

fn on_struct( &self, _s: &Struct, _registry: &Registry<()>, _emit: &Emit, ) -> TokenStream

Per-struct emission. Typically empty for languages that get everything they need from auto-generated converters.
Source§

fn on_variant( &self, _v: &Variant, _registry: &Registry<()>, _emit: &Emit, ) -> TokenStream

Per-sum emission — an enum whose alternatives carry payloads. Read more
Source§

fn on_enum( &self, _e: &Enum, _registry: &Registry<()>, _emit: &Emit, ) -> TokenStream

Per-enum emission — the fieldless shape, a named set of integers.
Source§

fn post_process_item( &self, _item: &mut Item, _registry: &Registry<Self::Metadata>, _emit: &Emit, )

Final post-processing pass applied to every emitted item right before write. Default: no-op. Read more
Source§

fn validate_resolved( &self, _registry: &Registry<Self::Metadata>, ) -> Result<(), String>

Post-resolve validation boundary — the counterpart of Self::validate that sees the fully resolved registry (converters, plans, metadata). Every artifact writer calls it before writing anything, so an invalid binding fails cleanly — with every problem reported at once — instead of panicking midway after a sibling artifact already reached disk. Deterministic over (self, registry); it runs once per write call, which keeps artifact writes order-independent. Read more
Source§

fn on_const( &self, c: &Constant, _registry: &Registry<Self::Metadata>, emit: &Emit, ) -> TokenStream

Per-const emission. Default: a named const re-emits as a path-alias when Self::source_module is available — initializer tokens are never copied, so a const whose initializer references source-crate internals stays valid in the generated file. An adapter without a source module passes the const through verbatim. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.