Skip to main content

spydecy_hir/
types.rs

1//! Type system for Unified HIR
2//!
3//! This module defines the type representation that bridges Python's dynamic typing,
4//! C's static typing, and Rust's ownership system.
5
6use serde::{Deserialize, Serialize};
7use std::fmt;
8
9/// Type representation in the Unified HIR
10#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
11pub enum Type {
12    /// Python built-in types
13    Python(PythonType),
14    /// C types
15    C(CType),
16    /// Rust types (target)
17    Rust(RustType),
18    /// Generic type parameter
19    Generic {
20        /// Type parameter name
21        name: String,
22        /// Bounds/constraints
23        bounds: Vec<String>,
24    },
25    /// Function type
26    Function {
27        /// Parameter types
28        params: Vec<Type>,
29        /// Return type
30        return_type: Box<Type>,
31    },
32    /// Unknown/inferred type
33    Unknown,
34}
35
36/// Python type
37#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
38pub enum PythonType {
39    /// int
40    Int,
41    /// float
42    Float,
43    /// str
44    Str,
45    /// bool
46    Bool,
47    /// list[T]
48    List(Box<Type>),
49    /// dict[K, V]
50    Dict {
51        /// Key type
52        key: Box<Type>,
53        /// Value type
54        value: Box<Type>,
55    },
56    /// tuple[T1, T2, ...]
57    Tuple(Vec<Type>),
58    /// set[T]
59    Set(Box<Type>),
60    /// None
61    None,
62    /// Any (dynamic)
63    Any,
64    /// Custom class
65    Class(String),
66}
67
68/// C type
69#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
70pub enum CType {
71    /// void
72    Void,
73    /// char
74    Char,
75    /// int
76    Int,
77    /// long
78    Long,
79    /// `size_t`
80    SizeT,
81    /// float
82    Float,
83    /// double
84    Double,
85    /// Pointer to type
86    Pointer(Box<CType>),
87    /// Array of type with size
88    Array {
89        /// Element type
90        element: Box<CType>,
91        /// Array size (None for flexible array)
92        size: Option<usize>,
93    },
94    /// Struct
95    Struct(String),
96    /// Union
97    Union(String),
98    /// Typedef
99    Typedef(String),
100    /// `CPython` API types
101    CPython(CPythonType),
102}
103
104/// `CPython` API types
105#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
106pub enum CPythonType {
107    /// `PyObject`*
108    PyObject,
109    /// `PyListObject`*
110    PyListObject,
111    /// `PyDictObject`*
112    PyDictObject,
113    /// `PyTupleObject`*
114    PyTupleObject,
115    /// `PyTypeObject`*
116    PyTypeObject,
117    /// `Py_ssize_t`
118    PySsizeT,
119}
120
121/// Rust type (target)
122#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
123pub enum RustType {
124    /// i8, i16, i32, i64, i128, isize
125    Int {
126        /// Bits (8, 16, 32, 64, 128, size)
127        bits: IntSize,
128        /// Signed or unsigned
129        signed: bool,
130    },
131    /// f32, f64
132    Float {
133        /// Bits (32 or 64)
134        bits: u8,
135    },
136    /// bool
137    Bool,
138    /// String
139    String,
140    /// &str
141    Str,
142    /// Vec<T>
143    Vec(Box<Type>),
144    /// `HashMap`<K, V>
145    HashMap {
146        /// Key type
147        key: Box<Type>,
148        /// Value type
149        value: Box<Type>,
150    },
151    /// (T1, T2, ...)
152    Tuple(Vec<Type>),
153    /// Option<T>
154    Option(Box<Type>),
155    /// Result<T, E>
156    Result {
157        /// Ok type
158        ok: Box<Type>,
159        /// Error type
160        err: Box<Type>,
161    },
162    /// &T
163    Reference {
164        /// Mutable reference
165        mutable: bool,
166        /// Referenced type
167        inner: Box<Type>,
168    },
169    /// Custom type
170    Custom(String),
171    /// Unit type ()
172    Unit,
173}
174
175/// Integer size
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
177pub enum IntSize {
178    /// 8 bits
179    I8,
180    /// 16 bits
181    I16,
182    /// 32 bits
183    I32,
184    /// 64 bits
185    I64,
186    /// 128 bits
187    I128,
188    /// Pointer size
189    ISize,
190}
191
192impl Type {
193    /// Check if type is compatible with another type (for unification)
194    #[must_use]
195    #[allow(clippy::unnested_or_patterns)]
196    pub fn is_compatible(&self, other: &Self) -> bool {
197        match (self, other) {
198            // Python list → Rust Vec
199            // Python dict → Rust HashMap
200            // C PyListObject → Rust Vec
201            (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            // Same types are compatible
207            (a, b) if a == b => true,
208            // Unknown types are always compatible
209            (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}