Skip to main content

zynk_schema/
types.rs

1use serde::{Deserialize, Deserializer, Serialize};
2use serde_json::Value;
3
4/// Language-neutral type categories used by Zynk generators.
5#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
6#[serde(rename_all = "snake_case")]
7pub enum TypeKind {
8    Primitive,
9    Array,
10    Record,
11    Tuple,
12    Union,
13    Literal,
14    Model,
15    Enum,
16    Any,
17    Void,
18}
19
20/// A reference to a value type in the Zynk API graph.
21#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
22#[serde(rename_all = "camelCase")]
23pub struct TypeRef {
24    pub kind: TypeKind,
25    #[serde(skip_serializing_if = "Option::is_none")]
26    pub name: Option<String>,
27    #[serde(default, skip_serializing_if = "Vec::is_empty")]
28    pub inner: Vec<TypeRef>,
29    #[serde(default)]
30    pub optional: bool,
31    #[serde(default)]
32    pub nullable: bool,
33    #[serde(
34        default,
35        skip_serializing_if = "Option::is_none",
36        deserialize_with = "deserialize_optional_literal_value"
37    )]
38    pub value: Option<Value>,
39}
40
41fn deserialize_optional_literal_value<'de, D>(deserializer: D) -> Result<Option<Value>, D::Error>
42where
43    D: Deserializer<'de>,
44{
45    Ok(Some(Value::deserialize(deserializer)?))
46}
47
48impl TypeRef {
49    pub fn new(kind: TypeKind) -> Self {
50        Self {
51            kind,
52            name: None,
53            inner: Vec::new(),
54            optional: false,
55            nullable: false,
56            value: None,
57        }
58    }
59
60    pub fn primitive(name: impl Into<String>) -> Self {
61        Self {
62            name: Some(name.into()),
63            ..Self::new(TypeKind::Primitive)
64        }
65    }
66
67    pub fn model(name: impl Into<String>) -> Self {
68        Self {
69            name: Some(name.into()),
70            ..Self::new(TypeKind::Model)
71        }
72    }
73
74    pub fn enum_ref(name: impl Into<String>) -> Self {
75        Self {
76            name: Some(name.into()),
77            ..Self::new(TypeKind::Enum)
78        }
79    }
80
81    pub fn array(item: TypeRef) -> Self {
82        Self {
83            inner: vec![item],
84            ..Self::new(TypeKind::Array)
85        }
86    }
87
88    pub fn record(key: TypeRef, value: TypeRef) -> Self {
89        Self {
90            inner: vec![key, value],
91            ..Self::new(TypeKind::Record)
92        }
93    }
94
95    pub fn union(types: Vec<TypeRef>) -> Self {
96        Self {
97            inner: types,
98            ..Self::new(TypeKind::Union)
99        }
100    }
101
102    pub fn literal(value: Value) -> Self {
103        Self {
104            value: Some(value),
105            ..Self::new(TypeKind::Literal)
106        }
107    }
108
109    pub fn any() -> Self {
110        Self::new(TypeKind::Any)
111    }
112
113    pub fn void() -> Self {
114        Self::new(TypeKind::Void)
115    }
116}