Skip to main content

json_schema_rs/code_gen/
mod.rs

1//! Code generation: schema → source in a target language.
2//!
3//! A [`CodeGenBackend`] takes the intermediate [`JsonSchema`] and returns generated
4//! source as bytes. The CLI matches on the language argument and calls the
5//! appropriate backend (e.g. the Rust backend).
6
7mod error;
8mod rust_backend;
9mod settings;
10
11pub use error::{CodeGenError, CodeGenResult};
12pub use rust_backend::{RustBackend, generate_rust};
13pub use settings::{CodeGenSettings, CodeGenSettingsBuilder, DedupeMode, ModelNameSource};
14
15use crate::json_schema::JsonSchema;
16
17/// Output of Rust code generation: optional shared buffer plus one buffer per input schema.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct GenerateRustOutput {
20    /// When dedupe is enabled and at least one struct is shared across schemas, contains the shared struct definitions. Otherwise `None`.
21    pub shared: Option<Vec<u8>>,
22    /// One UTF-8 Rust source buffer per input schema; length equals number of schemas.
23    pub per_schema: Vec<Vec<u8>>,
24}
25
26/// Contract for a codegen backend: schemas in, [`GenerateRustOutput`] with optional shared buffer and per-schema buffers.
27pub trait CodeGenBackend {
28    /// Generate model source for each schema. Returns shared buffer (if any) and one buffer per schema.
29    ///
30    /// # Errors
31    ///
32    /// Returns [`CodeGenError::RootNotObject`] if a root schema is not an object with properties.
33    /// Returns [`CodeGenError::Io`] on write failure.
34    /// Returns [`CodeGenError::Batch`] with index when one schema in the batch fails.
35    fn generate(
36        &self,
37        schemas: &[JsonSchema],
38        settings: &CodeGenSettings,
39    ) -> CodeGenResult<GenerateRustOutput>;
40}