1use serde::{Deserialize, Serialize};
7use std::fmt;
8
9#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
11pub enum Type {
12 Python(PythonType),
14 C(CType),
16 Rust(RustType),
18 Generic {
20 name: String,
22 bounds: Vec<String>,
24 },
25 Function {
27 params: Vec<Type>,
29 return_type: Box<Type>,
31 },
32 Unknown,
34}
35
36#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
38pub enum PythonType {
39 Int,
41 Float,
43 Str,
45 Bool,
47 List(Box<Type>),
49 Dict {
51 key: Box<Type>,
53 value: Box<Type>,
55 },
56 Tuple(Vec<Type>),
58 Set(Box<Type>),
60 None,
62 Any,
64 Class(String),
66}
67
68#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
70pub enum CType {
71 Void,
73 Char,
75 Int,
77 Long,
79 SizeT,
81 Float,
83 Double,
85 Pointer(Box<CType>),
87 Array {
89 element: Box<CType>,
91 size: Option<usize>,
93 },
94 Struct(String),
96 Union(String),
98 Typedef(String),
100 CPython(CPythonType),
102}
103
104#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
106pub enum CPythonType {
107 PyObject,
109 PyListObject,
111 PyDictObject,
113 PyTupleObject,
115 PyTypeObject,
117 PySsizeT,
119}
120
121#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
123pub enum RustType {
124 Int {
126 bits: IntSize,
128 signed: bool,
130 },
131 Float {
133 bits: u8,
135 },
136 Bool,
138 String,
140 Str,
142 Vec(Box<Type>),
144 HashMap {
146 key: Box<Type>,
148 value: Box<Type>,
150 },
151 Tuple(Vec<Type>),
153 Option(Box<Type>),
155 Result {
157 ok: Box<Type>,
159 err: Box<Type>,
161 },
162 Reference {
164 mutable: bool,
166 inner: Box<Type>,
168 },
169 Custom(String),
171 Unit,
173}
174
175#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
177pub enum IntSize {
178 I8,
180 I16,
182 I32,
184 I64,
186 I128,
188 ISize,
190}
191
192impl Type {
193 #[must_use]
195 #[allow(clippy::unnested_or_patterns)]
196 pub fn is_compatible(&self, other: &Self) -> bool {
197 match (self, other) {
198 (Type::Python(PythonType::List(_)), Type::Rust(RustType::Vec(_)))
202 | (Type::Python(PythonType::Dict { .. }), Type::Rust(RustType::HashMap { .. }))
203 | (Type::C(CType::CPython(CPythonType::PyListObject)), Type::Rust(RustType::Vec(_))) => {
204 true
205 }
206 (a, b) if a == b => true,
208 (Type::Unknown, _) | (_, Type::Unknown) => true,
210 _ => false,
211 }
212 }
213}
214
215impl fmt::Display for Type {
216 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217 match self {
218 Self::Python(py_type) => write!(f, "{py_type}"),
219 Self::C(c_type) => write!(f, "{c_type}"),
220 Self::Rust(rust_type) => write!(f, "{rust_type}"),
221 Self::Generic { name, .. } => write!(f, "{name}"),
222 Self::Function {
223 params,
224 return_type,
225 } => {
226 write!(f, "fn(")?;
227 for (i, param) in params.iter().enumerate() {
228 if i > 0 {
229 write!(f, ", ")?;
230 }
231 write!(f, "{param}")?;
232 }
233 write!(f, ") -> {return_type}")
234 }
235 Self::Unknown => write!(f, "?"),
236 }
237 }
238}
239
240impl fmt::Display for PythonType {
241 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
242 match self {
243 Self::Int => write!(f, "int"),
244 Self::Float => write!(f, "float"),
245 Self::Str => write!(f, "str"),
246 Self::Bool => write!(f, "bool"),
247 Self::List(inner) => write!(f, "list[{inner}]"),
248 Self::Dict { key, value } => write!(f, "dict[{key}, {value}]"),
249 Self::Tuple(types) => {
250 write!(f, "tuple[")?;
251 for (i, t) in types.iter().enumerate() {
252 if i > 0 {
253 write!(f, ", ")?;
254 }
255 write!(f, "{t}")?;
256 }
257 write!(f, "]")
258 }
259 Self::Set(inner) => write!(f, "set[{inner}]"),
260 Self::None => write!(f, "None"),
261 Self::Any => write!(f, "Any"),
262 Self::Class(name) => write!(f, "{name}"),
263 }
264 }
265}
266
267impl fmt::Display for CType {
268 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269 match self {
270 Self::Void => write!(f, "void"),
271 Self::Char => write!(f, "char"),
272 Self::Int => write!(f, "int"),
273 Self::Long => write!(f, "long"),
274 Self::SizeT => write!(f, "size_t"),
275 Self::Float => write!(f, "float"),
276 Self::Double => write!(f, "double"),
277 Self::Pointer(inner) => write!(f, "{inner}*"),
278 Self::Array { element, size } => {
279 if let Some(s) = size {
280 write!(f, "{element}[{s}]")
281 } else {
282 write!(f, "{element}[]")
283 }
284 }
285 Self::Struct(name) => write!(f, "struct {name}"),
286 Self::Union(name) => write!(f, "union {name}"),
287 Self::Typedef(name) => write!(f, "{name}"),
288 Self::CPython(cpy) => write!(f, "{cpy}"),
289 }
290 }
291}
292
293impl fmt::Display for CPythonType {
294 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
295 match self {
296 Self::PyObject => write!(f, "PyObject*"),
297 Self::PyListObject => write!(f, "PyListObject*"),
298 Self::PyDictObject => write!(f, "PyDictObject*"),
299 Self::PyTupleObject => write!(f, "PyTupleObject*"),
300 Self::PyTypeObject => write!(f, "PyTypeObject*"),
301 Self::PySsizeT => write!(f, "Py_ssize_t"),
302 }
303 }
304}
305
306impl fmt::Display for RustType {
307 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
308 match self {
309 Self::Int { bits, signed } => {
310 let prefix = if *signed { "i" } else { "u" };
311 let size = match bits {
312 IntSize::I8 => "8",
313 IntSize::I16 => "16",
314 IntSize::I32 => "32",
315 IntSize::I64 => "64",
316 IntSize::I128 => "128",
317 IntSize::ISize => "size",
318 };
319 write!(f, "{prefix}{size}")
320 }
321 Self::Float { bits } => write!(f, "f{bits}"),
322 Self::Bool => write!(f, "bool"),
323 Self::String => write!(f, "String"),
324 Self::Str => write!(f, "&str"),
325 Self::Vec(inner) => write!(f, "Vec<{inner}>"),
326 Self::HashMap { key, value } => write!(f, "HashMap<{key}, {value}>"),
327 Self::Tuple(types) => {
328 write!(f, "(")?;
329 for (i, t) in types.iter().enumerate() {
330 if i > 0 {
331 write!(f, ", ")?;
332 }
333 write!(f, "{t}")?;
334 }
335 write!(f, ")")
336 }
337 Self::Option(inner) => write!(f, "Option<{inner}>"),
338 Self::Result { ok, err } => write!(f, "Result<{ok}, {err}>"),
339 Self::Reference { mutable, inner } => {
340 if *mutable {
341 write!(f, "&mut {inner}")
342 } else {
343 write!(f, "&{inner}")
344 }
345 }
346 Self::Custom(name) => write!(f, "{name}"),
347 Self::Unit => write!(f, "()"),
348 }
349 }
350}
351
352#[cfg(test)]
353mod tests {
354 use super::*;
355
356 #[test]
357 fn test_python_list_to_rust_vec_compatibility() {
358 let py_list = Type::Python(PythonType::List(Box::new(Type::Python(PythonType::Int))));
359 let rust_vec = Type::Rust(RustType::Vec(Box::new(Type::Rust(RustType::Int {
360 bits: IntSize::I32,
361 signed: true,
362 }))));
363
364 assert!(py_list.is_compatible(&rust_vec));
365 }
366
367 #[test]
368 fn test_c_pylistobject_to_rust_vec_compatibility() {
369 let c_list = Type::C(CType::CPython(CPythonType::PyListObject));
370 let rust_vec = Type::Rust(RustType::Vec(Box::new(Type::Unknown)));
371
372 assert!(c_list.is_compatible(&rust_vec));
373 }
374
375 #[test]
376 fn test_type_display() {
377 let py_list = Type::Python(PythonType::List(Box::new(Type::Python(PythonType::Int))));
378 assert_eq!(py_list.to_string(), "list[int]");
379
380 let rust_vec = Type::Rust(RustType::Vec(Box::new(Type::Rust(RustType::Int {
381 bits: IntSize::I32,
382 signed: true,
383 }))));
384 assert_eq!(rust_vec.to_string(), "Vec<i32>");
385 }
386}