Crate camo

source ·
Expand description

A crate for representing and creating Rust type definitions as values, i. e. a subset of the Rust abstract syntax. Camo is a library for converting Rust type definitions into corresponding definitions in other languages.

  • Abstract syntax tree - Camo provides a collection of data structures that describe a subset of the Rust syntax. The syntax tree is rooted in core::Container, which types provide via the core::Camo trait.

  • Derive macro - The derive::Camo derive macro automates the work of creating the syntax tree for your type. The macro takes serde attributes into account, ensuring that generated types accurately describe the values that serde would produce.

  • TypeScript backend - The typescript module provides a ready-to-use TypeScript backend. Convert a core::Container into a typescript::Definition, and write it to a file.


Getting started

Add Camo as a dependency:

# `derive` is included by default
cargo add camo
# optionally add the typescript backend
cargo add camo --features typescript

Add the Camo derive macro to your type, and use the generated Camo::camo() implementation:

use camo::Camo;

#[derive(Camo)]
enum BindingType {
    Paperback,
    Hardcover,
}

#[derive(Camo)]
struct Book {
    title: String,
    author: String,
    page_count: usize,
    chapters: Vec<String>,
    binding: BindingType,
}


let book = Book::camo();
println!("{:?}", book);

let binding = BindingType::camo();
println!("{:?}", binding);

With the typescript feature enabled, create a TypeScript definition:

use camo::{
    Camo,
    /* ... */
    typescript::Definition,
};
/* ... */

let book: Definition = book.into();
assert_eq!(
    book.to_string(),
    unindent::unindent("
		interface Book {
			title: string;
			author: string;
			page_count: number;
			chapters: string[];
			binding: BindingType;
		}
	")
);

let binding: Definition = binding.into();
assert_eq!(
    binding.to_string(),
    unindent::unindent(r#"
		type BindingType =
			| "Paperback"
			| "Hardcover";
		"#)
);

See more examples here.

Features

FeatureDefaultDescription
deriveYesEnables the derive::Camo derive macro.
typescriptNoEnables the TypeScript backend, rooted in typescript::Definition.

Re-exports

Traits

  • Describes how to construct a type definition for a given type.

Derive Macros

  • The Camo derive macro, enabled by the derive feature. Derives an implementation of the Camo trait.