Rust Code Generation

paradox generate --rust [--path PATH]

Product Types

Input:

type Person
  name: Text
  age: Integer
  admin: Boolean

Output:

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[derive(serde::Serialize, serde::Deserialize)]
pub struct Person {
    pub name: String,
    pub age: i64,
    pub admin: bool,
}

All fields are pub. Products derive Debug, Clone, PartialEq, Eq, Hash, Serialize, and Deserialize.

Union Types

Input:

union Cheese
  farmers
  cheddar
  brie: Text

Output:

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Cheese {
    Farmers,
    Cheddar,
    Brie(String),
}

Custom Serialize/Deserialize implementations handle the tagged encoding: nullary variants as strings, payload variants as [tag, value] arrays.

Validators

impl Person {
    pub fn validate(&self) -> Result<(), String> {
        let mut errors: Vec<String> = Vec::new();
        if errors.is_empty() { Ok(()) } else { Err(errors.join("; ")) }
    }

    pub fn is_valid(&self) -> bool {
        self.validate().is_ok()
    }
}

Validation rules are emitted as push statements into the errors vector.

Union Helpers

impl Cheese {
    pub fn as_str(&self) -> &'static str {
        match self {
            Cheese::Farmers => "farmers",
            Cheese::Cheddar => "cheddar",
            Cheese::Brie(..) => "brie",
        }
    }
}

Dependencies

Generated Rust code uses:

  • serde with Serialize and Deserialize

  • std::collections::BTreeSet for sets