Skip to main content

CodeGenerator

Struct CodeGenerator 

Source
pub struct CodeGenerator { /* private fields */ }
Expand description

Collects type definitions — from Rust sources or programmatically — and generates TypeScript codec bindings for the rkyv-js runtime.

§Example

use rkyv_js_codegen::{CodeGenerator, codec};

let mut generator = CodeGenerator::new();
generator.add_struct("Point", [("x", codec::f64()), ("y", codec::f64())]);
let code = generator.generate().unwrap();
assert!(code.contains("export const ArchivedPoint = r.struct({"));
assert!(code.contains("export type Point = r.Infer<typeof ArchivedPoint>;"));

Implementations§

Source§

impl CodeGenerator

Source

pub fn add_source_file( &mut self, path: impl AsRef<Path>, ) -> Result<&mut Self, Error>

Parse a Rust source file and extract every type with a marker derive.

§Example
use rkyv_js_codegen::CodeGenerator;

fn main() -> Result<(), rkyv_js_codegen::Error> {
    CodeGenerator::new()
        .add_source_file("src/lib.rs")?
        .write_to_file("generated/bindings.ts")?;
    Ok(())
}
Source

pub fn add_source_str(&mut self, source: &str) -> Result<&mut Self, Error>

Parse Rust source from a string and extract every type with a marker derive.

Source

pub fn add_source_dir( &mut self, path: impl AsRef<Path>, ) -> Result<&mut Self, Error>

Recursively scan a directory for .rs files and extract every type with a marker derive. Files are processed in path order.

Source§

impl CodeGenerator

Source

pub fn new() -> Self

Create a generator with the built-in type and wrapper registrations.

Source

pub fn set_header(&mut self, header: impl Into<String>) -> &mut Self

Replace the header comment of the generated file.

Source

pub fn set_direction(&mut self, direction: Direction) -> &mut Self

Emit unidirectional bindings: Direction::Decode rewrites every rkyv-js import specifier to its /decode counterpart (rkyv-js/lib/X becomes rkyv-js/lib/X/decode), Direction::Encode symmetrically. Factory names and type exports are unchanged; imports of user modules registered via register_external are not rewritten.

Source

pub fn allow_typescript_syntax(&mut self, enabled: bool) -> &mut Self

When false, export type ... = r.Infer<...> lines are dropped so the output is valid plain JavaScript. Defaults to true.

Source

pub fn on_unknown_type(&mut self, mode: OnUnknown) -> &mut Self

Configure how unmappable field types are handled. Defaults to OnUnknown::Error.

Source

pub fn add_marker_path(&mut self, path: impl Into<String>) -> &mut Self

Register an additional derive path that marks types for extraction, alongside the default rkyv::Archive.

Source

pub fn register_external( &mut self, path: impl Into<String>, external: ExternalType, ) -> &mut Self

Register (or replace) an external type mapping for a fully-qualified Rust path.

use rkyv_js_codegen::{CodeGenerator, CodecExpr, ExternalType};

let mut generator = CodeGenerator::new();
generator.register_external(
    "my_crate::MyVec",
    ExternalType::generic1(|t| {
        CodecExpr::call(CodecExpr::import_from("my-pkg/codecs", "myVec"), [t])
    }),
);
Source

pub fn register_with( &mut self, path: impl Into<String>, wrapper: WithWrapper, ) -> &mut Self

Register (or replace) a #[rkyv(with = ...)] wrapper handler.

Source

pub fn unregister_external(&mut self, path: &str) -> &mut Self

Remove an external type mapping (e.g. to disable a builtin).

Source

pub fn add_struct( &mut self, name: impl Into<String>, fields: impl IntoIterator<Item = (impl Into<String>, CodecExpr)>, ) -> &mut Self

Add a struct definition.

Source

pub fn add_enum( &mut self, name: impl Into<String>, variants: impl IntoIterator<Item = EnumVariant>, ) -> &mut Self

Add an enum definition.

Source

pub fn add_alias( &mut self, name: impl Into<String>, target: CodecExpr, ) -> &mut Self

Add a type alias: export const Archived{name} = <expr>;.

Source

pub fn set_archived_name( &mut self, type_name: impl Into<String>, archived_name: impl Into<String>, ) -> &mut Self

Override the archived (exported) name of a type, corresponding to #[rkyv(archived = Name)].

Order-independent: the target type may be added before or after this call. A target that never materializes is reported as DiagnosticKind::UnknownRenameTarget at generate time.

Source

pub fn archived_name_of(&self, type_name: &str) -> Option<String>

The archived (exported) name a type will be emitted under, or None if no type with that name has been added.

Source

pub fn set_format( &mut self, endian: &str, pointer_width: u32, aligned: bool, ) -> &mut Self

Configure the rkyv wire format of the generated bindings.

When the format differs from the default (little/32/aligned), the output declares const FORMAT = r.format({ ... }) with the non-default keys and wraps every exported codec in r.withFormat(<expr>, FORMAT).

Source

pub fn generate(&self) -> Result<String, Error>

Generate the TypeScript bindings.

Validation runs first; every problem is aggregated into a single Error::Codegen.

Source

pub fn write_to_file(&self, path: impl AsRef<Path>) -> Result<(), Error>

Generate the bindings and write them to path.

Trait Implementations§

Source§

impl Debug for CodeGenerator

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for CodeGenerator

Source§

fn default() -> Self

Returns the “default value” for a type. 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, 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.