Skip to main content

ploidy_codegen_rust/
graph.rs

1use std::ops::Deref;
2
3use ploidy_core::{
4    codegen::UniqueNames,
5    ir::{ExtendableView, IrGraph, PrimitiveIrType},
6};
7
8use super::{config::CodegenConfig, naming::CodegenIdentScope};
9
10/// Decorates an [`IrGraph`] with Rust-specific information.
11#[derive(Debug)]
12pub struct CodegenGraph<'a>(IrGraph<'a>);
13
14impl<'a> CodegenGraph<'a> {
15    /// Wraps a type graph with the default configuration.
16    pub fn new(graph: IrGraph<'a>) -> Self {
17        Self::with_config(graph, &CodegenConfig::default())
18    }
19
20    /// Wraps a type graph with the given configuration.
21    pub fn with_config(graph: IrGraph<'a>, config: &CodegenConfig) -> Self {
22        // Decorate named schema types with their Rust identifier names.
23        let unique = UniqueNames::new();
24        let mut scope = CodegenIdentScope::new(&unique);
25        for mut view in graph.schemas() {
26            let ident = scope.uniquify(view.name());
27            view.extensions_mut().insert(ident);
28        }
29
30        // Decorate `DateTime` primitives with the format.
31        for mut view in graph
32            .primitives()
33            .filter(|view| matches!(view.ty(), PrimitiveIrType::DateTime))
34        {
35            view.extensions_mut().insert(config.date_time_format);
36        }
37
38        Self(graph)
39    }
40}
41
42impl<'a> Deref for CodegenGraph<'a> {
43    type Target = IrGraph<'a>;
44
45    fn deref(&self) -> &Self::Target {
46        &self.0
47    }
48}